MVC pattern

52 results back to index

pages: 420 words: 79,867

Developing Backbone.js Applications by Addy Osmani

Airbnb, anti-pattern, create, read, update, delete, don't repeat yourself, Firefox, full text search, Google Chrome, Khan Academy, Kickstarter, loose coupling, MVC pattern, node package manager, pull request, Ruby on Rails, side project, single page application, web application

Views and Controllers have a slightly different relationship. Controllers facilitate Views’ responses to different user input and are an example of the Strategy pattern. Summary Having reviewed the classical MVC pattern, you should now understand how it allows developers to cleanly separate concerns in an application. You should also now appreciate how JavaScript MVC frameworks may differ in their interpretation of MVC, and how they share some of the fundamental concepts of the original pattern. When reviewing a new JavaScript MVC/MV* framework, remember - it can be useful to step back and consider how it’s opted to approach Models, Views, Controllers or other alternatives, as this can better help you understand how the framework is intended to be used. Further reading If you are interested in learning more about the variation of MVC which Backbone.js uses, please see the MVP (Model-View-Presenter) section in the appendix.

Historically, developers creating desktop and server-class applications have had a wealth of design patterns available for them to lean on, but it’s only been in the past few years that such patterns have been applied to client-side development. In this chapter, we’re going to explore the evolution of the Model-View-Controller (MVC) design pattern and get our first look at how Backbone.js allows us to apply this pattern to client-side development. MVC MVC is an architectural design pattern that encourages improved application organization through a separation of concerns. It enforces the isolation of business data (Models) from user interfaces (Views), with a third component (Controllers) traditionally managing logic, user-input, and coordination of Models and Views. The pattern was originally designed by Trygve Reenskaug while working on Smalltalk-80 (1979), where it was initially called Model-View-Controller-Editor. MVC was described in depth in “Design Patterns: Elements of Reusable Object-Oriented Software” (The “GoF” or “Gang of Four” book) in 1994, which played a role in popularizing its use.

Backbone solves this problem for you, providing a way to cleanly organize code, separating responsibilities into recognizable pieces that are easy to maintain. In “Developing Backbone.js Applications,” I and a number of other experienced authors will show you how to improve your web application structure using the popular JavaScript library, Backbone.js What Is MVC? A number of modern JavaScript frameworks provide developers an easy path to organizing their code using variations of a pattern known as MVC (Model-View-Controller). MVC separates the concerns in an application into three parts: Models represent the domain-specific knowledge and data in an application. Think of this as being a ‘type’ of data you can model — like a User, Photo, or Todo note. Models can notify observers when their state changes. Views typically constitute the user interface in an application (e.g., markup and templates), but don’t have to be.

pages: 671 words: 228,348

Pro AngularJS by Adam Freeman

business process, create, read, update, delete,, Google Chrome, information retrieval, inventory management, MVC pattern, place-making, premature optimization, revision control, Ruby on Rails, single page application, web application

Use AngularJS for more complex single-page web apps, when you have time for careful design and planning and when you can easily control the HTML generated by the server. Understanding the MVC Pattern The term Model-View-Controller has been in use since the late 1970s and arose from the Smalltalk project at Xerox PARC where it was conceived as a way to organize some early GUI applications. Some of the fine detail of the original MVC pattern was tied to Smalltalk-specific concepts, such as screens and tools, but the broader ideas are still applicable to applications, and they are especially well-suited to web applications. The MVC pattern first took hold in the server-side end of web development, through toolkits like Ruby on Rails and the ASP.NET MVC Framework. In recent years, the MVC pattern has been seen as a way to manage the growing richness and complexity of client-side web development as well, and it is in this environment that AngularJS has emerged.

AngularJS applications express functionality through custom elements, attributes, classes, and comments; a complex application can produce an HTML document that contains a mix of standard and custom markup. The style of development that AngularJS supports is derived through the use of the Model-View-Controller (MVC) pattern, although this is sometimes referred to as Model-View-Whatever, since there are countless variations on this pattern that can be adhered to when using AngularJS. I am going to focus on the standard MVC pattern in this book since it is the most established and widely used. In the sections that follow, I explain the characteristics of projects where AngularJS can deliver significant benefit (and those where better alternatives exist), describe the MVC pattern, and describe some common pitfalls. Understanding Where AngularJS Excels AngularJS isn’t the solution to every problem, and it important to know when you should use AngularJS and when you should seek an alternative.

I am going to use the AngularJS convention and use the ng-app attribute and all of the other HTML enhancements that are available. I recommend you do the same, but you can use one of the other approaches if you prefer—or if your development tool chain can’t process nonstandard HTML elements and attributes. 19 Chapter 2 ■ Your First AngularJS App Creating a Data Model AngularJS supports the Model-View-Controller (MVC) pattern, which I describe in Chapter 3. In short, following the MVC pattern requires you to break up the application into three distinct areas: the data in the application (the model), the logic that operates on that data (the controllers), and the logic that displays the data (the views). The data in my to-do application is currently distributed across the HTML elements. The user’s name is contained in the header, like this: ...

Realtime Web Apps: HTML5 WebSocket, Pusher, and the Web’s Next Big Thing by Jason Lengstorf, Phil Leggetter

Amazon Web Services, barriers to entry, don't repeat yourself,, Firefox, Google Chrome, MVC pattern, Ruby on Rails, Skype, software as a service, web application, WebSocket

To make the app simple to maintain and quick to develop, let’s run through how both the scripts and the database should be organized. Model View Controller The industry standard for software design in web applications is the Model-View-Controller (MVC) pattern. There are dozens of PHP frameworks available, and most of them are based on the MVC pattern. Because of its widespread usage and the fact that it’s generally considered the best approach for web applications, you’ll be building this app using the MVC pattern. A BRIEF INTRO TO THE MVC PROGRAMMING PATTERN MVC sounds more complicated than it is. At its core, the concept of MVC is to separate any presentational elements (the view, which is commonly HTML markup) from data (the model, typically information stored in a database) from logic (the controller, which might be PHP code). There are three pretty clear distinctions made in an app using the MVC pattern: 74 • Controllers Classes and code that manipulate data and interpret user input.

In the next chapter, you’ll build the server-side scripts and databases to make the app actually work. 153 Chapter 8 Building the Back End: Part 1 So far in the app development process, most of the efforts have been targeted at the front end of the site. In this chapter, you’ll be building the back-end scripts that will power the front end. Rolling Your Own Simple MVC Framework Before you can build the app, your first task is to build a framework for it. As we determined previously, a Model-View Controller (MVC) framework will be the best option in this particular build. In this section, you’ll build an MVC framework from scratch. This is a complex task, so we’ve built it across two chapters. In this first chapter you’ll set up the framework for the home page and some of the logic behind it, and in Chapter 9 we’ll fill out the MVC structure and complete the application. Determining the Directory Structure A good app starts with proper organization.

@font-face, 91–92 Font selection, 90–91 Footer creation, 94 Form elements submit button, 99 text and e-mail inputs, 95–98 Form handlers and data access methods answer_question() method, 215 array, model and action handler classes, 213 save new questions, 213–214 vote_question() method, 215 nH Header creation, 92–93 Home view design create-a-room form, 100–102 join-a-room form, 102–104 HTML5 active room view attendee-active.html, 129–130 CSS implementation, 133–141 data attributes, 131–133 media queries, 141–143 sections, 131 advantage, 67 application skeleton, 16 closed room view markup, 144–145 media queries, 147 styles, 145–146 design view, 109 <div> element, 68 document creation, 110 file creation, 17–18 fonts assets and styles, 111 @font-face and SAAS, 112–113 project details, 110 new <script> tag, 111 rules, 111–112 footer markup, 114–115 good markup vs. bad markup, 68–69 header markup, 113–114 home page view active and hovered form elements, 126–127 basics form, 121 CSS implementation, 123, 125–126 <form> element, 122 markup, 122 media queries, 127–129 indentation, 68 markup, 67 media queries adjustments, 119 header and footer-different screens, 120–121 screens, 120 need for, 16 opaque class name, 68 presenters room view existing markup rework, 147, 149 media queries updates, 151 tablet and handheld layouts, 152–153 updating CSS, 149, 151 287 ■ Index HTML5 (cont.) styles box-shadow rule, 119 CSS code, 115–116 font styling rules, 117 header and footer, 119 layout rules, 118 working principle, 17 HTML5 WebSocket Technology and Pusher application nervous system, 31 need for, 31 WebSocket API, 30–31 working principle, 32 HTTP, real-time hacks, 5 long-polling, 7 problems with, 8 streaming, 8 nI Is_logged_in() method, 276 n J, K JavaScript and jQuery application brain, 23 need for, 22–23 simple jQuery addition, 23–25 working principle, 23 jQuery effects addition of animated questions, 252 init methods, 251 reorder and animate, answer, 256 room events, handle, 251 stylesheet (animated), 253 testing (animation), 255 testing answers, 257 triggering animation, 254, 256 view of page (attendee & presenter), 258 votes, question, 253, 256 nL Logout() method, 276 n M, N Model-View-Controller (MVC) programming pattern Analogy, Silly, 76 controllers, 74 models, 74 operations, 75 288 steps, 75 views, 75 software design, 74 MySQL application memory, 28 fun with, 28–29 need for, 27 working principle, 28 nO OAuth application gatekeeper, 33 need for, 32–33 working principle, 33 OAuth protocol developer workflow access token request, 262 access token use, 263–264 login link design, 261–262 user authorization, 262 Flickr home page, 260 history, 259 login system design app register with Facebook, 265–266 app’s auth endpoint creation, 279–280 app’s home page creation, 280–281 app testing, 282–283 base OAuth class creation, 266–267 check_login() method, 276 class properties, 267, 269–272 Facebook config file creation, 279 Facebook OAuth child class design, 276–278 get_login_uri() & get_access_token_uri(), 272 is_logged_in() method, 276 logout() method, 276 RWA_OAuth class, 275 save_access_token() and request_uri(), 273–274 save_access_token() method, 276 sign-in to Facebook, 260 n P, Q Photoshop vs.

Backbone.js Cookbook by Vadim Mirgorod

Airbnb, create, read, update, delete,, Firefox, Google Chrome, MVC pattern, QR code, rolodex, Ruby on Rails, web application

Questions You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it. 4 1 Understanding Backbone In this chapter, we will cover the following points: ff Designing an application with the MVC pattern ff Defining business logic with models and collections ff Modeling an application's behavior with views and a router ff Creating an application structure from scratch ff Writing your first Backbone application ff Implementing URL routing in your application ff Extending an application with plugins ff Contributing to the Backbone project Introduction Backbone.js is a lightweight JavaScript framework that is based on the Model-View-Controller (MVC) pattern and allows developers to create single-page web applications. With Backbone, it is possible to update a web page quickly using the REST approach with a minimal amount of data transferred between a client and a server.

You can visit the following links to get acquainted with other usage examples of Backbone.js: Backbone.js was started by Jeremy Ashkenas from DocumentCloud in 2010 and is now being used and improved by lots of developers all over the world using Git, the distributed version control system. In this chapter, we are going to provide some practical examples of how to use Backbone.js, and we will structure a design for a program named Billing Application by following the MVC and Backbone pattern. We will also refer to this structure in the later chapters of this book. Reading this chapter is especially useful if you are new to developing with Backbone.js. If you feel that you're an experienced developer, you can skip this chapter. 6 Chapter 1 Designing an application with the MVC pattern MVC is a design pattern that is widely used in user-facing software, such as web applications. It is intended for splitting data and representing it in a way that makes it convenient for user interaction. To understand what it does, understand the following: ff Model: This contains data and provides business logic used to run the application ff View: This presents the model to the user ff Controller: This reacts to user input by updating the model and the view There could be some differences in the MVC implementation, but in general it conforms to the following scheme: sees User uses Application View Controller updates manipulates Model synchronizes Storage Worldwide practice shows that the use of the MVC pattern provides various benefits to the developer: ff Following the separation of the concerned paradigm, which splits an application into independent parts, it is easier to modify or replace ff It achieves code reusability by rendering a model in different views without the need to implement model functionality in each view ff It requires less training and has a quicker startup time for the new developers within an organization 7 Understanding Backbone To have a better understanding of the MVC pattern, we are going to design a Billing Application.

We will learn how to create outstanding web applications using lightweight JavaScript framework known as Backbone.js and utilizing the superior rendering power of modern browsers. Backbone.js Cookbook contains a series of recipes that provide practical, step-by-step solutions to the problems that may occur during the frontend application development, using an MVC pattern and a REST-style communication. You will learn how to build Backbone applications by utilizing the power of popular Backbone extensions and how to integrate your app with different third-party libraries. You will also learn how to fulfill the requirements of the most challenging tasks. What this book covers Chapter 1, Understanding Backbone, introduces you to an MVC pattern and Backbone.js framework. You will learn how to design Backbone applications in terms of MVC and will be able to create your first Backbone app using models, views, and routers. Chapter 2, Models, helps you learn about Backbone.Model, the main building block of your application, which stores data and provides business logic.

pages: 982 words: 221,145

Ajax: The Definitive Guide by Anthony T. Holdener

AltaVista, Amazon Web Services, business process, centre right, create, read, update, delete, database schema, David Heinemeier Hansson,, Firefox, full text search, game design, general-purpose programming language, Guido van Rossum, information retrieval, loose coupling, MVC pattern, Necker cube, p-value, Ruby on Rails, slashdot, sorting algorithm, web application

You could easily transform this type of pattern into a multitier architecture by adding modules to the design. The importance of this type of design pattern is that it allows you to modify one layer while having only a minimal effect on the other layers. Basic Web and Ajax Design Patterns | 29 Model-View-Controller From here, more complex design patterns evolved from the three-tier pattern that related more to the web application itself. One of them is the Model-View-Controller (MVC) architecture, shown in Figure 2-5. This design pattern separates the user interface, control logic, and data model into three separate components. With MVC, the end user interacts with the user interface through the browser. The controller is in charge of input events from the user interface, and when it receives these events, it calls the model and updates a view according to the user’s action.

Calls Request Business logic Controller Return forward Forward Client Response View Update Uses Model Figure 2-5. The Model-View-Controller design pattern For web applications, the view module is in charge of building the XHTML whenever there is a user request. The controller is all of the navigation code that runs the application, and it can be both client- and server-side scripting. The model is the data access module for the design pattern, handling most data access requests and all business logic. I said most because if there is a user request for an XML response, for example, the view module alone may respond through an XML transformation or something similar. Many of the server-side scripting languages now have frameworks that are based on the MVC design pattern, as you will see in Chapter 4. Rich Internet Applications Rich Internet Applications (RIAs) are Ajax web applications.

On the Web and the desktop, frameworks allow developers to concentrate on the application’s requirements and on meeting deadlines, instead of on the mundane but necessary components that make applications run. With our focus on Ajax web development, it is important to understand the differences among the various frameworks on the Web, not just within a given language, but among languages as well. Earlier in the chapter, we focused on ASP/ASP.NET, PHP, Python, Ruby, and Java, so the frameworks we discuss here will correspond with these languages. Some of these frameworks follow the Model-View-Controller (MVC) design pattern discussed in Chapter 2, and others are just a whole lot of functionality bundled together. Your choice of framework will depend on how structured you want to be. Frameworks and Languages | 57 The .NET Framework The Microsoft .NET Framework ( is positioned to be the development platform for all new Windows applications, on the Web as well as the desktop.

Service Design Patterns: Fundamental Design Solutions for SOAP/WSDL and RESTful Web Services by Robert Daigneau

Amazon Web Services, business intelligence, business process, continuous integration, create, read, update, delete,, fault tolerance, loose coupling, MITM: man-in-the-middle, MVC pattern, pull request, RFC: Request For Comment, Ruby on Rails, software as a service, web application

., CORBA objects) HTTPD: The Apache web server Log4J: A logging utility 277 278 G LOSSARY Project Associated URL Apache ODE: An Orchestration Engine that uses the WS-BPEL standard Apache ServiceMix: An open source ESB Apache Subversion: An open source centralized version control system Apache Struts: An open source framework that implements the MVC pattern Apache Thrift: An RPC framework for cross-language service development originally developed by Facebook and contributed to Apache Apache XMLBeans: An XML data-binding technology ASCII—The American Standard Code for Information Interchange. ASP.NET MVC—A Microsoft framework which implements the MVC pattern. Asynchronous JavaScript and XML (AJAX)—A number of client-side scripting techniques which leverage asynchronous background calls to web services. These techniques promote dynamic and rich web applications, and allow data to be retrieved or updated without having to load an entire web page.

Once the handler has evaluated the request, it selects and instantiates a Command [GoF] object, which encapsulates the web service logic. Several web-oriented frameworks (e.g., Apache Struts, Ruby on Rails, ASP.NET MVC) strive to insulate the developer from the internal complexities of Front Controllers. The Rails framework, for example, lets developers maintain the rules that correlate requests with subcontrollers (i.e., commands) in a separate routing file. In a similar fashion, the ASP.NET MVC framework enables developers to define these rules in configuration files. These practices let developers centralize the routing rules for large and complex applications. Front Controllers that use these techniques work quite well for services with Resource APIs (38) since Commands can usually be selected by simply parsing the requested URI. However, the routing logic becomes more complex Service Controller 86 C HAPTER 4 R EQUEST AND R ESPONSE M ANAGEMENT if different Commands [GoF] must be selected based on the client’s preferred media types.

See Tolerant Reader delivery assurance, Idempotent Retry example, 217–219 structural changes to, 229–230 Messages, ESB canonical set, 222 converting to canonical form, 222–223 Guaranteed Delivery [EIP], 223–224 Message Stores [EIP], 223–224 Orchestration Engines, 224–225 routing, 222 workflow management, 224–225 Microformat, definition, 286 MIDL (Microsoft Interface Definition Library), 287 MIME (Multipurpose Internet Mail Extensions), 287. See also Media type MITM (Man-in-the-Middle Attack), 286 MOM (Message-Oriented Middleware), web service alternative, 8–9 MSMQ (Microsoft Message Queuing), 287 MTOM (Message Transmission Optimization Mechanism), 286 MVC pattern. See ASP.NET MVC N NAck (Negative Acknowledgment), 61 Naming DTOs, 99 Negotiating media preferences. See Media Type Negotiation Network efficiency, Service Descriptors, 177–178 Nondeterministic content models, 287 Normalizer [EIP], 273 I NDEX Notification. See Event Messages [EIP] NUnit, 256–260, 287 O Object composition, 280. See also Service composition Object Relational Mapper (ORM), 287.

pages: 290 words: 119,172

Beginning Backbone.js by James Sugrue

Airbnb, continuous integration, don't repeat yourself, Firefox, Google Chrome, loose coupling, MVC pattern, node package manager, single page application, web application, Y Combinator

Following design patterns results in the improved readability of source code for any architect or developer and allows you to follow proven techniques and structures in application creation. It was just a matter of time before this much-needed discipline was introduced to the JavaScript world where the most widely used and applicable patterns is among the oldest: Model View Controller. The emergence of real objectoriented JavaScript has allowed many frameworks to adopt variations of this pattern. 3 Chapter 1 ■ An Introduction to Backbone.js Model View Controller Model View Controller (MVC) is a pattern that separates the three main areas of any code base that involves a user interface. The origins of this pattern go way back to the days of SmallTalk, a well-respected language that dealt with object-oriented software before its time, back in the 1970s. Since then, it has become a foundation of any good software system.

To take this understanding one step further, let’s illustrate how the MVC pattern would apply to a typical web application that includes a registration form. The view in this case is the HTML form, which presents the user with the ability to input, or edit, data about themselves. The controller is the code that gets invoked when the user clicks Save. The controller will also apply some validation to the data provided in the form. Finally, the model is our data representation of the user. Figure 1-3 represents this in a sequence diagram. User Registration Form (View) Form Logic (Controller) User (Model) Enter data Validate Validation Feedback Display Save Feedback Save Figure 1-3. MVC interaction sequence for a registration form This design pattern provides two key benefits: a separation of concerns and code reuse.

The following snippet of HTML shows how a controller is a user for an HTML page, and the list of people in this controller are iterated through and displayed: <body ng-controller="AddressBookController"> <ul> <li ng-repeat="person in people"> {{}} </li> </ul> Written as a simple JavaScript object, the controller merely needs to allow the data to be retrieved for the view. function AddressBookController($scope) { $scope.people = [ {"name": "James}, {"name": "Sarah}, ]; } Some developers might find that Angular is too opinionated, forcing you to write your application in a particular fashion. Ember Ember.js was released in 2011 as a rebranding of SproutCore 2.0. SproutCore is a slightly older framework, which included its own widget set. In an effort to expose the MVC framework that ran underneath SproutCore, without the need to use these widgets, Ember.js was born. Ember can be downloaded from as illustrated in Figure 1-7. 9 Chapter 1 ■ An Introduction to Backbone.js Figure 1-7. EmberJS web site Ember is another framework that uses a data binding approach, allowing the view to automatically update when the model changes. This data binding works between models too so that if the data in a related object changes, both are kept in sync.

Django Book by Matt Behrens

Benevolent Dictator For Life (BDFL), create, read, update, delete, database schema, distributed revision control, don't repeat yourself,, Firefox, full text search, loose coupling, MITM: man-in-the-middle, MVC pattern, revision control, Ruby on Rails, school choice, slashdot, web application

Those three pieces together – data access logic, business logic, and presentation logic – comprise a concept that’s sometimes called the Model-View-Controller (MVC) pattern of software architecture. In this pattern, “Model” refers to the data access layer, “View” refers to the part of the system that selects what to display and how to display it, and “Controller” refers to the part of the system that decides which view to use, depending on user input, accessing the model as needed. Why the Acronym? The goal of explicitly defining patterns such as MVC is mostly to streamline communication among developers. Instead of having to tell your coworkers, “Let’s make an abstraction of the data access, then let’s have a separate layer that handles data display, and let’s put a layer in the middle that regulates this,” you can take advantage of a shared vocabulary and say, “Let’s use the MVC pattern here.” Django follows this MVC pattern closely enough that it can be called an MVC framework.

Django follows this MVC pattern closely enough that it can be called an MVC framework. Here’s roughly how the M, V, and C break down in Django: M, the data-access portion, is handled by Django’s database layer, which is described in this chapter. V, the portion that selects which data to display and how to display it, is handled by views and templates. C, the portion that delegates to a view depending on user input, is handled by the framework itself by following your URLconf and calling the appropriate Python function for the given URL. Because the “C” is handled by the framework itself and most of the excitement in Django happens in models, templates and views, Django has been referred to as an MTV framework. In the MTV development pattern, M stands for “Model,” the data access layer. This layer contains anything and everything about the data: how to access it, how to validate it, which behaviors it has, and the relationships between the data.

T stands for “Template,” the presentation layer. This layer contains presentation-related decisions: how something should be displayed on a Web page or other type of document. V stands for “View,” the business logic layer. This layer contains the logic that access the model and defers to the appropriate template(s). You can think of it as the bridge between models and templates. If you’re familiar with other MVC Web-development frameworks, such as Ruby on Rails, you may consider Django views to be the “controllers” and Django templates to be the “views.” This is an unfortunate confusion brought about by differing interpretations of MVC. In Django’s interpretation of MVC, the “view” describes the data that gets presented to the user; it’s not necessarily just how the data looks, but which data is presented. In contrast, Ruby on Rails and similar frameworks suggest that the controller’s job includes deciding which data gets presented to the user, whereas the view is strictly how the data looks, not which data is presented.

pages: 190 words: 52,865

Full Stack Web Development With Backbone.js by Patrick Mulder

Airbnb, create, read, update, delete, Debian, Kickstarter, MVC pattern, node package manager, Ruby on Rails, side project, single page application, web application, WebSocket

Developing with JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 vi | Table of Contents Preface Web users demand intuitive and responsive interfaces for tracking their finances and browsing catalogs. Unlike desktop or system applications, where interfaces are mostly built with flavors of C, C++, or Java, today’s web browsers only run JavaScript natively. But the same patterns that make graphical user interfaces successful on different plat‐ forms apply to JavaScript as well. Many communities have formed around experimenting and developing ideas for the model-view-controller (MVC) pattern with JavaScript. It seems like every day there is a new idea about how MVC in web browsers should look and why other ideas won’t work for you. In these turbulent times, the Backbone.js library stands out like a lighthouse. Unlike other approaches to JavaScript MVC, Backbone.js is very small and flexible. However, the main difference of Backbone.js compared to its peers is the Backbone “ecosystem.”

The requirements of Munich Cinema are layout first. Before coding, it is advisable to start with a sketch of an interface on paper. This can help you to structure your software later. We’ll use a basic wireframe for interaction ideas, and we’ll learn how to model the interface with Backbone components. We explore the basic contexts for Backbone views and Backbone models. We also touch on the topic of the model-view-controller (MVC) pattern in Backbone.js. Because Backbone.js has no controller, Backbone’s “MV*” pattern will be explained. The examples in this chapter walk you through the basics of rendering a view, triggering state changes with events, and notifying views to re-render. We build on top of the CommonJS module format from the previous chapter. The following topics will be discussed: • Exploring a UI concept with a wireframe • The separation of data and user interface • The basics of Backbone.Events • Rendering a collection of movies • Viewing updates from events 17 Creating a Wireframe Let’s imagine that we’ve been approached by Munich Cinema, a small, fictional cinema, for help in improving the user experience of its online movie schedule.

Send email to 165 Backbone.Collection, sorting/filtering models with, 61–71 Backbone.js dependencies, 2 distributed application design, 6 fetching local copy of, 4 fetching via content delivery networks, 5 fetching with Node’s package manager, 2 philosophy of, 2, 145 Backbone.Model building a data layer, 26 data resolution, 88 DRYer Views and ViewModels, 46 modal view, 125 sorting, 62 wrapping a data store, 101 Backbone.ModelBinder, 39 Backbone.Obscura, 68, 137 Backbone.Router addressing state, 49–55 orchestrating views, 55–60 overview of, 49 Backbone.Sync, 84, 87 Backbone.View basic events, 31 basic rendering, 37 basic view templates, 41 DRYer Views and ViewModels, 46 filtering, 66 handling UI events, 43 modal view, 125 navbar view, 123 parent/child views, 56 rendering a collection, 42 sorting, 62 templates, 74 Backburner, 76 backend-as-a-service providers, 94, 98 bind function, 159 bindAll function, 159 binding, 39 Bluebird library, 103 Bower, 136 Browserify, 10, 29, 136 browsers development console, 15 DOM representation in, 161 packaging modules for, 9 166 | Index security in, 113 (see also authentication) browsing experience mock-up, 19 Brunch, 136 build automation goals of, 77 Grunt, 77 overview of, 135 scaffolding components, 143 tools to improve productivity, 135 Yeoman, 138 C callbacks, 103 Catero, 136 Cavage, Mark, 100 chaining methods, 161 change events, 28 Chaplin framework, 136, 146 child views, 56 className property, 37 click dummy basic CSS for, 25 basic events, 31 basic HTML for, 24 data layer, 26 preparation overview, 24 Cloudflare, 5 Cocoa API, 22, 5 CoffeeScript, 136 collection helpers, 161 collections filtering, 21, 66 pagination, 68 sorting, 21, 62 transforming, 61 Underscore.js helpers, 158 command line interface (CLI) benefits of, 1 bundling modules from, 10 npm (Node package manager), 2 CommonJS modules benefits of, 8 Browserify, 10 Cartero management system, 136 Express.js and Stitch, 13 require in browsers, 9 comparator function, 62 content delivery network (CDN), 5 controllers, 24, 55 convention-over-configuration, 147 cookies drawbacks of, 115, 118 overview of, 114 session management, 118 user signup, 116 CORS (cross origin resource sharing), 99 createUser method, 116 cross-site request forgery (CSRF), 114 cross-site scripting (XSS), 114 D data binding, 39 building the data layer, 26 controlling access to, 113 (see also authentication) representation with models, 21 transforming with Underscore.js, 158 databases non-relational, 98 NoSQL, 98 relational, 98 wrapping data stores behind an API, 101 debuggers, 15 Decker, Kevin, 145 default properties, 27 dependencies managing with Bower, 136 resolving with main.js file, 141 reusing across projects, 8 Underscore.js, 158–160 Document Object Model (DOM) changing multiple nodes at once, 76 manipulation libraries, 2 node types, 161 statelessness and, 19 DOM nodes attaching/removing event handlers, 162 chaining methods on, 161 operating on directly, 161 preventing event bubbling, 162 selecting with jQuery, 161 types of, 161 DRYer views, 46 E Eastridge, Ryan, 145 ECO (embedded CoffeeScript), 75 event bubbling, 162 event handlers attaching/removing, 162 for UI events, 43 event listeners, 39 events change events, 28 default, 31 handling UI events, 43 sources of, 21, 31 Express.js, 13, 100 extend function, 27, 160 F fetching information asynchronous effects, 92 from hosted backend services, 94 overview of, 83, 87 RESTful web service handling, 84 filtering, 66 Firebase, 94 frameworks benefits of, 145 Chaplin, 146 Giraffe, 146 Junior, 146 Marionette, 146 Rendr, 146 Thorax.js, 146 Function.prototype.bind, 159 functional programming, 158 functions binding context to, 159 get, 28 private, 28 set, 28 sharing across multiple objects, 160 G get function, 28 Giraffe, 146 Grunt, 77 Index | 167 H Handlebars, 76 hashes/hashbangs, 50 Homebrew package manager, 157 HTTP requests basic verbs, 84 cookies, 115 sending from JavaScript, 163 signing, 114 HTTP responses, 102 I index.html, 9 inheritance, 160 isomorphic application design, 97 J JavaScript adding moudles from command line, 143 Ajax, 163 basic abstractions for Backbone.js, 1 debugging, 15 distributed application design, 6 HTTP requests from, 163 jQuery basics of, 160 element selection, 161 event handling, 162 Node.js installation, 157 overview of, 157 promises, 102 Underscore.js benefits of, 158 collections/arrays, 158 functions, 159 objects, 160 utility functions, 160 (see also objects) jQuery Ajax browsing experience mock-up, 19 jQuery API for, 163 basics of, 160 chaining methods, 161 collection helpers, 161 element selection, 161 event handling, 162 168 | Index node wrappers, 161 referencing, 35 JSBin, 5 JSFiddle, 5 JSLint/JSHint, 16 JST (JavaScript Templates), 74 Junior, 146 K key-value pairs data representation with, 21 primary keys, 107 syntax considerations for, 28 L LAMP (Linux-Apache-MySQL-PHP), 98 Layout View, 55 Linux, Node.js installation, 157 M Mac OS Homebrew package manager, 157 Node.js installation, 157 main.js file, 141 Marionette, 146 Mincer, 13 mixin functions, 46 mock-ups APIs, 85 browsing experience, 19 data, 149 wireframes, 19 Mockjax, 149 modal view, 125 model parameter, 29 model-view-controller (MVC) pattern, 22 models (see Backbone models) modules Browserify, 10 bundling from command line, 10 choosing, 8 CommonJS, 8 packaging for browsers, 9 RequireJS, 142 Morell, Jeremy, 68 Munich Cinema example API creation, 100 click dummy preparation basic CSS, 25 basic events, 31 basic HTML, 24 data layer, 26 overview of, 24 current web page, 18 preliminary mock-up, 19 project goals, 18 star rating/voting system, 108 synchronizing state in basic sync and fetch, 87 fetching remote movies, 84 goals of, 83 user interface DRYer views/ViewModels, 46 goals for, 35 handling UI events, 43 interfacing the DOM, 36–43 referencing jQuery, 35 N Navbar view, 123 navigate function, 54 navigation view (navbar), 123 NeXTSTEP operating system, 22 noBackend providers, 94, 98 Node.js installation of, 157 package manager, 2 read-eval-print-loop (REPL), 15 nodes (see DOM nodes) non-relational data stores, 98 npm (Node package manager), 2, 8 O object-relational-mapper (ORM), 98 objects customizing interfaces of, 160 rendering within templates, 160 open-source software, 4 P package managers, 13 pagination, 68 parent views, 56 passwords, 113 (see also authentication) persistence, 101, 108 primary keys, 107 private functions, 28 productivity, improving, 135 (see also workflow automation) promises, 103 proxies, 98 publish-subscribe pattern, 31 pushState(), 50 R React.js, 77 read-eval-print-loop (REPL), 15, 29 relational databases, 98 render function, 37 Rendr, 146 representations in RESTful web services, 85 with models, 21 RequireJS adding modules, 142 benefits of, 140 main.js file, 141 RESTful web services, 84 Restify library, 100 router basics addressing state defining routes, 51 goal of, 49 navigating, 54 preparing, 50 orchestrating views Layout View, 55 parent/child views, 56 overview of, 49 S security, 113 (see also authentication) session management Backbone applications API calls, 118 login dialog, 129 modal view, 125 navbar view, 123 cookies, 118 Index | 169 creating new, 131 logout, 132 set function, 28 signing requests approaches to, 114 benefits of, 114 sorting, 62 Sprockets, 13 state addressing with routers defining routes, 51 goal of, 49 navigating, 54 preparing, 50 authentication and, 131 decoupling from UI benefits of, 22 models and collections, 21 MVC pattern, 22 need for, 19 views, 22 synchronizing basic sync and fetch, 87 fetching remote information, 84 overview of, 83 statelessness, 19, 84 Stitch, 13 T tagName property, 37 template property, 41, 75 templates embedded CoffeeScript, 75 Handlebars, 76 JavaScript Templates, 74 overview of, 73 Thorax.js benefits of, 145 getting started application initialization, 150 build tasks, 147 installation/setup of, 147 mock data preparation, 149 overview of, 146 rendering advanced views, 154 Router setup, 152 Thorax.Collection, 152 TodoMVC demo, 24 tokens, access, 114 170 | Index U Ubuntu, Node.js installation, 157 Underscore.js benefits of, 158 collections/arrays, 158 functions, 159 objects, 160 utility functions, 160 user interface decoupling from state benefits of, 22 models and collections, 21 MVC pattern, 22 need for, 19 views, 22 DRYer views/ViewModels, 46 goals for, 35 handling UI events, 43 interfacing the DOM basic rendering, 37 basic view templates, 41 bindings to data changes, 39 rendering a collection, 42 strategy overview, 36 referencing jQuery, 35 V ViewModels, 46 views advanced view templates, 73 Backbone views, 22 data display management with, 23 DRYer view/ViewModels, 46 Layout View, 55 modal view, 125 MVC pattern, 22 navbar view, 123 parent/child views, 56 updating immediately, 39 welcome view, 59 vulnerabilities cross-site request forgery (CSRF), 114 cross-site scripting (XSS), 114 W Walmart’s shopping cart, 147 welcome view, 59 Windows, Node.js installation, 157 wireframes benefits of, 19 creating, 18 workflow, automation of (see build automation) X benefits of, 136, 138 installation of, 138 running, 139 Z Zepto library, 2, 160 XMLHttpRequest object, 163 Y Yeoman application directory, 140 Index | 171 About the Author Before discovering software development for web applications with Java and Ruby in 2008, Patrick Mulder mainly worked as a software engineer on measurement equip‐ ment and electronic devices.

pages: 779 words: 116,439

Test-Driven Development With Python by Harry J. W. Percival

continuous integration, database schema, Debian, DevOps, don't repeat yourself, Firefox, loose coupling, MVC pattern, platform as a service, pull request, web application, WebSocket

Caching and Performance Testing Find out how to install and configure memcached. Find out how to use Apache’s ab to run a performance test. How does it perform with and without caching? Can you write an automated test that will fail if caching is not enabled? What about the dreaded prob‐ lem of cache invalidation? Can tests help you to make sure your cache invalidation logic is solid? JavaScript MVC Frameworks JavaScript libraries that let you implement a Model-View-Controller pattern on the client side are all the rage these days. To-do lists are one of the favourite demo applica‐ tions for them, so it should be pretty easy to convert the site to being a single-page site, where all list additions happen in JavaScript. Pick a framework—perhaps Backbone.js or Angular.js—and spike in an implementa‐ tion. Each framework has its own preferences for how to write unit tests, so learn the one that goes along with it, and see how you like it.

Send email to 443 code smell, 59, 65, 193, 301 collectstatic, 127–129 comments, 15, 86 commits, 18, 24, 30, 110 configuration management tools, 167 (see also Fabric) context managers, 177 continuous integration (CI), 365–385, cdvii adding required plugins, 368 best practices, 385 configuring Jenkins, 367 debugging with screenshots, 374–378 installing Jenkins, 365 JavaScript tests, 381–384 project setup, 369 Selenium race conditions, 378–381 for staging server test automation, 384 virtual display setup, 372–374 contracts, implicit, 356 cookies, 282, 304 Cross-Site Request Forgery (CSRF) error, 53 CSS (Cascading Style Sheets) framework, 116, 118 (see also Bootstrap) where Bootstrap won’t work, 126 cutting corners, cdvii D data migrations, 428–431 database deployment issues, 132 database location, 141 De-spiking, 251, 285–293 debugging, 21, 52, 249 Ajax, 249 Django debug screen, 146 improving error messages, 57 in continuous integration, 374–378 in JavaScript, 261 staging for, 306–310 switching DEBUG to false, 151 screenshots, for debugging, 374–378 dependencies and deployment, 132 mocking out, 278 virtualenv, 142 deployment, 411 adjusting database location, 141 automating, 152–155, 157–166 danger areas, 132 444 | dependencies and, 132 deploying to live, 163 further reading, 166 key points, 155 to live, 237 migrate, 147 Nginx, 144–146 overview, 152 production-ready, 148–152 vs. provisioning, 140 sample script, 158–161 saving progress, 156 staging, 237, 427 virtualenvs, 142–144 deployment testing, 131–156 domain name for, 135 manual provisioning for hosting, 136–140 overview, 133 design (see layout and style) Django, 4 admin site, 434 apps, 22 authentication in, 245–248, 282 class-based views, 413–421 (see also class-based views) collectstatic, 127–129 custom user model, 293–297 debugging screen, 146, 151 field types, 64 foreign key relationship, 99 forms in (see forms) FormView, 414 functional tests (FT) in (see functional tests/ testing (FT)) and Gunicorn, 148 LiveServerTestCase, 77 management commands, 311–314, 320 migrations, 62–64, 71–74, 237 model adjustment in, 97 model-layer validation, 175–187 Model-View-Controller (MVC), 24 notifications, 433 Object-Relational Mapper (ORM), 60–64 POST requests (see POST requests) as PythonAnywhere app, 410 startproject, 6 static files in, 122 static live server case, 124 template inheritance, 120–121 Index templates, 69–71, 90 test class in, 93 test client, 88, 93 test fixtures, 304 TestCase, 23 unit testing in, 23 URLs in, 24–30, 88, 94, 96, 102, 106, 108, 110 validation quirk, 178 view functions in, 24, 89, 94, 105–108, 326 and virtualenvs, 142–144 Django-BrowserID, 243 documentation, tests as, 296 domain names, 135 Don’t Test Constants rule, 40 double-loop TDD, 47, 323 DRY (don’t repeat yourself), 59, 396 duplicates, eliminating, 58, 211–221 E encryption, 436 end-to-end test (see functional tests/testing (FT)) error messages, 435 error pages, 434 evaluating third-party systems, 252 expected failure, 16, 19 explicit waits, 253 exploratory coding, 195, 242 (see also spiking) F Fabric, 167, 314, 426 configuration, 163 installing, 157 sample deployment script, 158–161 Fake XMLHttpRequest, 268 fixtures in functional tests, 303 in JavaScript tests, 229 on staging server, 311–317 foreign key relationship, 99 forms advanced, 211–223 autogeneration, 195 customising form field input, 194 experimenting with, 194 ModelForm, 195 save methods, 208 simple, 193–210 thin views, 210 tips for, 210 using in views, 198–207 validation testing and customising, 196 Fuctional Core, Imperative Shell architecture, 403 functional tests/testing (FT), 5, 398 automation of (see continuous integration (CI)) cleanup, 77–80, 95, 387 de-duplication, 320 defining, 14 for de-spiking, 251 for duplicate items, 211–221 isolation in, 77–80, 112 in JavaScript, 232–234 for layout and style, 115–118, 148, 173 multiple users, 387, 393–394 pros and cons, 364 in provisioning, 139 running unit tests only, 80 safeguards with, 317 splitting, 171 for staging sites, 132, 133 unittest module, 13–19 vs. unit tests, 22, 303 in views, 223 G generator expression, 39 GET requests, 198, 205 get_user, 291 Git repository setup, 8–11 reset --hard, 118 tags, 166, 238 global variables, 228 greedy regular expressions, 106 Gunicorn, 148–155, 165, 307, 425 H headless browsers, 372 helper functions/methods, 59, 172, 175, 206, 226, 350, 390–393 hexagonal architecture, 403 hosting options, 136 Index | 445 hosting, manual provisioning, 136–140 L Idempotency, 167 implicit waits, 18 in-memory model objects, 352 integrated tests, 351–363, 403 vs. integration test, 342 vs. isolated tests, 362, 398 pros and cons, 364 vs. unit tests, 61 integration tests, 342, 398 integrity errors, 217 isolated tests, 337, 403 (see also test isolation) vs. integrated tests, 362, 398 problems with, 400 pros and cons, 364 layout and style, 115–130 Bootstrap for (see Bootstrap) functional tests (FT) for, 173 large inputs, 125 overview, 130 rows and columns, 122 static files, 122, 127–129 table styling, 126 using a CSS framework for, 118 (see also Bootstrap) using our own CSS in, 126 what to functionally test for, 115 list comprehension, 39 LiveServerTestCase, 77 log messages, 320 logging, 307, 320 logging configuration, 318–320 J M I JavaScript, 225 de-spiking in, 251 debug console, 261 functional test (FT) building in, 232–234 jQuery and Fixtures Div, 229–231 linters, 228 MVC frameworks, 435 onload boilerplate and namespacing, 234 QUnit, 227 running tests in continuous integration, 381–384 spiking with, 242–255 (see also spiking) in TDD Cycle, 234 test runner setup, 226 testing notes, 235 Jenkins Security, 365–384 (see also continuous integration (CI)) adding required plugins, 368 configuring, 367 installing, 365 jQuery, 229–231, 234, 235 JSON fixtures, 304, 320 jumbotron, 125 446 |, 6, 24, 63, 72, 127 Meta, 196 meta-comments, 86 migrate, 147 migrations, 62–64, 71–74, 99, 237, 238 (see also data migrations) database, 427–431 deleting, 99 testing, 427–431 minimum viable application, 13–16, 81 MockMyID, 252 mocks/mocking callbacks, 272–275 checking call arguments, 267 implicit contracts, 356 in JavaScript, 241, 257–275 initialize function test, 258–264 Internet requests, 285–293 for isolation, 338–341 mock library, 301 Mock side_effects, 339 namespacing, 258 in Outside-In TDD, 331 in Python, 278–284 risks, 354 sinon.js, 265 testing Django login, 284 Index model-layer validation, 175–187 changes to test, 216 enforcing, 186 errors in View, 178–182 integrity errors, 217 POST requests, 183–187 preventing duplicates, 212 refactoring, 175, 184–186 unit testing, 177–178 at views level, 218 Model-View-Controller (MVC), 24, 435 ModelForm, 195 Mozilla Persona, 242 MVC frameworks, 24, 435 N namespacing, 258 Nginx, 138, 144–146, 149, 165, 424 nonroot user creation, 137 notifications, 433 O Q QuerySet, 61, 214–216 QUnit, 227, 235, 263, 268 ORM (Object-Relational Mapper), 60–64 Outside-In TDD, 323–335 advantages, 323 controller layer, 326 defined, 335 vs. Inside-Out, 323 model layer, 331–333 pitfalls, 335 presentation layer, 325 template hierarchy, 327–329 views layer, 326–331, 333 P PaaS (Platform-as-a-Service), 136 Page pattern, 390–393, 396 patch decorator, 278, 301 patching, 287 payment systems, testing for, 252 performance testing, 435 Persona, 242, 252, 308–310, 435 PhantomJS, 381–384, 434 Platform-as-a-Service (PaaS), 136 POST requests, 203 processing, 54, 183–187 redirect after, 68 saving to database, 65–67 sending, 51–54, 92 Postgres, 433 private key authentication, 137 programming by wishful thinking, 328, 335 (see also Outside-In TDD) property Decorator, 334 provisioning, 136–140 with Ansible, 423–426 automation in, 166 functional tests (FT) in, 139 overview, 152 vs. deployment, 140 pure unit tests (see isolated tests) py.test, 436 Python adding to Jenkins, 369 PythonAnywhere, 136, 409 R race conditions, 374, 389 Red, Green, Refactor, 58, 89, 170 redirects, 68, 188 refactoring, 40–45 at application level, 183–186 Red, Green, Refactor, 58, 89, 170 removing hard-coded URLs, 187 and test isolation, 341, 362 tips, 190 unit tests, 175 Refactoring Cat, 44, 112 relative import, 161, 173 render to string, 56 REST (Representational Site Transfer), 82 S screenshots, 411 scripts, automated, 132 secret key, 160 Security Engineering (Anderson), 53 security tests, 435 sed (stream editor), 165 Index | 447 Selenium, 4 and JavaScript, 235 best practices, 385 in continuous integration, 378–381 in continuous integration, 372 race conditions, 389 race conditions in, 378–381 upgrading, 86 for user interaction testing, 37–40 wait patterns, 18, 253, 387, 389 waits in, 379–381, 385 server configuration, 155 server options, 137 servers, 136–140 (see also staging server) session key, 304 sessions, 282 Shining Panda, 369 sinon.js, 265, 268, 272 skips, 170 spiking, 242–255, 275 browser-ID protocol, 244 de-spiking, 251 frontend and JavaScript code, 243 logging, 250 server-side authentication, 245–248 with JavaScript, 242 SQLite, 433 staging server creating sessions, 311 debugging in, 306–310 managing database on, 311–306 test automation with CI, 384 staging sites, 132, 133, 135 static files, 116, 122, 132, 149 static folder, site-wide, 256 static live server case, 124 string representation, 215 string substitutions, 103 style (see layout and style) superlists, 8 superusers, 73 system boundaries, 403 system tests, 398 T table styling, 126 template inheritance, 120–121 template inheritance hierarchy, 327 448 | template tag, 53 templates, 40, 55 rendering items in, 69–71 separate, 90 test fixtures, 304, 320 test isolation, 112, 337–363 cleanup after, 359–362 collaborators, 343–345 complexity in, 363 forms layer, 347–350 full isolation, 342 interactions between layers, 355 isolated vs. integrated tests, 362 mocks/mocking for, 338–341 models layer, 351–353 ORM code, 347–351, 364 refactoring in, 341, 362 views layer, 337, 338–347, 353 test methods, 17 test organisation, 190 test skips, 170 test types, 364, 397 test-driven development (TDD) advanced considerations in, 397–404 and developer stupidity, 213 double-loop, 47, 323 further reading on, 404 Inside-Out, 323 iterating towards new design, 86 Java testing in, 234 justifications for, 35–37 new design implementation with, 83–86 Outside-In, 323–335 (see also Outside-In TDD) process flowchart, 83 process recap, 47–50 trivial tests, 36–37 Working state to working state, 86, 110, 112 testing best practices, 397 Testing Goat, 3, 110, 112, cdvii tests, as documentation, 296 thin views, 210 time.sleep, 52 tracebacks, 26, 56 triangulation, 58 U Ubuntu, 137 Index unit tests architectural solutions for, 402 context manager, 177 desired features of, 401 in Django, 23 for simple home page, 21–33 vs. functional tests, 303 vs. functional tests (FT), 22 vs. integrated tests, 61 pros and cons of, 398–401 refactoring, 175 unit-test/code cycle, 31–33 unittest, 134 Unix sockets, 150 Upstart, 151 URLs capturing parameters in, 103 distinct, 102 in Django, 24–30, 88, 94, 96, 102, 106, 108 pointing forms to, 96, 27–30 user authentication (see authentication) user creation, 291 user input, saving, 51–75 user interaction testing, 37–40 user stories, 19, 170 validation, 169 (see also functional tests/testing (FT)) model-layer, 175–187 (see also model-layer validation) VCS (version control system), 8–11 view functions, in Django, 24, 89, 94, 105–108 views layer, 337, 338–347, 353 model validation errors in, 178–182 views, what to test in, 223 virtual displays, 372 Virtualbox, 426 virtualenvs, 132, 142–144 W waits, 18, 253, 379–381, 385, 387, 389 warnings, 17 watch function, 265 websockets, 435 widgets, 194, 196 X Xvfb, 369, 373, 410 Y YAGNI, 82 V Vagrant, 426 Index | 449 About the Author After an idyllic childhood spent playing with BASIC on French 8-bit computers like the Thomson T-07 whose keys go “boop” when you press them, Harry spent a few years being deeply unhappy with economics and management consultancy.

This is a good point for a commit: $ $ $ $ git git git git status # should show you lists/ is untracked add lists diff --staged # will show you the diff that you're about to commit commit -m"Add app for lists, with deliberately failing unit test" As you’ve no doubt guessed, the -m flag lets you pass in a commit message at the com‐ mand line, so you don’t need to use an editor. It’s up to you to pick the way you like to use the Git command line, I’ll just show you the main ones I’ve seen used. The main rule is: make sure you always review what you’re about to commit before you do it. Django’s MVC, URLs, and View Functions Django is broadly structured along a classic Model-View-Controller (MVC) pattern. Well, broadly. It definitely does have models, but its views are more like a controller, and it’s the templates that are actually the view part, but the general idea is there. If you’re interested, you can look up the finer points of the discussion in the Django FAQs. Irrespective of any of that, like any web server, Django’s main job is to decide what to do when a user asks for a particular URL on our site.

Catalyst 5.8: The Perl MVC Framework by Antano Solar John, Jonathan Rockway, Solar John Antano, create, read, update, delete, database schema, Debian,, Firefox, MVC pattern, Ruby on Rails, social intelligence, web application

As each page generates its own HTML, a request from your web designer to update the layout of a page will involve having to dig through your Perl source code (potentially breaking database queries or other logic), just to change some HTML. In addition, whenever you make a change that affects your entire site or application, you'll have to make the change a number of times—once for each page. Similarly, fixing one bug will entail copying the fix to every other place. This is inconvenient, a waste of time, and just plain boring. Catalyst is an open source Perl-based Model-View-Controller (MVC) framework that aims to solve this problem by reorganizing your web application. Catalyst application architecture Rather than making each location that a user may visit as an individual file, we make each location an action inside a Controller class. Catalyst sits in front of each of these Controllers, and when it receives a request, it dispatches the request to the proper action. When an action is called by the dispatcher, it's in a preconfigured environment—all configuration options have been read from a configuration file at the application start, all databases are connected, all parameters from the request have been parsed, and so on.

Catalyst 5.8 The Perl MVC Framework Build scalable and extendable web applications using the Agile MVC framework Antano Solar John BIRMINGHAM - MUMBAI Catalyst 5.8 The Perl MVC Framework Copyright © 2009 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Develop your own coding standard and enforce it automatically CodeIgniter for Rapid PHP Application Development ISBN: 978-1-847191-74-8 Paperback: 260 pages Improve your PHP coding productivity with the free compact open-source MVC CodeIgniter framework! 1. Clear, structured tutorial on working with CodeIgniter 2. Careful explanation of the basic concepts of CodeIgniter and its MVC architecture 3. Using CodeIgniter with databases, HTML forms, files, images, sessions, and email 4. Building a dynamic website quickly and easily using CodeIgniter’s prepared code Please check for information on our titles CodeIgniter 1.7 ISBN: 978-1-847199-48-5 Paperback: 300 pages Improve your PHP coding productivity with the free compact open-source MVC CodeIgniter framework! 1. Clear, structured tutorial on working with CodeIgniter for rapid PHP application development 2. Careful explanation of the basic concepts of CodeIgniter and its MVC architecture 3.

pages: 309 words: 65,118

Ruby by example: concepts and code by Kevin C. Baird

Benevolent Dictator For Life (BDFL), David Heinemeier Hansson, Debian, digital map, Donald Knuth,, Firefox, fudge factor, general-purpose programming language, Guido van Rossum, Larry Wall, MVC pattern, Paul Graham, Perl 6, premature optimization, union organizing, web application

There are several other options that you may want to use, for example, if you haven’t been following along with the text, or if you simply wish to install Rails via some other method. It should be noted, however, that installation as a gem is the recommended way to install Rails. Via Operating System Package Manager Some operating systems’ package managers, such as APT, provide Rails as an installable package. For example, on my Ubuntu system, the command apt-cache search rails shows (among other packages) this result: rails - MVC ruby based framework geared for web application development If you want to use Rails, but you don’t need the most recent bleeding-edge version, and you want to avoid installing RubyGems (for whatever reason), this option may work well for you. From Source As with any free or open source software, there is always the option to install from source. You can browse to for the most recent recommended source tarball.

However, there are situations in which you’d want the code outside of the base Controller. What if you want to implement a common feature across multiple Controllers? Each Controller in a Rails app is a child of the next file we’ll look at (app/controllers/application.rb ), so putting the code in that file is an option. Another option is to use what Rails calls Helpers. Helpers are add-ons to the MVC framework and are similar to the mixin concept we used in to_lang.rb in Chapter 10. At in album_controller.rb , we see from the RDoc that our footer-related code is in a distinct file called app/helpers/ footer_helper.rb, and we can make use of that code within album_controller.rb by simply including the line helper :footer. If we had a Helper at app/helpers/ credit_card_authorization_helper.rb, we could make use of its code in a Controller with the line helper :credit_card_authorization, and so on.

To write a real Rails application, we’ll start filling these empty classes, methods, and HTML stub files with real content, and we’ll also connect to a database to retrieve our information. 234 C h ap te r 1 2 Since our View files are .rhtml files, not just static .html files, we can use techniques similar to those we’ve already seen in the context of mod_ruby to put Ruby code directly into our .rhtml files.2 This will be crucial in the next chapter. Chapter Recap What was new in this chapter? Package management Installing RubyGems Installing, updating, and querying specific gem package files Rails basics Installing Rails The MVC pattern ORM basics Viewing your first Rails application Generating Models and Controllers The index View used as the default View Distinguishing instance methods from class methods with # HTML stub files for Views With just that information, you could create some interesting applications that do a variety of dynamic tasks. However, the real power of Rails stems from its ability to access a database and manipulate content.

pages: 244 words: 20,327

Structuring Backbone Code With RequireJS and Marionette Modules by David Sulc, MVC pattern, web application

You can, however, add other attributes to the view definition. You can see the exercise solution at the end of the book. Download from Wow! eBook <> Displaying a Model Now that we’ve covered displaying static content, let’s move on to displaying content containing data from a model. As you may know, one of Backbone’s selling points is the possibility to structure javascript applications with a Model-View-Controller²⁷ (MVC) pattern. In this pattern, we use socalled models to interact with our data, passing them onto views for rendering the information they contain. You can learn more about models in Backbone’s documentation²⁸. So let’s declare a model within our javascript block, above our view declaration: ContactManager.Contact = Backbone.Model.extend({}); That wasn’t very hard. What did we do? We simply declared a model named Contact and attached it to our ContactManager app.

This is because they have different responsibilities: • templates – are basically HTML – govern “how things should be displayed” (what HTML should be in the view, CSS styles, where data should be displayed, etc.) • views – are javascript objects – take care of “reacting to things that happen” (clicks, keeping track of a model, etc.) This can be somewhat confusing if you’re used to working with an MVC web framework such as Rails. In these, the template and view are typically mixed in the “view” part of the MVC: they get data from the model instances provided by the controller, then generate some HTML that is sent to the browser. What you must keep in mind is that once the HTML is rendered by these frameworks, it never gets modified: a new view may get created by the same controller (e.g. on refresh), but this particular instance will never be modified.

Programming Android by Zigurd Mednieks, Laird Dornin, G. Blake Meike, Masumi Nakamura

anti-pattern, business process, conceptual framework, create, read, update, delete, database schema, Debian, domain-specific language,, fault tolerance, Google Earth, interchangeable parts, iterative process, loose coupling, MVC pattern, revision control, RFID, web application

Finally, let’s delete a record using its ID: sqlite> DELETE FROM video WHERE _id = 1; sqlite> SELECT _id, description FROM videos; 2|Epic Fail Bicycle 3|Epic Fail Wagon 4|Epic Fail Sidewalk 5|Epic Fail Motorcycle SQL and the Database-Centric Data Model for Android Applications Now that you have some basic SQL programming knowledge, we can start thinking about how to put it to use in an Android application. Our goal is to create robust applications based on the popular Model-View-Controller (MVC) pattern that underlies well-written UI programs, specifically in a way that works well for Android. Wikipedia has background information on MVC at One fundamental difference between mobile phone apps and desktop apps is how they handle persistence. Traditional desktop-based applications—word processors, text editors, drawing programs, presentation programs, and so on—often use a document-centric form of the MVC pattern. They open a document, read it into memory, and turn it into objects in memory that form the data model. Such programs will make views for the data model, process user input through their controller, and then modify the data model (Figure 10-1).

A more complex widget—one that can nest other widgets—will have to subclass ViewGroup, which is itself a subclass of View. A very complex widget, perhaps used as an interface tool implemented in several places (even by multiple applications), might be an entire package of classes, only one of which is a descendant of View. This chapter is about graphics, and therefore about the View part of the Model-View-Controller (MVC) pattern. Widgets also contain Controller code, which is good design because it keeps together all the code relevant to a behavior and its representation on the screen. This part of this chapter discusses only the implementation of the View. The implementation of the Controller was discussed in Chapter 7. Concentrating on graphics, then, we can break the tasks of this chapter into two essential parts: finding space on the screen and drawing in that space.

Additionally, a more detailed discussion of MVC in Android will lead us into A “Network MVC”. In order to understand the power of the content provider framework, we need to discuss how cursor update events drive dynamic updates of Android UIs. We think it will help to highlight the often-overlooked communications pathways in the traditional MVC programming pattern, where the following occurs: the View delivers user input events to the Controller; the Controller makes modifications to the Model, and the Model sends update events to the View and to any other observer that registers interest in the Model; the View renders the contents of the Model, usually without directly engaging in application logic, and ideally, just simply iterates over the data in the Model. In Android, the MVC pattern works as shown in Figure 12-3, where explicitly: The Model consists of a content provider and the cursors it returns from its query method, as well as the data it holds in its SQLite tables.

Design Patterns: Elements of Reusable Object-Oriented Software (Joanne Romanovich's Library) by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides

A Pattern Language, Donald Knuth, finite state, loose coupling, MVC pattern, yield curve

Before the Update operation draws the clock face, it checks to make sure the notifying subject is the clock’s subject: An AnalogClock class can be defined in the same way. The following code creates an AnalogClock and a DigitalClock that always show the same time: Whenever the timer ticks, the two clocks will be updated and will redisplay themselves appropriately. Known Uses The first and perhaps best-known example of the Observer pattern appears in Smalltalk Model/View/Controller (MVC), the user interface framework in the Smalltalk environment [KP88]. MVC’s Model class plays the role of Subject, while View is the base class for observers. Smalltalk, ET++ [WGM88], and the THINK class library [Sym93b] provide a general dependency mechanism by putting Subject and Observer interfaces in the parent class for all other classes in the system. Other user interface toolkits that employ this pattern are Interviews [LVC89], the Andrew Toolkit [P+88], and Unidraw [VL90].

CLOS has multi-methods, for example, which lessen the need for a pattern such as Visitor (page 331). In fact, there are enough differences between Smalltalk and C++ to mean that some patterns can be expressed more easily in one language than the other. (See Iterator (257) for an example.) 1.2 Design Patterns in Smalltalk MVC The Model/View/Controller (MVC) triad of classes [KP88] is used to build user interfaces in Smalltalk-80. Looking at the design patterns inside MVC should help you see what we mean by the term “pattern.” MVC consists of three kinds of objects. The Model is the application object, the View is its screen presentation, and the Controller defines the way the user interface reacts to user input. Before MVC, user interface designs tended to lump these objects together. MVC decouples them to increase flexibility and reuse.

The View-Controller relationship is an example of the Strategy (315) design pattern. A Strategy is an object that represents an algorithm. It’s useful when you want to replace the algorithm either statically or dynamically, when you have a lot of variants of the algorithm, or when the algorithm has complex data structures that you want to encapsulate. MVC uses other design patterns, such as Factory Method (107) to specify the default controller class for a view and Decorator (175) to add scrolling to a view. But the main relationships in MVC are given by the Observer, Composite, and Strategy design patterns. 1.3 Describing Design Patterns How do we describe design patterns? Graphical notations, while important and useful, aren’t sufficient. They simply capture the end product of the design process as relationships between classes and objects. To reuse the design, we must also record the decisions, alternatives, and trade-offs that led to it.

pages: 157 words: 35,874

Building Web Applications With Flask by Italo Maia

continuous integration, create, read, update, delete, Debian,, Firefox, full stack developer, minimum viable product, MVC pattern, premature optimization, web application

Request dispatching Secure cookies Sessions Jinja2 templates (tags, filters, macros, and more) With that much, you can handle Ajax requests, browser requests, and user sessions between requests; route HTTP requests to your controllers; evaluate form data; respond to HTML and JSON; and so on. That is nice, but is Flask not an MVC framework? Well, that's arguable. If a web framework does not implement an MVC antipattern, such as handling requests in the view or mixing models and controllers, it could potentially facilitate an MVC, which, in my opinion, is as good as it gets because it does not enforce your application structure. Note Flask is not an MVC framework as it does not implement the model layer, although it does not restrict you in any way if you wish to create your own. If you need a simple, single-file web application that receives a form and gives back an answer, HTML or not, Flask will help you with that, easily.

Flask does not come with bundled functionality in terms of database integration, a forms library, administration interface, or migration tools. You can have these through extensions, which will be discussed soon enough, but they are all external to Flask. If you need these extensions right at the beginning of your project and you don't want to set it up (or can't spare the time to), you might do better with a full-fledged MVC all-in one, low-cohesive, and high-coupling framework such as Django. Now, imagine you need to build a website with a single form, such as a clone, which receives a form and returns the current currency trade values; Flask could help conclude your project really fast. Let's think further. What if you need a specific set of libraries to work together in your project and you don't want the web framework getting in the way; that's another very good scenario for Flask as it gives you the bare minimum and lets you put together everything else you may need.

It is less presumptuous about how your application should look or what you should use to make it available. The BSD licensed package has all this! An introduction to Flask and its features The Flask framework is actually a glue, a very nice one, that sticks together the amazing Werkzeug and Jinja2 frameworks, responsible for answering requests and presenting the output (HTML, maybe). In the MVC architecture, also known as Model-View-Controller, Flask covers C and V. But where is M? Flask does not provide you with an integrated model layer out-of-the-box as that is not actually needed for a web application. If you do need to work with a database, just pick your database solution from the many available and create your own model layer, which is not hard, and be happy! The concept of a micro-framework, with good intentions and made just for Flask, is all about giving you the the smallest (but also the most useful) feature set you need, and one that won't get in the way.

pages: 292 words: 66,588

Learning Vue.js 2: Learn How to Build Amazing and Complex Reactive Web Applications Easily With Vue.js by Olga Filipova

Amazon Web Services, continuous integration, create, read, update, delete,, Firefox, Google Chrome, MVC pattern, pull request, side project, single page application, Skype, source of truth, web application

npm: This is a package manager for JavaScript and allows searching, installing, and managing JavaScript packages. Markdown: This is a human-friendly syntax that allows web writers to write their text without worrying about styles and HTML tags. Markdown files have a .md extension. Model View ViewModel (MVVM): This is an architectural pattern whose central point is a ViewModel that acts as a bridge between the View and the data model, allowing the data flow between them. Model View Controller (MVC): This is an architectural pattern. It allows separating Views from Models and from the way that information flows from Views to Models, and vice versa. One-way data binding: This is the type of data binding where the changes in the data model are automatically propagated to the View layer, but not vice versa. Rapid prototyping: In the Web, this is a technique of easily and rapidly building the mockups of the user interface, including some basic user interaction.

I am looking forward for the next chapter to see what's next! When someone who you love very much tells you this, you just want to move on and continue your amazing writing. Thank you very much for this! About the Reviewer Bogdan-Alin Bâlc is a team lead with a passion for frontend technologies. He has worked with JavaScript for the past 8 years, from the emergence of jQuery and Ajax to modern full-fledged MVC frameworks. When he's not looking into some new JS challenge, he spends time with his friends, playing games and watching sports. For support files and downloads related to your book, please visit Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at and as a print book customer, you are entitled to a discount on the eBook copy.

pages: 537 words: 82,938

Rust Programming by Example by Guillaume Gomez, Antoni Boucher

Debian, MVC pattern, type inference, web application

Also, add the following to Cargo.toml: gdk-pixbuf = "^0.3.0" id3 = "^0.2.0" Next, we'll create a new module to contain this new widget: mod playlist; We'll start this module by adding a bunch of use statements: use std::path::Path; use gdk_pixbuf::{InterpType, Pixbuf, PixbufLoader}; use gtk::{ CellLayoutExt, CellRendererPixbuf, CellRendererText, ListStore, ListStoreExt, ListStoreExtManual, StaticType, ToValue, TreeIter, TreeModelExt, TreeSelectionExt, TreeView, TreeViewColumn, TreeViewColumnExt, TreeViewExt, Type, WidgetExt, }; use id3::Tag; These will be followed by some constants: const THUMBNAIL_COLUMN: u32 = 0; const TITLE_COLUMN: u32 = 1; const ARTIST_COLUMN: u32 = 2; const ALBUM_COLUMN: u32 = 3; const GENRE_COLUMN: u32 = 4; const YEAR_COLUMN: u32 = 5; const TRACK_COLUMN: u32 = 6; const PATH_COLUMN: u32 = 7; const PIXBUF_COLUMN: u32 = 8; const IMAGE_SIZE: i32 = 256; const THUMBNAIL_SIZE: i32 = 64; The *_COLUMN constant represents the column we'll show in the playlist. The last one, PIXBUF_COLUMN, is a bit special: it will be a hidden column holding the cover of a bigger size so that we can show this image in the cover widget we created earlier. Next, we'll create a new structure to hold the widget and its model: pub struct Playlist { model: ListStore, treeview: TreeView, } The MVC pattern For the list and tree widgets, GTK+ follows the MVC pattern. MVC stands for Model-View-Controller. Now we can add a constructor for our playlist: impl Playlist { pub fn new() -> Self { let model = ListStore::new(&[ Pixbuf::static_type(), Type::String, Type::String, Type::String, Type::String, Type::String, Type::String, Type::String, Pixbuf::static_type(), ]); let treeview = TreeView::new_with_model(&model); treeview.set_hexpand(true); treeview.set_vexpand(true); Self::create_columns(&treeview); Playlist { model, treeview, } } } The gtk::ListStore type is a model to represent the data as a list.

Table of Contents Preface Who this book is for What this book covers To get the most out of this book Download the example code files Download the color images Conventions used Get in touch Reviews Basics of Rust Getting to know Rust Installing Rust Windows Linux/Mac Test your installation Documentation and reference Main function Variables Built-in data types Integer types Floating-point types Boolean type Character type Control flow Writing a condition Creating while loops Creating functions Creating structures References Clone types Copy types Mutable references Methods Constructors Tuples Enumerations Pattern matching Irrefutable patterns Traits Default methods Associated types Rules Generics The Option type Arrays Slices For loops Macros Multiple pattern rules Repetitions Optional quantifier Summary Starting with SDL Understanding Rust crates Installing SDL2 Installing SDL2 on Linux Installing SDL2 on Mac Installing SDL2 on Windows Windows with Build Script Windows (MinGW) Windows (MSVC) Setting up your Rust project Cargo and The documentation Back to our Cargo.toml file Rust's modules Tetris Creating a window Drawing Playing with Options Solution Loading images Installing SDL2_image on Mac Installing SDL2_image on Linux Installing SDL2_image on Windows Playing with features Playing with images Handling files Saving/loading high scores Iterators Reading formatted data from files Summary Events and Basic Game Mechanisms Writing Tetris Tetrimino Creating tetriminos Generating a tetrimino Rotating a tetrimino Tetris struct Interacting with the game map SDL events Score, level, lines sent Levels and lines sent Highscores loading/overwriting Summary Adding All Game Mechanisms Getting started with game mechanisms Rendering UI Rendering initialization Rendering Playing with fonts Install on OS X Install on Linux Other system/package manager Loading font Summary Creating a Music Player Installing the prerequisite Installing GTK+ on Linux Installing GTK+ on Mac Installing GTK+ on Windows Creating your first window Closure Preventing the default behavior of an event Creating a toolbar Stock item Improving the organization of the application Adding tool button events Lifetime Ownership Containers Types of containers The Box container Adding a playlist The MVC pattern Opening MP3 files Reference-counting pointer ID3— MP3 metadata Opening files with a file dialog Deleting a song Displaying the cover when playing a song Summary Implementing the Engine of the Music Player Installing the dependencies Installing dependencies on Linux Installing dependencies on Mac Installing dependencies on Windows Decoding MP3 files Adding dependencies Implementing an MP3 decoder Getting the frame samples Playing music Event loop Atomic reference counting Mutual exclusion Send trait Sync trait Lock-free data structures Playing music Mutex guard RAII Using the music player Pausing and resuming the song Interior mutability Showing the progression of the song Improving CPU usage Condition variable Showing the song's current time Loading and saving the playlist Saving a playlist Loading a playlist Using gstreamer for playback Summary Music Player in a More Rusty Way with Relm Reasons to use relm instead of gtk-rs directly State mutation Asynchronous user interface Creating custom widgets Creating a window with relm Installing Rust nightly Widget Model Messages View Properties Events Code generation Update function Adding child widgets One-way data binding Post-initialization of the view Dialogs Other methods Playlist Model parameter Adding a relm widget Communicating between widgets Communicating with the same widget Emit With different widgets Handle messages from a relm widget Syntax sugar to send a message to another relm widget Playing music Computing the song duration Using relm on stable Rust Relm widgets data binding Summary Understanding FTP File transfer protocol Introduction to FTP Implementing simple chunks of commands Starting with basics Commands implementation Implementing the SYST command Implementing the USER command Implementing the NOOP command Implementing the PWD command Implementing the TYPE command Implementing the LIST command Implementing the PASV command Back to the LIST command Implementing the CWD command Implementing the CDUP command Full implementation of the LIST command Implementing the MKD command Implementing the RMD command Testing it Summary Implementing an Asynchronous FTP Server Advantages of asynchronous IO Disadvantages of asynchronous IO Creating the new project Using Tokio Tokio event loop Using futures Handling errors Unwrapping Custom error type Displaying the error Composing error types The ?

And, finally, we can call this function from the click event handler of the play button: let playlist = self.playlist.clone(); let cover = self.cover.clone(); self.toolbar.play_button.connect_clicked(move |_| { if play_button.get_stock_id() == Some(PLAY_STOCK.to_string()) { play_button.set_stock_id(PAUSE_STOCK); set_cover(&cover, &playlist); } else { play_button.set_stock_id(PLAY_STOCK); } }); Here's the result after adding a song and clicking play: Figure 5.9 Summary This chapter started by showing you how to install GTK+ on your machine. You then learned how to use gtk-rs to create windows, to manage user events like mouse click, to add different types of widgets to your window, to arrange your widgets with containers, and to show beautiful icons with stock items. You also saw how to use complex GTK+ widgets that use the MVC pattern. You also gained more knowledge of Rust in the areas of closures, lifetimes, and ownerships, which are key concepts in this language. Finally, you learned how to extract the metadata of an MP3 file by getting the ID3 tags. In the next chapter, we'll improve the music player so that it can actually play a song. Implementing the Engine of the Music Player In the previous chapter, we implemented the user interface of the music player, but it is unable to play any music.

pages: 180 words: 37,187

AngularJS Essentials by Rodrigo Branas

Firefox, MVC pattern, node package manager, single page application, web application

After 3 weeks and only 1.500 lines of code, he delivered the project! Nowadays, the framework is used by more than 100 projects just at Google, and it is maintained by its own internal team, in which Miško takes part. The name of the framework was given by Adam Abrons, and it was inspired by the angle brackets of the HTML elements. [8] Chapter 1 Architectural concepts It's been a long time since the famous Model-View-Controller (MVC) pattern started to gain popularity in the software development industry and became one of the legends of the enterprise architecture design. Basically, the model represents the knowledge that the view is responsible for presenting, while the controller mediates the relationship between model and view. However, these concepts are a little bit abstract, and this pattern may have different implementations depending on the language, platform, and purpose of the application.

^ parameter 45 A AngularJS about 7 architectural concepts 9 built-in services 76 data handling 53 history 8 service, creating 69 URL 12, 120 AngularJS $compile documentation URL 47 AngularJS animation about 48 ngClass directive, animating 50 ngHide directive, animating 50 ngRepeat directive, animating 49 working 48 AngularJS built-in directives ngApp directive 19, 20 ngBind directive 21 ngBindHtml directive 22 ngClass directive 27 ngClick directive 25, 26 ngController directive 20 ngDisable directive 26 ngHide directive 31 ngIf directive 31 ngInclude directive 31 ngModel directive 24 ngOptions directive 28-30 ngRepeat directive 22, 23 ngShow directive 30 ngStyle directive 30 other directives 26 using 19 AngularJS built-in services $timeout service 96 asynchronous implementation 98 backend communication 76 logging strategy 96 AngularJS components $httpBackend service, mocking with 132-139 controller 126 directives 129 filters 128 service 125 testing 124 test, running with Karma 140 application organization refactoring 32 architectural concepts, AngularJS controller 9 framework, setting up 10, 11 model 9 view 9 array, orderBy filter 59 Asynchronous JavaScript and XML (AJAX) 79, 80 autoWatch property 142 B backend communication about 76 AJAX 79 caching mechanism 85 headers 84 HTTP 76 HTTP facade, creating 82 interceptors 85, 86 JSON 76, 77 REST method 77 best practices, scope object 106 bootstrapping process 18 Bower about 156 cache 158 installation 156 packages, managing with 156 used, for installing packages 157 used, for searching packages 156 bower.json file 157 C cache, Bower 158 caching mechanism 85 callback 98 code organization about 12, 13 ways 13 code organization, ways domain style 15 inline style 13 specific style 14 stereotyped style 13, 14 cohesion 67 Common Gateway Interface (CGI) 7 compile function used, for creating directive 47 configuration, Grunt 146 constants 74 Content Delivery Network (CDN) URL 12 controller, AngularJS components testing 126 controller function used, for creating directive 46 coupling 68 currency filter 56 D date filter 56 deferred API about 100 notify(value) function 100 reject(reason) function 100 resolve(result) function 100 dependency injection 68, 69 directive 18, 19 directive configuration compile function, using 47 controller function, using 46 link function, using 43 replace property, using 36 require property, using 44-46 restrict property, using 37, 38 scope property, using 38-41 template property, using 35 templateUrl property, using 36 transclude property, using 42 Directive Definition Object 34 directives, AngularJS components compiling 130 creating 18, 34 digest cycle, invoking 130 element, creating 130 [ 160 ] link function, calling with scope 130 testing 129 directive scope configuring 38 distribution package creating, for performance improvement 147 creating, for quality improvement 147 creating, for security improvement 147 grunt-connect plugin, installing 153-155 grunt-contrib-clean plugin, installing 147, 148 grunt-contrib-concat plugin, installing 149 grunt-contrib-copy plugin, installing 150 grunt-contrib-jshint plugin, installing 148 grunt-contrib-uglify plugin, installing 149 grunt-karma plugin, installing 151 Document Object Model (DOM) 17 domain style 15 E expression about 53, 54 interpolation 53 F factory function about 70 used, for creating services 70-73 filters about 55 creating 61 interacting, with expression 55 testing 128 using, in other components 60 filter usage, with expression about 56, 57 currency filter, using 55, 56 date filter, using 56 json format, using 57 limitTo filter, using 58 lowercase filter, using 58 number filter, using 58 orderBy filter, using 59, 60 uppercase filter, using 60 form validation $dirty object 65 $error object 65 $pristine object 65 about 62 basic validation, adding 63, 64 first form, creating 62 framework, AngularJS setting up 10-12 function, orderBy filter 59 G GET method 76 Git repository 156, 157 Google Web Toolkit (GWT) 8 Grunt configuration 146 distribution package, creating 147 installing 146 workflow, automating with 145 workflow, executing 155 grunt-connect plugin installing 153-155 grunt-contrib-clean plugin installing 147, 148 grunt-contrib-concat plugin installing 149 grunt-contrib-copy plugin installing 150 grunt-contrib-jshint plugin installing 148 grunt-contrib-uglify plugin installing 149 Gruntfile.js file 146 grunt-karma plugin installing 151 H headers, backend communication 84, 85 HyperText Markup Language (HTML) 7 HyperText Transfer Protocol (HTTP) 7 I Immediately-Invoked Function Expression (IIFE) 71 inline style 13 installation, Bower 156 [ 161 ] installation, Grunt 146 installation, grunt-connect plugin 153-155 installation, grunt-contrib-clean plugin 147, 148 installation, grunt-contrib-concat plugin 149 installation, grunt-contrib-copy plugin 150 installation, grunt-contrib-uglify plugin 149 installation, grunt-karma plugin 151 installation, packages Bower used 157 interceptors httpTimestampInterceptor 85 httpUnauthorizedInterceptor parameter 86 request interceptor 85 response interceptor 86 J Jasmine 121 Jasmine testing framework about 122-124 URL 122 JavaScript Object Notation (JSON) 57, 77 jQuery library URL 104 JSHint 121, 147 JSLint 121, 147 K Karma about 140 configuring 141 configuring, browser options 141 installing, prerequisites 140 tests, running with 140-142 L limitTo filter 58 link function attrs 43 calling, with scope 130 ctrl 43 element 43 scope 43 transcludeFn 43 used, for creating directive 43 logging strategy levels 96 low cohesion application 67 lowercase filter 58 M Mocha, Karma 141 Model-View-Controller (MVC) pattern 9 Model-View-Whatever (MVW) 9 modules creating 115 parking application 115, 119, 120 search 115, 118, 119 UI 115-118 N nested controllers, ngController directive 21 new operator 74 ngApp directive 19, 20 ngBind directive 21 ngBindHtml directive 22 ngClass directive about 27 animating 50 ngClick directive 25, 26 ngController directive about 20 nested controllers 21 ngDisable directive 26 ngHide directive about 31 animating 50 ngIf directive 31 ngInclude directive 31 ngModel directive 24 ngOptions directive 28-30 ngRepeat directive about 22, 23 animating 49 ngShow directive 30 ngStyle directive 30 NodeJS 146 Node Package Manager (npm) 141, 146 number filter 58 [ 162 ] O one-way data binding mechanism 103 orderBy filter about 59, 60 array 59 function 59 string property 59 P package.jsonfile file 146, 154, 155 packages installing, with Bower 157 managing, with Bower 156 searching, with Bower 156 using 157 parking application module 115, 119, 120 Plain-Old-JavaScript-Object (POJO) 9 POST method 77 prerequisites, Karma installation NodeJS 140 Node Package Manager(npm) 141 promise API catch(errorCallback) 101 finally(callback) 101 then (successCallback, errorCallback, notifyCallback) 101 provider used, for creating services 75, 76 Q QUnit, Karma 141 R recommended modules, AngularJS 120 replace property used, for creating directive 36 Representational State Transfer (REST method) 77 RequireJS, Karma 141 require property used, for creating directive 44-46 restrict property used, for creating directive 37, 38 Revealing Module Pattern 70, 72, 122 RSpec 122 run function 112 S scope object about 103 best practices 106-110 broadcasting 111, 112 scope property used, for creating directive 38-41 search module 115, 118, 119 services, AngularJS components creating 69 creating, with AngularJS service 74 creating, with factory function 70-73 creating, with provider 75, 76 testing 125 single-page application.

pages: 59 words: 12,801

The Little Book on CoffeeScript by Alex MacCaw

Firefox, MVC pattern, node package manager, web application, Y2K

Additional Libraries Stitch and Eco aren’t the only libraries you can use for creating CoffeeScript and Node applications. There are a variety of alternatives. For example, when it comes to templating, you can use Mustache, Jade, or write your HTML in pure CoffeeScript using CoffeeKup. As for serving your application, Hem is a great choice, supporting both CommonJS and NPM modules and integrating seamlessly with the CoffeeScript MVC framework Spine. node-browsify is another similar project. Or if you want to go lower level with express integration, there’s Trevor Burnham’s connect-assets You can find a full list of CoffeeScript web framework plug-ins on the project’s wiki. Chapter 5. The Good Parts JavaScript is a tricky beast, and knowing the parts that you should avoid is just as important as knowing about the parts you should use.

pages: 628 words: 107,927

Node.js in Action by Mike Cantelon, Marc Harter, Tj Holowaychuk, Nathan Rajlich

Amazon Web Services, Chris Wanstrath, create, read, update, delete, Debian,, Firefox, Google Chrome, MITM: man-in-the-middle, MVC pattern, node package manager, p-value, pull request, Ruby on Rails, web application, WebSocket

In this chapter, you’ll focus exclusively on templating, learning how to use three popular template engines and how to use templating to keep any web application’s code clean by separating logic from presentation markup. If you’re familiar with templating and the model-view-controller (MVC) pattern, you can skim through to section 11.2, where you’ll start learning about the template engines we’ll detail in this chapter, which include Embedded JavaScript, Hogan, and Jade. If you’re not familiar with templating, keep reading—we’ll explore it conceptually in the next few sections. 11.1. Using templating to keep code clean You can use the model-view-controller (MVC) pattern to develop conventional web applications in Node as well as with nearly every other web technology. One of the key concepts in MVC is the separation of logic, data, and presentation. In MVC web applications, the user will typically request a resource from the server, which will cause the controller to request application data from the model and then pass the data to the view, which will finally format the data for the end user.

In MVC web applications, the user will typically request a resource from the server, which will cause the controller to request application data from the model and then pass the data to the view, which will finally format the data for the end user. This view portion of the MVC pattern is often implemented using one of various templating languages. When an application uses templating, the view will relay selected values, returned by the model, to a template engine, and specify what template file should define how to display the provided values. Figure 11.1 shows how templating logic fits into the overall architecture of an MVC application. Figure 11.1. The flow of an MVC application and its interaction with the template layer Template files typically contain placeholders for application values as well as HTML, CSS, and sometimes small bits of client-side JavaScript to do things like display third-party widgets, such as Facebook’s Like button, or to trigger interface behavior, such as hiding or revealing parts of the page.

leave method lengthAbove method level option lib directory, 2nd libuv library Lightweight Directory Access Protocol (LDAP) limit() middleware overview why needed wrapping for greater flexibility link command Linode list command listen function, 2nd listeners, 2nd lists little-endian LLEN command locally installing packages locals argument log method, 2nd logging requests customizing formats options for overview lookup directory in Express framework lpush command lrange command LSB (least significant byte) M main key make package malloc() function map filter mapping file extensions in Express master branch maxAge argument, 2nd Memcached memLevel option memory storage MemoryStore object message property method property, 2nd, 3rd, 4th, 5th :method token methodOverride() middleware accessing original req.method property overview Microsoft Azure SDK for Node.js mime module, 2nd MIME types, 2nd, 3rd, 4th, 5th mixins defined in Jade mkdir() function model-view-controller pattern. See MVC. modes, for ansi.js module module.exports property, 3rd overview vs. exports object Mongoose adding task connecting to deleting documents registering schema searching for documents updating documents most significant byte. See MSB. move() function moving files with fs module MSB (most significant byte) multiuser applications and file-based storage Mustache template language. See Hogan. mv command MVC (model-view-controller) pattern and templates application flow N namespaces NaN (not a number) value navigation in built-in debugger in Node Inspector nesting callbacks NET module netcat command new keyword next argument, 2nd, 3rd next command next function, 2nd, 3rd, 4th ngen tool Nginx, 2nd Nimble node command Node Knockout Node Package Manager (npm), 2nd NODE_ENV environment variable, 2nd, 3rd NODE_PATH environment variable node_redis module, 2nd node-cgi module node-elf module node-inspector command Nodejitsu, 2nd node-mongodb-native Google Group node-mongodb-native module node-mysql module node-postgres module node-tar module nodeunit installing overview testing applications with non-blocking I/O model nonparallel testing not a number.

The Data Journalism Handbook by Jonathan Gray, Lucy Chambers, Liliana Bounegru

Amazon Web Services, barriers to entry, bioinformatics, business intelligence, carbon footprint, citizen journalism, correlation does not imply causation, crowdsourcing, David Heinemeier Hansson, eurozone crisis, Firefox, Florence Nightingale: pie chart, game design, Google Earth, Hans Rosling, information asymmetry, Internet Archive, John Snow's cholera map, Julian Assange, linked data, moral hazard, MVC pattern, New Journalism, openstreetmap, Ronald Reagan, Ruby on Rails, Silicon Valley, social graph, SPARQL, text mining, web application, WikiLeaks

Things changed thanks to the development of two free/open source rapid development frameworks: Django and Ruby on Rails, both of which were first released in the mid-2000s. Django, which is built on top of the Python programming language, was developed by Adrian Holovaty and a team working in a newsroom—the Lawrence Journal-World in Lawrence, Kansas. Ruby on Rails was developed in Chicago by by David Heinemeier Hansson and 37Signals, a web application company. Though the two frameworks take different approaches to the “MVC pattern,” they’re both excellent and make it possible to build even very complex web applications very quickly. They take away some of the rudimentary work of building an app. Things like creating and fetching items from the database, and matching URLs to specific code in an app are built into the frameworks, so developers don’t need to write code to do basic things like that. While there hasn’t been a formal survey of news app teams in the U.S., it is generally understood that most teams use one of these two frameworks for database-backed news apps.

pages: 266 words: 38,397

Mastering Ember.js by Mitchel Kelonye

Firefox, MVC pattern, Ruby on Rails, single page application, web application, WebRTC, WebSocket

Therefore, a better understanding of the following will be gained at the end of the chapter: Ember.js's origin Downloading Ember.js and its dependencies Creating a basic Ember.js application Ember.js application concepts The origin of Ember.js Ember.js is a fun and productive open source JavaScript framework used for creating ambitious web applications. It powers complex client-side applications and guarantees development productivity through use of common web conventions over trivial configurations. Its official website is It was forked from SproutCore by Yehuda Katz and Tom Dale. SproutCore is an MVC framework that strives to provide a robust JavaScript widget toolkit similar to Apple's Cocoa API for Max OS X. The additional user interface widget feature was found to be unnecessary to most developers, hence the fork. The result was a more lightweight, easy-to-use library that still lived up to the promise of: Reducing development time Creating robust applications through use of common client-side web application development best practices Friendly API that makes client-side programming fun Ember.js has a wide range of applications.

pages: 48 words: 10,481

Instant Ember.JS Application Development: How-To by Marc Bodmer

don't repeat yourself, Firefox, Google Chrome, MVC pattern, web application Table of Contents Preface Instant Ember.js Application Development How-to Setting up Ember.js (Simple) Creating an Ember model/object (Simple) Enhancing an Ember object (Simple) Creating an Ember controller (Simple) Handlebar HTML templates (Simple) Creating an Ember view (Simple) Routing for your application (Medium) Common parts of an application (Medium) Handling external data (Advanced) 1 7 7 10 12 16 18 21 25 30 33 Preface Ember.js is a frontend MVC JavaScript framework that runs in the browser. It is for developers who are looking to build ambitious and large web applications that rival native applications. Ember.js was created from concepts introduced by native application frameworks, such as Cocoa. Ember.js helps you to create great experiences for the user. It will help you to organize all the direct interactions a user may perform on your website. A common use case for Ember.js is when you believe your JavaScript code will become complex; when the code base becomes complex, problems about maintaining and refactoring the code base will arise. MVC stands for model-view-controller. This kind of structure makes it easy to make modifications or refactor changes to any part of your code.

pages: 134 words: 29,488

Python Requests Essentials by Rakesh Vidya Chandra, Bala Subrahmanyam Varanasi

create, read, update, delete,, Kickstarter, MITM: man-in-the-middle, MVC pattern, natural language processing, RFC: Request For Comment, RFID, supply-chain management, web application

Now install the following packages with your virtual environment activated: (survey)~ $ pip install flask flask-sqlalchemy requests httpretty beautifulsoup4 Survey – a simple voting application using Flask To create the survey application, we are going to follow an approach which will give you an easy understanding of the ins and outs of the application and also will make this process of developing a joyride. [ 90 ] Chapter 7 Our development procedure drives you through the process of getting you introduced to all the functions that the project deals with. And then, we will implement each and every function step-by-step. During the development process we will be following the Model-View-Controller (MVC) design pattern, which is popular for developing web applications. The main aim of the survey application is to record the number of responses — 'yes', 'no' and 'maybe' - for the created survey questions. Basic file structures For developing a Flask application, we are following a specific structure to organize the contents of our application. Here is the file structure of the application that we are going to develop: Here is a description of all the files and folders present in our application's file structure: Name of the File/Folder Description Invokes the application development server to startup.

[ 106 ] Index A Access tokens, Facebook API App Access Token 57 Client Token 57 obtaining 57 Page Access Token 57 User Access Token 56 Application Programming Interface (API) 1, 50 B base template 101 basic authentication about 29 advantages 29, 30 flow 30 using, with Requests 30 BeautifulSoup about 69 document parsers 69 installing 69 objects 69 tree, modifying 76 tree, navigating 73 tree, navigating back and forth 75 tree, navigating down 73 tree, navigating sideways 74, 75 tree, navigating up 75 tree, searching 73 web scraping tasks 71, 72 Body Content Workflow about 22 keep-alive facility 23 uploads, streaming 23 built-in response status codes viewing 11 C Chrome DevTools 68 Chunked Responses 46 chunk encoded Requests sending, with generator 24 cookies accessing, with Requests 13 custom authentication 38 custom headers about 8 URL 9 D data types 66 database instance, survey application creating 94 database models, querying 96, 97 model, defining 94, 95 tables, creating 96 Digest authentication about 31 using, with Requests 32 document parsers 69 E errors and exceptions ConnectionError 16 HTTPError 16 [ 107 ] Timeout 16 TooManyRedirects 16 URL 16 event hooks used, for obtaining request method arguments 24, 25 extensions 87 F Facebook API about 56 Access tokens 56 albums, retrieving 59 feed, retrieving 59 friends list, retrieving 58 key, obtaining 56, 57 user profile, getting 57, 58 FireBug Add-on 68 Flask about 87 application, creating 88, 89 features 88 installing 89, 90 required packages, installing with pip 90 Flask micro-framework 101 Flask-SQLAlchemy about 90, 93 used, for writing models 93 form-encoded data sending 9 G generator used, for sending chunk encoded Requests 24 Graduate Record Examinations (GRE) word lists 77 grant types, OAuth 2.0 about 38 Authorization code grant 38 Client credentials grant 38 Implicit grant 38 Resource owner password credentials grant 38 H HTTPAdapter 27 HTTP libraries 68 HTTP request about 1, 2 methods 2 Request Header fields 2, 3 Request URI 2 HTTPretty about 42 headers, setting 44 HTTP requests, mocking 45 installing 42 working with 42, 43 HTTP verbs DELETE method 26 GET method 26 HEAD method 26 OPTIONS method 27 PATCH method 27 POST method 26 PUT method 26 Hypertext Transfer Protocol (HTTP) 1 J Jinja2 88 K Kerberos authentication about 32-35 Authentication Server 32 Host Machine 32 Ticket Granting Server 32 ticket granting ticket (TGT) 33, 34 using, with Requests 35 L link headers used, for describing APIs 27 M micro framework 87 [ 108 ] model about 93 defining 93 Model-View-Controller (MVC) 91 multipart encoded files posting 10 O OAuth 2.0 about 37 grant types 38 OAuth authentication about 35 OAuth 1.0 36, 37 OAuth 1.0, using with Requests 37 OAuth 2.0 37, 38 Object Relational Mapper (ORM) 90 objects, BeautifulSoup BeautifulSoup object 70 comments 70 NavigableString 70 tags 69 P prepared Requests using 20, 21 productive usage checking, with timeout parameter 15 Python modules httplib2 3 Requests 3 urllib2 3 Python Package Index (PyPi) 42 R reddit API about 60 account 60 account information, modifying 61, 62 fullnames 60 listings 60 modhashes 60 new account, registering 60 parts 60 simple search, performing 62 subreddits, searching in 63 REpresentational State Transfer (REST) 50 Requests basic authentication, using with 30 creating 5, 6 Digest authentication, using with 32 essence 5 Kerberos authentication, using with 35 OAuth 1.0 authentication, using with 37 parameters, persisting with Session objects 18 redirection tracking, with request history 14 used, for accessing cookies 13 used, for verifying SSL certificate 21 versus urllib2 3-5 Requests for Comments (RFC) 13 Requests object, parameters auth 19 cookies 19 data 19 files 19 headers 19 hooks 19 Method 19 params 19 URL 19 response content about 6-8 custom headers 8 form-encoded data, sending 9 multipart encoded files, posting 10 types 8 response headers viewing 13 responses dynamic responses, through callbacks 47 rotating responses 45, 46 streaming responses 46, 47 structure 19, 20 RESTful API 50 retweet 54 [ 109 ] S scraping 67 semistructured data 67 Session objects used, for persisting parameters across Requests 18 SSL certificate verifying, with Requests 21 streaming API encoding 25 HTTP verbs 26, 27 iterating 25 Streaming Requests URL 25 structured data 66 survey application building 92 creating 90 database instance, creating 94 executing 104 file structure 91 models, defining 93 models, writing with Flask-SQLAlchemy 93 unit tests, writing 105, 106 URLs, designing 93 T tasks, web scraping semistructured document, modifying 68 semistructured document, navigating 68 semistructured document, searching 68 template about 101 base template 101 details of survey template, displaying 103 list of questions, displaying 102 new survey template, creating 102 vote template, casting 103 template inheritance 101 timeout parameter used, for checking productive usage 15 Transport Adapter 27 Twitter API about 50 authentication request, creating 52 favorite tweet, getting 52 followers list, accessing 54 key, obtaining 51 retweet 54 simple search, performing 53 trends, accessing 55 URL 51 user status, updating 55 types, of data semistructured data 67 structured data 66 unstructured data 66 U unit tests writing, to survey application 105, 106 unstructured data 66 urllib2 examples, URL 4 versus Requests 3-5 V view about 97 new survey, creating 98 new survey question, creating 98 new vote form, creating 100 survey, deleting 100 survey, displaying 99 survey questions, listing 98 survey, updating 99 vote, casting 100 virtual environment wrapper 89 W web scraping about 65-67 dos and don'ts 67 process 68 [ 110 ] requisites 68 tasks 68 web scraping bot about 77 building 76 data, discovering to scrape 80, 81 desired data, drawing 81-85 dos and don'ts 78 HTTP client, using 79 URL/URLs, identifying 78 web scraping tools about 68 utilizing 81 Web Server Gateway Interface (WSGI) protocol 88 Where on Earth ID (woeid) 55 [ 111 ] Thank you for buying Python Requests Essentials About Packt Publishing Packt, pronounced 'packed', published its first book, Mastering phpMyAdmin for Effective MySQL Management, in April 2004, and subsequently continued to specialize in publishing highly focused books on specific technologies and solutions.

pages: 1,331 words: 183,137

Programming Rust: Fast, Safe Systems Development by Jim Blandy, Jason Orendorff

bioinformatics, bitcoin, Donald Knuth, Elon Musk, Firefox, mandelbrot fractal, MVC pattern, natural language processing, side project, sorting algorithm, speech recognition, Turing test, type inference, WebSocket

Finally, our simple router is ready to handle incoming requests: impl BasicRouter { fn handle_request(&self, request: &Request) -> Response { match self.routes.get(&request.url) { None => not_found_response(), Some(callback) => callback(request) } } } Using Closures Effectively As we’ve seen, Rust’s closures are different from closures in most other languages. The biggest difference is that in languages with GC, you can use local variables in a closure without having to think about lifetimes or ownership. Without GC, things are different. Some design patterns that are commonplace in Java, C#, and JavaScript won’t work in Rust without changes. For example, take the Model-View-Controller design pattern (MVC for short), illustrated in Figure 14-3. For every element of a user interface, an MVC framework creates three objects: a model representing that UI element’s state, a view that’s responsible for its appearance, and a controller that handles user interaction. Countless variations on MVC have been implemented over the years, but the general idea is that three objects divvy up the UI responsibilities somehow. Here’s the problem.

Here’s the problem. Typically, each object has a reference to one or both of the others, directly or through a callback, as shown in Figure 14-3. Whenever anything happens to one of the objects, it notifies the others, so everything updates promptly. The question of which object “owns” the others never comes up. Figure 14-3. The Model-View-Controller design pattern You can’t implement this pattern in Rust without making some changes. Ownership must be made explicit, and reference cycles must be eliminated. The model and the controller can’t have direct references to each other. Rust’s radical wager is that good alternative designs exist. Sometimes you can fix a problem with closure ownership and lifetimes by having each closure receive the references it needs as arguments. Sometimes you can assign each thing in the system a number and pass around the numbers instead of references.

, Macro Basicsabout, Macro Basics fragment types supported by, Fragment Types main(), Handling Errors in main() Mandelbrot setbasics of calculation, What the Mandelbrot Set Actually Is concurrent implementation, Concurrency concurrent program for, A Concurrent Mandelbrot Program mapping from pixels to complex numbers, Mapping from Pixels to Complex Numbers parsing pair command-line arguments, Parsing Pair Command-Line Arguments plotting, Plotting the Set rendering with fork-join parallelism, Revisiting the Mandelbrot Set running the plotter, Running the Mandelbrot Plotter writing image files, Writing Image Files map adapter, map and filter map typesBTreeMap<K, V>, HashMap<K, V> and BTreeMap<K, V> HashMap<K, V>, HashMap<K, V> and BTreeMap<K, V> map, defined, HashMap<K, V> and BTreeMap<K, V> map.entry(key), Entries mapping, Mapping from Pixels to Complex Numbers match expressions, A Simple Web Server, if and match Matsakis, Niko, Rayon max method, max, min max_by method, max_by, min_by max_by_key method, max_by_key, min_by_key memoryenums in, Enums in Memory raw pointers and, Moving into and out of Memory strings in, Strings in Memory types for representing sequence of values in, Arrays, Vectors, and Slices memory ordering, Atomics method calls, fully qualified, Fully Qualified Method Calls methodscalling, Function and Method Calls defining with impl, Defining Methods with impl fully qualified method calls, Fully Qualified Method Calls integers and, Integer Types min method, max, min min_by method, max_by, min_by min_by_key method, max_by_key, min_by_key Model-View-Controller (MVC), Using Closures Effectively modules, Modulesin separate files, Modules in Separate Files items, Items, the Building Blocks of Rust libraries and, Turning a Program into a Library paths and imports, Paths and Imports standard prelude, The Standard Prelude Morris worm, Why Rust?, Type Safety moves, Movesand control flow, Moves and Control Flow and indexed content, Moves and Indexed Content assigning to a variable, More Operations That Move closures and, Closures That Steal constructing new values, More Operations That Move Copy types as exception to, Copy Types: The Exception to Moves defined, Why Rust?

pages: 550 words: 84,515

Vue.js 2 Cookbook by Andrea Passaglia

bitcoin, Kickstarter, loose coupling, MVC pattern, node package manager, Silicon Valley, single page application, web application, WebSocket

Support from my colleagues at the lab was invaluable, to you guys goes my gratitude for always asking "How's the book going?" It really meant a lot to me. Thanks to my wife for constantly pushing me to write every day and everywhere; thanks to my family for your love and support. About the Reviewer Bogdan is a team lead with a passion for frontend technologies. He has worked on JavaScript for the past 8 years, from the emergence of jQuery and Ajax to modern full-fledged MVC frameworks. When he is not fiddling with some new JavaScript challenge, he spends his time playing sports and games with friends, and watching sports and movies. Nowadays he channels most of his efforts into making WE3 Interactive one of the most successful and creative startups in Cluj. He is so passionate about Vue.js that he has already helped publish another awesome book written by Olga Filipova: Learning Vue.js.

pages: 509 words: 92,141

The Pragmatic Programmer by Andrew Hunt, Dave Thomas

A Pattern Language, Broken windows theory, business process, buy low sell high,, combinatorial explosion, continuous integration, database schema, domain-specific language, don't repeat yourself, Donald Knuth, general-purpose programming language, George Santayana, Grace Hopper, if you see hoof prints, think horses—not zebras, index card, lateral thinking, loose coupling, Menlo Park, MVC pattern, premature optimization, Ralph Waldo Emerson, revision control, Schrödinger's Cat, slashdot, sorting algorithm, speech recognition, traveling salesman, urban decay, Y2K

Tip 42 Separate Views from Models By loosening the coupling between the model and the view/controller, you buy yourself a lot of flexibility at low cost. In fact, this technique is one of the most important ways of maintaining reversibility (see Reversibility, page 44). Java Tree View A good example of an MVC design can be found in the Java tree widget. The tree widget (which displays a clickable, traversable tree) is actually a set of several different classes organized in an MVC pattern. To produce a fully functional tree widget, all you need to do is provide a data source that conforms to the TreeModel interface. Your code now becomes the model for the tree. The view is created by the TreeCellRenderer and TreeCellEditor classes, which can be inherited from and customized to provide different colors, fonts, and icons in the widget. JTree acts as the controller for the tree widget and provides some general viewing functionality.

., 273 McCabe Cyclomatic Complexity Metric, 242 Member variables, see Accessor functions Memory allocation, 135 Metadata, 144, 203 business logic, 146 configuration, 147 controlling transactions, 39 decoupled code, 145 and formal methods, 221 in plain text, 74 Metric, 242 Meyer, Bertrand, 31n, 109, 184, 264 Meyer, Scott, 265 Microsoft Visual C++, 198 Microsoft Windows, 46 Mini-language, 59 data language, 60 embedded, 62 imperative, 60 parsing, 62 stand-alone, 62 Mixing board, 205 MKS Source Integrity, 271 Model, 160 calculations, 67 components and parameters, 66 and estimating, 66 executable documents, 251 view, 162 Model-view-controller (MVC), 38, 160 Modular system, 37 coding, 138 prototyping, 55 resource allocation, 135 reversibility, 45 testing, 41, 190, 244 More Effective C++, 265 Mozilla, 273 Multithreaded programming, 154 MVC, see Model-view-controller The Mythical Man Month, 264 N Name, variable, 249 Nana, 114, 268 Nest allocations, 131 Nested loop, 180 Netscape, 145, 273 Newsgroup, 15, 17, 33 Nonorthogonal system, 34 Normalize, 30 Novobilski, Andrew J., 189n O() notation, 178, 181 Object coupling, 140n destruction, 133, 134 persistence, 39 publish/subscribe protocol, 158 singleton, 41 valid/invalid state, 154 viewer, 163 Object Management Group (OMG), 270 Object Pascal, 29 C interface, 101 Object-Oriented Programming, 189n Object-Oriented Software Construction, 264 Obsolescence, 74 OLTP, see On-Line Transaction Processing system OMG, see Object Management Group On-Line Transaction Processing system (OLTP), 152 Options, providing, 3 Ordering, see Workflow Orthogonality, 34 coding, 34, 36, 40 design, 37 documentation, 42 DRY principle, 42 nonorthogonal system, 34 productivity, 35 project teams, 36, 227 testing, 41 toolkits & libraries, 39 see also Modular system Over embellishment, 11 P Pain management, 185 paint() method, 173 Painting, 11 Papua New Guinea, 16 Parallel programming, 150 Parrots, killer, see Branding Parsing, 59 code generators, 105 log messages, 196 mini-language, 62 strings, 155 Partitioning, 168 Pascal, 29 Passive code generator, 103 Performance testing, 241 Perl, 55, 62, 99 C/Object Pascal interface, 101 database schema generation, 100 home page, 267 Java property access, 100 power tools, 270 test data generation, 100 testing, 197 and typesetting, 100 Unix utilities in, 81 web documentation, 101 Perl Journal, 263 Persistence, 39, 45 Petzold, Charles, 265 Pike, Rob, 99 Pilot landing, handling, etc., 217 who ate fish, 34 Plain text, 73 vs. binary format, 73 drawbacks, 74 executable documents, 251 leverage, 75 obsolescence, 74 and easier testing, 76 Unix, 76 Polymorphism, 111 Post-it note, 53, 55 Powerbuilder, 55 The Practice of Programming, 99 Pragmatic programmer characteristics, xviii e-mail address, xxiii Web site, xxiii Pre- and postcondition, 110, 113, 114 Predicate logic, 110 Preprocessor, 114 Presentation, 20 Problem domain, 58, 66 metadata, 146 Problem solving, 213 checklist for, 214 Productivity, 10, 35 Programming by coincidence, 173 Programming staff expense of, 237 Programming Windows, 265 Project glossary, 210 “heads”, 228 saboteur, 244 schedules, 68 see also Automation; Team, project Project librarian, 33, 226 Prototyping, 53, 216 architecture, 55 disposable code, 56 kinds of, 54 and programming languages, 55 and tracer code, 51 using, 54 Publish/subscribe protocol, 158 Pugh, Greg, 95n Purify, 136 PVCS Configuration Management, 271 Python, 55, 99, 267 Q Quality control, 9 requirements, 11 teams, 225 Quarry worker’s creed, xx Quicksort algorithm, 180 R Rational Unified Process, 227n Raymond, Eric S., 273 RCS, see Revision Control System Real-world data, 243 Refactoring, 5, 185 automatic, 187 and design, 186 testing, 187 time constraints, 185 Refactoring browser, 187, 268 Refinement, excessive, 11 Regression, 76, 197, 232, 242 Relationship has-a, 304 kind-of, 111, 304 Releases, and SCCS, 87 Remote Method Invocation (RMI), 128 exception handling, 39 Remote procedure call (RPC), 29, 39 Repository, 87 Requirement, 11, 202 business problem, 203 changing, 26 creep, 209 DBC, 110 distribution, 211 documenting, 204 in domain language, 58 expressing as invariant, 116 formal methods, 220 glossary, 210 over specifying, 208 and policy, 203 usability testing, 241 user interface, 203 Researching, 15 Resource balancing, 129 C++ exceptions, 132 checking, 135 coupled code, 130 dynamic data structures, 135 encapsulation in class, 132 Java, 134 nest allocations, 131 Response set, 141, 242 Responsibility, 2, 250, 258 Reuse, 33, 36 Reversibility, 44 flexible architecture, 46 Revision Control System (RCS), 250, 271 Risk management, 13 orthogonality, 36 RMI, see Remote Method Invocation Rock-n-roll, 47 RPC, see Remote procedure call Rubber ducking, 3, 95 Rules engine, 169 S Saboteur, 244 Samba, 272 Sample programs, see Example code Sather, 114, 268 SCCS, see Source code control system Schedule, project, 68 Schrödinger, Erwin (and his cat), 47 Scope, requirement, 209 Screen scraping, 61 Scripting language, 55, 145 Secure hash, 74 sed, 99 Sedgewick, Robert, 183 Self-contained components, see Orthogonality; Cohesion Semantic invariant, 116, 135 sendmail program, 60 Sequence diagram, 158 Server code, 196 Services, design using, 154 Shell, command, 77 vs.

In an orthogonally designed system, you would need to change only those modules associated with the user interface to handle this: the underlying logic of controlling the plant would remain unchanged. In fact, if you structure your system carefully, you should be able to support both interfaces with the same underlying code base. It's Just a View, page 157, talks about writing decoupled code using the Model-View-Controller (MVC) paradigm, which works well in this situation. Also ask yourself how decoupled your design is from changes in the real world. Are you using a telephone number as a customer identifier? What happens when the phone company reassigns area codes? Don't rely on the properties of things you can't control. Toolkits and Libraries Be careful to preserve the orthogonality of your system as you introduce third-party toolkits and libraries.

Python Web Development With Django by Jeff Forcier

create, read, update, delete, database schema, Debian, don't repeat yourself,, Firefox, full text search, Guido van Rossum, loose coupling, MVC pattern, revision control, Ruby on Rails, Silicon Valley, slashdot, web application

Safety Because you are rarely executing your own SQL queries when using an ORM, you don’t have to worry as much about the issues caused by malformed or poorly protected query strings, which often lead to problems such as SQL injection attacks. ORMs also provide a central mechanism for intelligent quoting and escaping of input variables, freeing up time otherwise spent dealing with that sort of minutia.This sort of benefit is common with modularized or layered software of which MVC frameworks are a good example.When all the code responsible for a specific problem domain is well-organized and selfcontained, it can often be a huge time-saver and increase overall safety. Expressiveness Although not directly related to the definition of models, one of the greatest benefits of using an ORM (and certainly one of the largest differences, compared to writing raw SQL) is the query syntax used to obtain records from the database.

In this section, we expand further on those concepts, discussing the programming methodologies involved and an overview of how Django implements them (with details and examples in chapters to come). Separating the Layers (MVC) The idea of breaking down a dynamic application (Web or otherwise) has been around for some time, usually applied to graphical client-side applications, and is generally known as the MVC (Model-View-Controller) paradigm.As you can expect, this means the application is segregated into the model, which controls the data, the view, which defines 79 80 Chapter 3 Starting Out how to display data, and a controller, which mediates between the two and enables the user to request and manipulate the data. Compartmentalizing an application in such a manner enables the programmer to be flexible and encourages code reuse among other things.

See also Django applications admin application changing list display, 68-69 creating blog posts, 67-69 customizing, 235-240 login, 66-67 setup, 65-66 troubleshooting, 66 anonymous functions (Python) in, 39 Django architectural overview, 82 block tags, 71 blog aggregator, 338 caching, 226, 265 backend types, 272-274 baseline, determining, 265-266 cache type, setting, 266 middleware, adding, 266 strategies for, 267-271 testing, 266-267 codebase customizing, 264 testing, 279-281 community, contributing to, 337-338 core philosophies of, 82 DRY (Don’t Repeat Yourself), 84 modularity, 84-85 as Pythonic, 84 rapid development, 85 custom managers, 248 default object set, changing, 248-249 methods, creating, 249-250 methods, naming, 249 databases, setup, 62-65 decorators cache_control, 269 cache_page, 268 stringvalue, 258 described, 7 development of, 2 dictionaries in, 28, 225 documentation, 338 downloadable file generation, 243 charts and graphs, 246-248 CSV (comma-separated values) files, 245-246 Nagios configuration files, 243-244 vCards, 244-245 downloading development version, 302 packaged releases, 302 exception handling, 33 filters, 229 fixtures, 65, 113-115 forms, 142 data normalization, 150 defining, 142-143 displaying, 150-152 filling out, 147-149 model-based forms, 143-146 subclassing, 146-147 validating, 149-150 widgets, 152-154 function objects (Python) in, 37-38 hooking into Apache Web server with mod_python, 304-305 imports (CMS example application), 188 installing, 302-303 interactive interpreter (Python) usage, 9-10 keyword arguments (Python) in, 42 managers, 249 349 350 Django models admin options, 101-102 classes (Python) and, 46-47 CMS example application, 186-189 creating and updating databases, 103-104 default ordering, setting, 74 defining, 91 designing, 62 encapsulation of methods, 89-90 enumerate function (Python) in, 30 field types, 91-92 inheritance, 97-100 Meta class, 100-101 non-Django SQL features, usage of, 112-115 ORM (Object-Relational Mapper), advantages of, 89-91 photo gallery example, 160-161 portability, 90 primary keys, 92-93 query syntax, ease of use, 90 querying databases, 104-112 registering, 66 relationships, 93-96 security, 90 uniqueness, enforcing, 93 MVC (Model-View-Controller) architecture in, 80 projects, creating, 58-59 raw strings, 22 superusers, creating, 65 Syndication application, 240 feeds, configuring, 240-241 feeds, URLs for, 242 Universal Feed Parser, 242-243 templates, 70, 135 base templates, creating, 73-74 for CMS example application, 196-198 contexts, 135-136 creating, 70-71 embedding JavaScript actions in, 215 extending, 250-260 filters, 75, 137-138 for Flatpages application, 184 inclusion, 141 inheritance, 139-141 language syntax, 136-137 liveblog example application, 209 photo gallery example, 173-179 tags, 136, 138-141 tuples in, 24-25 URL patterns, 70 creating, 72 URLs, 117 callable views, 121-122 HTTP request-response model, 122-127 include function, 120-121 multiple patterns objects, 119-120 url method, 119 URLconfs, 59, 117-118 Django applications utility scripts, 261 cron jobs, 262-263 data import/export, 263-264 variable tags, 70 view functions, 70 creating, 71-72 liveblog example application, 216-218 views, 127 custom views, 131-132 generic views, 128-131, 221.

Mastering Blockchain, Second Edition by Imran Bashir

3D printing, altcoin, augmented reality, autonomous vehicles, bitcoin, blockchain, business process, carbon footprint, centralized clearinghouse, cloud computing, connected car, cryptocurrency, data acquisition, Debian, disintermediation, disruptive innovation, distributed ledger, domain-specific language,, Ethereum, ethereum blockchain, fault tolerance, fiat currency, Firefox, full stack developer, general-purpose programming language, gravity well, interest rate swap, Internet of things, litecoin, loose coupling, MITM: man-in-the-middle, MVC pattern, Network effects, new economy, node package manager, Oculus Rift, peer-to-peer, platform as a service, prediction markets, QR code, RAND corporation, Real Time Gross Settlement, reversible computing, RFC: Request For Comment, RFID, ride hailing / ride sharing, Satoshi Nakamoto, single page application, smart cities, smart contracts, smart grid, smart meter, supply-chain management, transaction costs, Turing complete, Turing machine, web application, x509 certificate

At the bottom of the image, a magnified view of blockchain is shown where by existing systems can produce events for the blockchain and also can listen for the blockchain events, which then can optionally trigger an action. At the bottom right-hand side, a user's interaction is shown with the application which talks to the smart contract via the invoice() method, and smart contracts can query or update the state of the blockchain. The application model Any blockchain application for Hyperledger Fabric follows the MVC-B architecture. This is based on the popular MVC design pattern. Components in this model are Model, View, Control, and Blockchain: View logic: This is concerned with the user interface. It can be a desktop, web application, or mobile frontend. Control logic: This is the orchestrator between the user interface, data model, and APIs. Data model: This model is used to manage the off-chain data. Blockchain logic: This is used to manage the blockchain via the controller and the data model via transactions.

Exploring ES6 - Upgrade to the next version of JavaScript by Axel Rauschmayer

anti-pattern, domain-specific language,, Firefox, Google Chrome, MVC pattern, web application, WebSocket

The proxies intercept the get operation that is triggered by the bracket operator. ⁷ Meta programming with proxies 505 function createArray(...elements) { let handler = { get(target, propKey, receiver) { let index = Number(propKey); // Sloppy way of checking for negative indices if (index < 0) { propKey = String(target.length + index); } return Reflect.get(target, propKey, receiver); } }; // Wrap a proxy around an Array let target = []; target.push(...elements); return new Proxy(target, handler); } let arr = createArray('a', 'b', 'c'); console.log(arr[-1]); // c Acknowledgement: The idea for this example comes from a blog post⁸ by 28.4.6 Data binding Data binding is about syncing data between objects. One popular use case are widgets based on the MVC (Model View Controler) pattern: With data binding, the view (the widget) stays up-to-date if you change the model (the data visualized by the widget). To implement data binding, you have to observe and react to changes made to an object. In the following code snippet, I sketch how observing changes could work for an Array. let array = []; let observedArray = new Proxy(array, { set(target, propertyKey, value, receiver) { console.log(propertyKey+'='+value); Reflect.set((target, propertyKey, value, receiver); } }); observedArray.push('a'); Output: ⁸ Meta programming with proxies 506 0=a length=1 Data binding is a complex topic.

pages: 2,054 words: 359,149

The Art of Software Security Assessment: Identifying and Preventing Software Vulnerabilities by Justin Schuh

Albert Einstein, Any sufficiently advanced technology is indistinguishable from magic, bash_history, business process, database schema, Debian, defense in depth,, Firefox, information retrieval, iterative process, loose coupling, MITM: man-in-the-middle, MVC pattern, RFC: Request For Comment, slashdot, web application

Business objects becoming out of sync with the Web tier could lead to denial-of-service conditions and security exposures. Threading issues can also be more subtle with business objects. If you have multiple threads or hosts in the Web tier using the same business object at the same time, the potential for race conditions and desynchronization attacks can increase. Web Tier: Model-View-Controller Enterprise Web applications often further divide up functionality in the Web tier. This division is often done via the Model-View-Controller (MVC) architecture pattern, which describes a user interface as being composed of three different modules. It’s not a Web-specific model; it actually originated in the Smalltalk language and is used for general-purpose user interface design. It’s just that the Web development community, or at least the Java Web development community, has embraced the MVC model for enterprise Web application development.

See IPSs (intrusion prevention systems) INVALID_HANDLE_VALUE, NULL, compared, 632-633 invocation DCOM objects, 735-736 UNIX programs, 565-572 direct invocation, 565-570 indirect invocation, 570-572 IP (Internet Protocol), 831-832 addresses, 832-833 maintaining state with, 1029-1030 addressing, 833-834 checksum, 843 fragmentation, 853-863 overlapping fragments, 858-862 pathological fragment sets, 855-858 processing, 854-855 header validation, 836-844 IP packets, 834-836 options, 844-851 source routing, 851-853 subnet, 832 IPC (interprocess communications), Windows NT, 685 COM (Component Object Model), 725-754 DDE (Dynamic Data Exchange), 697 desktop object, 690-691 impersonation, 688-689 mailslots, 705-706 messaging, 689-698 pipes, 698-705 redirector, 686-688 RPCs (Remote Procedure Calls), 706-724 security, 686-689 shatter attacks, 694-697 window station, 690 WTS (Windows Terminal Services), 697-698 IPSs (intrusion prevention systems), 88 host-based IPSs (intrusion prevention systems), 83 IRIX, 460 ISAKMP (Internet Security Association and Key Management Protocol), 948 encryption vunerabilities, 971-972 headers, 949-952 payloads, 952-956 certificate payloads, 963-964 certificate request payloads, 964 delete payloads, 969-971 hash payloads, 964-965 identification payloads, 961-963 key exchange payloads, 959, 961 nonce payloads, 965-966 notification payloads, 966-968 proposal payloads, 956-958 SA (security association) payloads, 956 signature payloads, 965 transform payloads, 959 vendor ID payloads, 971 ISAPI (Internet Server Application Programming Interface), 1010 ISAPI filters, 71 IsDBCSLeadByte( ) function, 454 iterative process, application review, 98-99 J Jaa, Tony, 685 Java Database Connectivity (JDBC), 1106 Java servlets, 1014, 1105-1106 configuration settings, 1112-1113 cross-site scripting, 1110-1111 file access, 1107-1108 file inclusion, 1108-1109 inline evaluation, 1110 JSP file inclusion, 1109-1110 shell invocation, 1108 SQL injection queries, 1106-1107 threading, 1111-1112 Web server APIs versus, 1106 Java Virtual Machine (JVM), 6 JavaScript Object Notation (JSON), 1085 JavaServer Pages (JSP), 1013-1014, 1106 file inclusion, 1109-1110 JDBC (Java Database Connectivity), 1106 Johanson, Eric, 1060 Johnson, Nick, 459 JSON (JavaScript Object Notation), 1085 JSP (JavaServer Pages), 1013, 1106 file inclusion, 1109-1110 jump locations, signals, 788-791 junction points, Windows NT files, 676-680 arbitrary file accesses, 678-680 race conditions, 680 TOCTTOU (time of check to time of use), 680 JVM (Java Virtual Machine), 6 K kernel Linux, probing, 569 UNIX, 461 kernel files, UNIX, 511 Kernel Object Manager (KOM), 627 Kernel Probe Vulnerability in Linux 2.2 listing (10-1), 569 key exchange payloads, ISAKMP (Internet Security Association and Key Management Protocol), 959, 961 keys, Windows NT registry key squatting, 682-684 permissions, 681-682 predefined keys, 681 kill bit, Active X controls, 752 kill( ) function, 786 Kirch, Olaf, 545 Klima, Vlastimil, 48 KOM (Kernel Object Manager), 627 Koziol, Jack, 168 Krahmer, Sebastian, 606, 877 Kuhn, Juan Pablo Martinez, 885 L Lai, Xuejia, 48 languages (programming), C, 203-204 arithmetic boundary conditions, 211-223 binary encoding, 207-208 bit fields, 205 bitwise shift operators, 236-237 byte order, 209 character types, 205 data storage, 204-211 floating types, 205 function invocations, 237-238 implementation defined behavior, 204 integer types, 205-206 macros, 288-289 objects, 205 operators, 271-277 order of evaluation, 282-283 pointers, 277-282 precedence, 287-288 preprocessor, 288-289 signed integer boundaries, 220-223 standards, 204 structure padding, 284-287 switch statements, 237 type conversion vunerabilities, 246-270 type conversions, 223-246 types, 204-207 typos, 289-296 unary operator, 236 unary + operator, 235 unary - operator, 235 undefined behavior, 204 unsigned integer boundaries, 213-218, 220 Last Stage of Delirium (LSD), 188 Last-Modified header field (HTTP), 1019 layer 1 (physical), network segmentation, 84 layer 2 (data link), network segmentation, 84-85 layer 3 (network), network segmentation, 85 layer 4 (transport), network segmentation, 85-87 layer 5 (session), network segmentation, 87 layer 6 (presentation), network segmentation, 87 layer 7 (application) enterprise firewalls, 894 network segmentation, 87-88 layering, stateful inspection firewalls, 911-913 layers multiple encoding layers, 444-445 network segmentation, 84-87 LD_LIBRARY_PATH environment variable (UNIX), 607 LD_PRELOAD environment variable (UNIX), 607 Le Blanc, David, 50 leaks, file descriptors, UNIX, 582-587 Leblanc, David, 235, 647-648, 736 Lebras, Gregory, 1100 Leidl, Bruce, 885 length calculations, multiple calculations on same input, 367-369 Length Miscalculation Example for Constructing an ACC log listing (7-33), 362 length variables, DNS (Domain Name System), 996, 998-1000, 1002 Lenstra, Arjen, 48 levels, impersonation, IPC (interprocess communications, 688-689 libraries, 499-500 UNIX, 510 Lincoln, Abraham, 167 linked lists auditing, 321-326 circular linked lists, 322 doubly linked lists, 322 singly linked lists, 322 linking objects, vunerabilities, 607-608 links UNIX files, 515-525 hard links, 515, 522-525 soft links, 515-522 Windows NT files, 676-680 hard links, 676 junction points, 676-680 Linux, 459-460 capabilities, 492-494 do_mremap( ) function, vunerabilities, 342-343 environment strings, 594 file system IDs, 491 kernel probes, vunerabilities, 569 teardrop vunerability, 325 Linux do_mremap( ) Vulnerability listing (7-26), 342 Linux Teardrop Vulnerability listing (7-14), 325 List Pointer Update Error listing (7-13), 324 listings 5-1 (Function Prologue), 174 5-2 (Off-by-One Length Miscalculation), 175 5-3 (Off-by-One Length Miscalculation), 181 5-4 (Overflowing into Local Variables), 197 5-5 (Indirect Memory Corruption), 199 5-6 (Off-by-One Overwrite), 200 6-1 (Twos Complement Representation of -15), 209 6-2 (Integer Overflow Example), 215 6-3 (Challenge-Response Integer Overflow Example in OpenSSH 3.1), 216 6-4 (Unsigned Integer Underflow Example), 217 6-5 (Signed Integer Vulnerability Example), 221 6-6 (Integer Sign Boundary Vulnerability Example in OpenSSL 0.9.6l), 222 6-7 (Signed Comparison Vulnerability Example), 247 6-8 (Antisniff v1.0 Vulnerability), 250 6-9 (Antisniff v1.1 Vulnerability), 251 6-10 (Antisniff v1.1.1 Vulnerability), 252 6-11 (Antisniff v1.1.2 Vulnerability), 253 6-12 (Sign Extension Vulnerability Example), 254 6-13 (Prescan Sign Extension Vulnerability in Sendmail), 256 6-14 (Sign-Extension Example), 258 6-15 (Zero-Extension Example), 258 6-16 (Truncation Vulnerability Example in NFS), 260 6-17 (Truncation Vulnerabilty Example), 260 6-18 (Detect_attack Small Packet Algorithm in SSH), 261 6-19 (Detect_attack Truncation Vulnerability in SSH), 262 6-20 (Comparison Vulnerability Example), 266 6-21 (Signed Comparison Vulnerability), 267 6-22 (Unsigned Comparison Vulnerability), 267 6-23 (Signed Comparison Example in PHP), 269 6-24 (Sizeof Misuse Vulnerability Example), 271 6-25 (Sign-Preserving Right Shift), 273 6-26 (Right Shift Vulnerability Example), 273 6-27 (Division Vulnerability Example), 274 6-28 (Modulus Vulnerability Example), 275 6-29 (Pointer Arithmetic Vulnerability Example), 281 6-30 (Order of Evaluation Logic Vulnerability), 283 6-31 (Order of Evaluation Macro Vulnerability), 283 6-32 (Structure Padding in a Network Protocol), 284 6-33 (Example of Structure Padding Double Free), 286 6-34 (Example of Bad Counting with Structure Padding), 286 7-1 (Apache mod_dav CDATA Parsing Vulnerability), 298 7-2 (Bind 9.2.1 Resolver Code gethostans( ) Vulnerability), 300 7-3 (Sendmail crackaddr( ) Related Variables Vulnerability), 304 7-4 (OpenSSH Buffer Corruption Vulnerability), 307 7-5 (OpenSSL BUF_MEM_grow( ) Signed Variable Desynchronization), 311 7-6 (Uninitialized Variable Usage), 313 7-7 (Uninitialized Memory Buffer), 314 7-8 (Uninitialized Object Attributes), 314 7-9 (Arithmetic Vulnerability Example), 317 7-10 (Arithmetic Vulnerability Example in the Parent Function), 318 7-11 (Type Confusion), 320 7-12 (Empty List Vulnerabilities), 322 7-13 (List Pointer Update Error), 324 7-14 (Linux Teardrop Vulnerability), 325 7-15 (Simple Nonterminating Buffer Overflow Loop), 328 7-16 (MS-RPC DCOM Buffer Overflow Listing), 329 7-17 (NTPD Buffer Overflow Example), 329 7-18 (Apache mod_php Nonterminating Buffer Vulnerability), 331 7-19 (Apache 1.3.29/2.X mod_rewrite Off-by-one Vulnerability), 332 7-20 (OpenBSD ftp Off-by-one Vulnerability), 333 7-21 (Postincrement Loop Vulnerability), 334 7-22 (Pretest Loop Vulnerability), 335 7-23 (Break Statement Omission Vulnerability), 337 7-24 (Default Switch Case Omission Vulnerability), 338 7-25 (Ignoring realloc( ) Return Value), 341 7-26 (Linux do_mremap( ) Vulnerability), 342 7-27 (Finding Return Values), 344 7-28 (Ignoring Return Values), 345 7-29 (Unexpected Return Values), 347 7-30 (Outdated Pointer Vulnerability), 351 7-31 (Outdated Pointer Use in ProFTPD), 354 7-32 (Sendmail Return Value Update Vulnerability), 356 7-33 (Length Miscalculation Example for Constructing an ACC log), 362 7-34 (Buffer Overflow in NSS Library’s ssl2_HandleClientHelloMessage), 365 7-35 (Out-of-Order Statements), 366 7-36 (Netscape NSS Library UCS2 Length Miscalculation), 367 7-37 (Integer Overflow with 0-Byte Allocation Check), 370 7-38 (Allocator-Rounding Vulnerability), 372 7-39 (Allocator with Header Data Structure), 372 7-40 (Reallocation Integer Overflow), 373 7-41 (Dangerous Data Type Use), 374 7-42 (Problems with 64-bit Systems), 375 7-43 (Maximum Limit on Memory Allocation), 376 7-44 (Maximum Memory Allocation Limit Vulnerability), 377 7-45 (Double-Free Vulnerability), 379 7-46 (Double-Free Vulnerability in OpenSSL), 380 7-47 (Reallocation Double-Free Vulnerability), 383 8-1 (Different Behavior of vsnprintf( ) on Windows and UNIX), 394 8-2 (Dangerous Use of strncpy( )), 396 8-3 (Strcpy( )-like Loop), 400 8-4 (Character Expansion Buffer Overflow), 401 8-5 (Vulnerable Hex-Decoding Routine for URIs), 404 8-6 (If Header Processing Vulnerability in Apache’s mod_dav Module), 404 8-7 (Text-Processing Error in Apache mod_mime), 406 8-8 (Embedded Delimiter Example), 409 8-9 (Multiple Embedded Delimiters), 410 8-10 (NUL-Byte Injection with Memory Corruption), 413 8-11 (Data Truncation Vulnerability), 415 8-12 (Data Truncation Vulnerability 2), 415 8-13 (Correct Use of GetFullPathName( )), 416 8-14 (GetFullPathName( ) Call in Apache 2.2.0), 417 8-15 (Directory Traversal Vulnerability), 420 8-16 (Format String Vulnerability in WU-FTPD), 423 8-17 (Format String Vulnerability in a Logging Routine), 424 8-18 (Shell Metacharacter Injection Vulnerability), 426 8-19 (Example of Dangerous Program Use), 428 8-20 (SQL Injection Vulnerability), 431 8-21 (SQL Truncation Vulnerability), 433 8-22 (Character Black-List Filter), 435 8-23 (Character White-List Filter), 436 8-24 (Metacharacter Vulnerability in PCNFSD), 437 8-25 (Vulnerability in Filtering a Character Sequence), 437 8-26 (Vulnerability in Filtering a Character Sequence #2), 438 8-27 (Hex-encoded Pathname Vulnerability), 441 8-28 (Decoding Incorrect Byte Values), 443 8-29 (Return Value Checking of MultiByteToWideChar( )), 452 8-30 (Dangerous Use of IsDBCSLeadByte( )), 454 8-31 (Code Page Mismatch Example), 455 8-32 (NUL Bytes in Multibyte Code Pages), 456 9-1 (Privilege Misuse in XFree86 SVGA Server), 478 9-2 (Incorrect Temporary Privilege Relinquishment in FreeBSD Inetd), 487 9-3 (Race Condition in access( ) and open( )), 526 9-4 (Race Condition from Kerberos 4 in lstat( ) and open( )), 529 9-5 (Race Condition in open( ) and lstat( )), 529 9-6 (Reopening a Temporary File), 542 10-1 (Kernel Probe Vulnerability in Linux 2.2), 569 10-2 (Setenv( ) Vulnerabilty in BSD), 576 10-3 (Misuse of putenv( ) in Solaris Telnetd), 597 13-1 (Signal Interruption), 791 13-2 (Signal Race Vulnerability in WU-FTPD), 802 13-3 (Race Condition in the Linux Kernel’s Uselib( )), 821 16-1 (Name Validation Denial of Service), 931 16-2 (Certificate Payload Integer Underflow in CheckPoint ISAKMP), 954 lists auditing, 321-324, 326 data ranges, 324, 326 duplicate elements, 323 empty lists, vunerabilities, 322-323 linked lists, 322 pointer updates, errors, 323-324 list_add( ) function, 757 list_init( ) function, 757 little-endian architecture, bytes, ordering, 209 loading DLLs, 656-658 Processes, Windows NT, 654-655 local namespaces, Windows NT, 629 local privilege separation socket, OpenSSH, 161 Location header field (HTTP), 1019 lock matching, synchronization objects, 781-783 LOCK method, 1022 log files, UNIX, 510 logic business logic, 1041 presentation logic, 1040-1041 login groups, UNIX, 461 logon rights, Windows NT sessions, 638 longjmp( ) function, 788-791 looping constructs, auditing, 327-336 loops data copy, 330 posttest loops, 334-335 pretest loops, 334-335 terminating conditions, 327-334 typos, 335-336 loose coupling, software design, 33 loosely coupled modules, 33 Lopatic, Thomas, 895, 903, 907-911 lreply( ) function, 423 LSD (Last Stage of Delirium), 188 lstat( ) function, 528-531 M %m format specifier, 423 MAC (Media Address Control), 84 Macros, C programming language, 288-289 magic_quotes option (PHP), 1105 mail spools, UNIX, 509 mailslot squatting, 706 mailslots, Windows NT, IPC (interprocess communications), 705-706 Maimon, Uriel, 897 maintaining state, 1027-1029 client IP addresses, 1029-1030 cookies, 1036-1038 embedding state in HTML and URLs, 1032-1033 HTTP authentication, 1033-1036, 1056-1057 Referer request header, 1030-1031 sessions, 1038-1039, 1049-1052 security vulnerabilities, 1051-1052 session management, 1052-1053 session tokens, 1053-1056 stateful versus stateless systems, 1027 maintenance, SDLC (Systems Development Life Cycle), 13 major components, 50 make_table( ) function, 216 malicious input, tracing, 113-114 malloc( ) function, 341, 371 man-in-the-middle attacks, 162 management, sessions, 1052-1053 mapping CLSIDs to applications, 728 Max-Forwards header field (HTTP), 1019 Maximum Limit on Memory Allocation listing (7-43), 376 Maximum Memory Allocation Limit Vulnerability listing (7-44), 377 McDonald, John, 571, 903, 907, 911 McGraw, Gary, 168 Media Address Control (MAC), 84 Mehta, Neel, 203, 895, 967 memory, 0 bytes, allocating, 370-371 memory blocks, shared memory blocks, 201-202 memory buffers, unitialized memory buffers, 314 memory corruption, 167 assessing, 196-202 buffer overflows, 168-169 global overflows, 186 heap overflows, 183-186 off-by-one errors, 180-183 process memory layout, 169 SHE (structured exception handling) attacks, 178-180 stack overflows, 169-178 static overflows, 186 protection mechanisms, 189-190 ASLR (address space layout randomization), 194 function pointer obfuscation, 195-196 heap hardening, 191-193 nonexecutable stack, 193 SafeSEH, 194-195 stack cookies, 190-191 shellcode, 187-189 memory management, auditing, 362 ACC (allocation-check-copy) logs, 362-369 allocation functions, 369-377 allocator scorecards, 377-379 double-frees, 379-385 error domains, 378-379 memory pages, nonexecutable memory pages, 193 memset( ) function, 199 message queues, 614 Message-Id header field (HTTP), 1019 messaging, Windows NT, IPC (interprocess communications), 689-698 metacharacter evasion, 441-445 Metacharacter Vulnerability in PCNFSD listing (8-24), 437 metacharacters, 387, 407-408 embedded delimiters, 408-411 filtering, 434-445 character stripping vunerabilities, 437-439 escaping metacharacters, 439-440 insufficient filtering, 436-437 metacharacter evasion, 441-445 format strings, 422-425 formats, 418 NUL-byte injection, 411-414 path metacharacters, 418-422 file canonicalization, 419-420 Windows registry, 420-422 Perl open( ) function, 429-431 shell metacharacters, 425-429 SQL queries, 431-434 truncation, 414-418 UNIX programs, indirect invocation, 570-571 metadata, 407 methods CONNECT, 1021 COPY, 1022 DELETE, 1020 GET, 1023, 1026 LOCK, 1022 MKCOL, 1022 MOVE, 1022 OPTIONS, 1021 POST, 1025-1026 PROPFIND, 1022 PROPPATCH, 1022 PUT, 1020 SEARCH, 1022 SPACEJUMP, 1021 TEXTSEARCH, 1021 TRACE, 1021 UNLOCK, 1022 Microsoft Developer Network (MSDN), 626 Microsoft Windows Internals, 4th Edition, 654 MIDL (Microsoft Interface Definition Language) DCOM (Distributed Component Object Model), 738-740 RPCs (Remote Procedure Calls), 708 misinpreterpeting return values, 346-350 Misuse of putenv( ) in Solaris Telnetd listing (10-3), 597 mitigating factors, operational vunerabilities, 76 mitigation, threats, 61 MKCOL method, 1022 mkdtemp( ) function, 543 mkstemp( ) function, 542-543 mktemp( ) function, 539, 541 Model component (MVC), 1045 Model-View-Controller (MVC), 1044-1045 modular artihmetic, 214 modules analyzing, CC (code comprehension), 114-116 loosely coupled modules, 33 strongly coupled modules, 33 Modulus Vulnerability Example listing (6-28), 275 mount points, UNIX, 463 MOVE method, 1022 MS-RPC DCOM Buffer Overflow Listing listing (7-16), 329 MSDN (Microsoft Developer Network), 626 MTA (mulitthreaded apartment), COM (Component Object Model), 729 multibyte character sequences, interpretation, 455 MultiByteToWideChar( ) function, 451-452, 456-457 Multics (Multiplexed Information and Computing Service), 460 Multiple Embedded Delimiters listing (8-9), 410 multiple encoding layers, 444-445 multiple-input test cases, code audits, 143 Multiplexed Information and Computing Service (Multics), 460 multiplication overflows, Intel architectures, 218, 220 multiplicative operators, 243 multithreaded apartment (MTA), COM (Component Object Model), 729 multithreaded programs, synchronization, 810-825 deadlocks, 823-825 PThreads API, 811-813 race conditions, 816-823 starvation, 823-825 Windows API, 813-815 Murray, Bill, 25 mutex, 756 mutex objects, Windows NT, 766 mutexes, PThreads API, 811-812 MVC (Model-View-Controller), 1044-1045 my_malloc( ) function, 371 N N-tier architectures, 1041, 1043 business tier, 1042-1044 client tier, 1042 data tier, 1042-1043 MVC (Model-View-Controller), 1044-1045 Web tier, 1042-1045 name servers, DNS (Domain Name System), 986-987 name squatting, 630 Name Validation Denial of Service listing (16-1), 931 named pipes UNIX, 511 Windows NT, 698-699 names, DNS (Domain Name System), 993-996 namespaces (Windows NT) global namespaces, 629 local namespaces, 629 objects, 629-632 collisions, 630-631 Vista object namespaces, 631 narrowing integer types, 227-228 NAT (Network Address Translation), 88 National Institute for Standards and Technology (NIST), 44 navigating code, 109 external flow sensitivity, 109-110 tracing, 111 NCACN (network computing architecture connection-oriented protocol), RPCs (Remote Procedure Calls), 707 NCALRPC (network computing architecture local remote procedure call protocol), RPCs (Remote Procedure Calls), 708 NCDAG (network computing architecture datagram protocol), RPCs (Remote Procedure Calls), 707 .NET Common Language Runtime (CLR), 6 .NET Developer’s Guide to Windows Security, The, 637 NetBSD, 460 netmasks, 833 Netscape NSS Library UCS2 Length Miscalculation listing (7-36), 367 Netscape Server Application Programming Interface (NSAPI), 1010 Network Address Translation (NAT).

WEB APPLICATIONS Introduction Web Technology Overview The Basics Static Content CGI Web Server APIs Server-Side Includes Server-Side Transformation Server-Side Scripting HTTP Overview Versions Headers Methods Parameters and Forms State and HTTP Authentication Overview Client IP Addresses Referer Request Header Embedding State in HTML and URLs HTTP Authentication Cookies Sessions Architecture Redundancy Presentation Logic Business Logic N-Tier Architectures Business Tier Web Tier: Model-View-Controller Problem Areas Client Visibility Client Control Page Flow Sessions Authentication Authorization and Access Control Encryption and SSL/TLS Phishing and Impersonation Common Vulnerabilities SQL Injection OS and File System Interaction XML Injection XPath Injection Cross-Site Scripting Threading Issues C/C++ Problems Harsh Realities of the Web Auditing Strategy Summary 18.

Refactoring: Improving the Design of Existing Code by Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts

conceptual framework, database schema, index card, MVC pattern, place-making, sorting algorithm

You may want several interfaces for similar business logic; the user interface becomes too complicated if it does both; it is easier to maintain and evolve domain objects separate from the GUI; or you may have different developers handling the different pieces. Although the behavior can be separated easily, the data often cannot. Data needs to be embedded in GUI control that has the same meaning as data that lives in the domain model. User interface frameworks, from model-view-controller (MVC) onward, used a multitiered system to provide mechanisms to allow you to provide this data and keep everything in sync. 153 If you come across code that has been developed with a two-tiered approach in which business logic is embedded into the user interface, you need to separate the behaviors. Much of this is about decomposing and moving methods. For the data, however, you cannot just move the data, you have to duplicate it and provide the synchronization mechanism.

Example The example in Chapter 1 is a good example of the need for Convert Procedural Design to Objects, particularly the first stage, in which the statement method is broken up and distributed. When you're finished, you can work on now-intelligent data objects with other refactorings. Separate Domain from Presentation You have GUI classes that contain domain logic. Separate the domain logic into separate domain classes Motivation Whenever you hear people talking about objects, you hear about model-view-controller (MVC). This idea underpinned the relationship between the graphical user interface (GUI) and domain objects in Smalltalk-80. 302 The gold at the heart of MVC is the separation between the user interface code (the view, these days often called the presentation) and the domain logic (the model). The presentation classes contain only the logic needed to deal with the user interface. Domain objects contain no visual code but all the business logic.

Programming Python by Mark Lutz

Benevolent Dictator For Life (BDFL), Build a better mousetrap, business process, cloud computing, Firefox, general-purpose programming language, Google Chrome, Guido van Rossum, iterative process, linear programming, loose coupling, MVC pattern, natural language processing, off grid, slashdot, sorting algorithm, web application

Also in the framework category are Zope—an open source web application server and toolkit, written in and customizable with Python, in which websites are implemented using a fundamentally object-oriented model; Plone—a Zope-based website builder which provides a workflow model (called a content management system) that allows content producers to add their content to a site; and other popular systems for website construction, including pylons, web2py, CherryPy, and Webware. Many of these frameworks are based upon the now widespread MVC (model-view-controller) structure, and most provide state retention solutions that wrap database storage. Some make use of the ORM (object relational mapping) model we’ll meet in the next part of the book, which superimposes Python’s classes onto relational database tables, and Zope stores objects in your site in the ZODB object-oriented database we’ll study in the next part as well. Rich Internet Applications (revisited) Discussed at the start of Chapter 7, newer and emerging “rich Internet application” (RIA) systems such as Flex, Silverlight, JavaFX, and pyjamas allow user interfaces implemented in web browsers to be much more dynamic and functional than HTML has traditionally allowed.

., Other XML topics Jython, Python GUI Development Options, Python Internet Development Options, Other Client-Side Scripting Options, Extending and Embedding, Other Extending Tools, Other Integration Topics development options, Python Internet Development Options integration considerations, Extending and Embedding, Other Integration Topics overview, Python GUI Development Options, Other Client-Side Scripting Options, Other Extending Tools K Kennedy, Bill, “Oh, What a Tangled Web We Weave” kill shell command, Signals, Preventing zombies with signal handlers on Linux kwParsing system, Advanced Language Tools L Label widget class, Packing Widgets Without Saving Them, The End of the Tutorial functionality, The End of the Tutorial pack method, Packing Widgets Without Saving Them LabelFrame widget class, Other Widgets and Options labels, Configuring Widget Appearance, Configuring Widget Appearance, Configuring Widget Appearance, Configuring Widget Appearance, Configuring Widget Appearance, Configuring Widget Appearance, Configuring Widget Appearance, Configuring Widget Appearance, Configuring Widget Appearance bg option, Configuring Widget Appearance customizing, Configuring Widget Appearance expand option, Configuring Widget Appearance fg option, Configuring Widget Appearance fill option, Configuring Widget Appearance font attribute, Configuring Widget Appearance height attribute, Configuring Widget Appearance pack option, Configuring Widget Appearance width attribute, Configuring Widget Appearance LALR parsers, Advanced Language Tools lambda callback handlers, Lambda Callback Handlers, Deferring Calls with Lambdas and Object References, Deferring Calls with Lambdas and Object References, Callback Scope Issues, But you must still sometimes use defaults instead of enclosing scopes callback scope issues, Callback Scope Issues, But you must still sometimes use defaults instead of enclosing scopes deferring calls, Deferring Calls with Lambdas and Object References, Deferring Calls with Lambdas and Object References functionality, Lambda Callback Handlers LAMP acronym, Other themes in this part of the book language analysis, Strategies for Processing Text in Python (see text processing and language analysis) languages2common module, Step 1: Sharing Objects Between Pages—A New Input Form languages2reply module, Step 3: Putting It All Together—A New Reply Script, Step 3: Putting It All Together—A New Reply Script launchmodes module, A Portable Program-Launch Framework, Running Programs lexical analysis, Advanced Language Tools (see text processing and language analysis) library modules, Python’s Internet Library Modules, Python’s Internet Library Modules line buffering, Line buffering, Line buffering Lisp language, Enter Python LIST command (FTP), Downloading Site Directories list comprehensions, summing with, Summing with zips and comprehensions list operators, Using Lists, A database list, A database list, Nested structures append, A database list, Nested structures extend, A database list functionality, Using Lists Listbox widget class, The End of the Tutorial, Listboxes and Scrollbars, Programming Listboxes, Programming Listboxes, Programming Listboxes, Programming Listboxes, Programming Listboxes, Programming Scroll Bars, Programming Scroll Bars, Programming Scroll Bars, Programming Scroll Bars curselection method, Programming Listboxes functionality, The End of the Tutorial, Listboxes and Scrollbars insert method, Programming Listboxes programming, Programming Listboxes, Programming Listboxes runCommand method, Programming Listboxes xscrollcommand option, Programming Scroll Bars xview method, Programming Scroll Bars yscrollcommand option, Programming Scroll Bars yview method, Programming Scroll Bars lists, Using Lists, A database list, Field labels, Field labels, Lists of dictionaries, Built-in Options, Optimization: In-Place List Modifications, Optimization: In-Place List Modifications database lists, A database list of dictionaries, Lists of dictionaries field labels, Field labels, Field labels in-place modifications, Optimization: In-Place List Modifications, Optimization: In-Place List Modifications sample records, Using Lists stacks as, Built-in Options loops, Coding alternatives: busy loops, arguments, and context managers, Coding alternatives: busy loops, arguments, and context managers, Simple Animation Techniques, Using time.sleep loops, Using time.sleep loops, Using multiple time.sleep loop threads threads and, Coding alternatives: busy loops, arguments, and context managers, Coding alternatives: busy loops, arguments, and context managers time.sleep, Simple Animation Techniques, Using time.sleep loops, Using time.sleep loops, Using multiple time.sleep loop threads ls command, Shell command limitations, Running shell listing commands with os.popen filename patterns, Running shell listing commands with os.popen shell command limitations, Shell command limitations M M2Crypto third-party package, HTTPS: Secure HTTP transmissions Mac environment, Running the Examples, Python GUI Development Options, Python GUI Development Options, Other Extending Tools language support, Other Extending Tools programming user interfaces, Python GUI Development Options, Python GUI Development Options tkinter support, Running the Examples machine names, Machine identifiers mail configuration module, Mail Configuration Module, POP Mail Reader Script, Implementation Overview, Using the Send Mail Script Outside a Browser mail reader tool, POP: Fetching Email, POP Mail Reader Script, Fetching Messages mail sender script, SMTP Mail Sender Script, Sending Email at the Interactive Prompt mailbox module, Python’s Internet Library Modules MailFetcher class, MailFetcher Class, MailParser Class MailParser class, MailParser Class MailSender class, MailSender Class, MailFetcher Class MailTool class, MailTool Class mailtools utility package, The mailtools Utility Package, The mailtools Utility Package, Initialization File, MailTool Class, MailSender Class, MailFetcher Class, MailFetcher Class, MailParser Class, MailParser Class, Self-Test Script, Updating the pymail Console Client, Updating the pymail Console Client, Running the pymail2 console client, Sending Email and Attachments, POP Message Numbers and Synchronization, Implementation Overview, The Mail Selection List Page, The Message View Page, POP Mail Interface initialization file, Initialization File MailFetcher class, MailFetcher Class, MailParser Class MailParser class, MailParser Class MailSender class, MailSender Class, MailFetcher Class MailTool class, MailTool Class overview, The mailtools Utility Package pymail client and, Updating the pymail Console Client, Running the pymail2 console client PyMailCGI and, Implementation Overview, The Mail Selection List Page, The Message View Page, POP Mail Interface PyMailGUI and, Sending Email and Attachments, POP Message Numbers and Synchronization module, The mailtools Utility Package, Self-Test Script, Updating the pymail Console Client mainloop function (tkinter), tkinter Coding Basics, tkinter Coding Alternatives marks, text, Text marks match objects (re module), First Examples media files, playing, Playing Media Files, Running the Script Menu widget class, The End of the Tutorial, Top-Level Window Menus, Top-Level Window Menus, Top-Level Window Menus add_cascade method, Top-Level Window Menus functionality, The End of the Tutorial, Top-Level Window Menus, Top-Level Window Menus Menubutton widget class, The End of the Tutorial, Frame- and Menubutton-Based Menus, Using Menubuttons and Optionmenus menus, Menus, Top-Level Window Menus, Top-Level Window Menus, Frame- and Menubutton-Based Menus, Using Menubuttons and Optionmenus, Frame- and Menubutton-Based Menus, Using Menubuttons and Optionmenus, Windows with Both Menus and Toolbars, Windows with Both Menus and Toolbars, Automating menu construction, GuiMaker: Automating Menus and Toolbars, BigGui: A Client Demo Program, Menus and toolbars automating, Automating menu construction, GuiMaker: Automating Menus and Toolbars, BigGui: A Client Demo Program defined, Menus displaying in windows, Windows with Both Menus and Toolbars, Windows with Both Menus and Toolbars frame-based, Frame- and Menubutton-Based Menus, Using Menubuttons and Optionmenus menubutton-based, Frame- and Menubutton-Based Menus, Using Menubuttons and Optionmenus PyEdit text editor, Menus and toolbars top-level, Top-Level Window Menus, Top-Level Window Menus message headers, Message header encodings: email package support, Message address header encodings and parsing, and header creation, Message address header encodings and parsing, and header creation, Unicode issues for attachments, save files, and headers, Unicode decoding for text part payloads and message headers, Alternative: Passing header text in hidden input fields (PyMailCGI_2.1), Alternative: Passing header text in hidden input fields (PyMailCGI_2.1) email addresses, Message address header encodings and parsing, and header creation, Message address header encodings and parsing, and header creation Internationalized, Message header encodings: email package support mailtools utility package, Unicode issues for attachments, save files, and headers, Unicode decoding for text part payloads and message headers passing text in hidden fields, Alternative: Passing header text in hidden input fields (PyMailCGI_2.1), Alternative: Passing header text in hidden input fields (PyMailCGI_2.1) Message objects, Message Objects, Message Objects, Basic email Package Interfaces in Action, Handling multipart messages, Handling multipart messages, Text payload encodings: Handling mixed type results, Text payload encodings: Using header information to decode composing messages, Basic email Package Interfaces in Action, Handling multipart messages functionality, Message Objects, Message Objects get_content_charset method, Text payload encodings: Using header information to decode get_payload method, Text payload encodings: Handling mixed type results multipart messages, Handling multipart messages Message Passing Interface (MPI) standard, “Telling the Monkeys What to Do” Message widget class, The End of the Tutorial, Message messagebox module, Standard (Common) Dialogs MFC (Microsoft Foundation Classes), Python GUI Development Options mimetypes module, Playing Media Files, Playing Media Files, The Python mimetypes Module, Using mimetypes guesses for SearchVisitor, Python’s Internet Library Modules, Downloading Site Directories, Uploading Site Directories, Message Objects, Message Objects functionality, The Python mimetypes Module, Using mimetypes guesses for SearchVisitor, Python’s Internet Library Modules guess_extension method, Message Objects guess_type method, Message Objects playing media files, Playing Media Files, Playing Media Files selecting transfer modes, Downloading Site Directories, Uploading Site Directories minimal URLs, Using minimal URLs, Step 1: Sharing Objects Between Pages—A New Input Form mixin utility classes, Mixin Utility Classes, Mixin Utility Classes mmap module, Interprocess Communication model-view-controller (MVC) structure, Python Internet Development Options module documentation sources, Module Documentation Sources mod_python module, Python Internet Development Options, Web Server Options, Extensions to the CGI Model Monty Python theme song, Playing the Monty Python theme song more function, A Custom Paging Script, Chaining programs with pipes chaining with pipes, Chaining programs with pipes functionality, A Custom Paging Script mouse-related events, Binding Events, More on <Destroy> events and the quit and destroy methods MPEG format, Graphics and gaming toolkits MPI (Message Passing Interface) standard, “Telling the Monkeys What to Do” multiplexing servers, Multiplexing Servers with select, Summary: Choosing a Server Scheme multiprocessing, “Telling the Monkeys What to Do” (see parallel processing) multiprocessing module, Python System Modules, A process-based alternative: multiprocessing (ahead), Interprocess Communication, The multiprocessing Module, Why multiprocessing?

GIL and, A process-based alternative: multiprocessing (ahead) implementation, Implementation and usage rules IPC support, Interprocess Communication, IPC Tools: Pipes, Shared Memory, and Queues, Queues and subclassing launching GUIs as programs, Launching GUIs as programs other ways: multiprocessing, Launching GUIs as programs other ways: multiprocessing processes and locks, The Basics: Processes and Locks, Implementation and usage rules socket server portability and, Why multiprocessing doesn’t help with socket server portability, Why multiprocessing doesn’t help with socket server portability starting independent programs, Starting Independent Programs usage rules, Implementation and usage rules Musciano, Chuck, “Oh, What a Tangled Web We Weave” MVC (model-view-controller) structure, Python Internet Development Options mysql-python interface, Persistence Options in Python N name conventions, File name conventions, Installing CGI scripts CGI scripts, Installing CGI scripts files, File name conventions __name__ variable, Using Programs in Two Ways named pipes, Interprocess Communication, Anonymous Pipes, Named Pipes (Fifos), Named pipe basics, Named pipe basics, Named pipe use cases basic functionality, Named pipe basics, Named pipe basics creating, Named Pipes (Fifos) defined, Interprocess Communication, Anonymous Pipes use cases, Named pipe use cases namespaces, Running Code Strings with Results and Namespaces, Running Code Strings with Results and Namespaces, Running Strings in Dictionaries creating, Running Strings in Dictionaries running code strings with, Running Code Strings with Results and Namespaces, Running Code Strings with Results and Namespaces natural language processing, Advanced Language Tools nested structures, Nested structures, Uploading Local Trees, Uploading Local Trees, Pickled Objects, Pickling in Action dictionaries, Nested structures pickling, Pickled Objects, Pickling in Action uploading local trees, Uploading Local Trees, Uploading Local Trees Network News Transfer Protocol (NNTP), NNTP: Accessing Newsgroups, NNTP: Accessing Newsgroups, More Than One Way to Push Bits over the Net network scripting, Python Internet Development Options, Python Internet Development Options, The Socket Layer, Machine identifiers, The Protocol Layer, Protocol structures, Python’s Internet Library Modules, Python’s Internet Library Modules, Socket Programming, Binding reserved port servers, Handling Multiple Clients, Summary: Choosing a Server Scheme, Making Sockets Look Like Files and Streams, Sockets versus command pipes, A Simple Python File Server, Using a reusable form-layout class development options, Python Internet Development Options, Python Internet Development Options handling multiple clients, Handling Multiple Clients, Summary: Choosing a Server Scheme library modules and, Python’s Internet Library Modules, Python’s Internet Library Modules making sockets look like files/streams, Making Sockets Look Like Files and Streams, Sockets versus command pipes protocols and, The Protocol Layer, Protocol structures Python file server, A Simple Python File Server, Using a reusable form-layout class sockets and, The Socket Layer, Machine identifiers, Socket Programming, Binding reserved port servers newsgroups, NNTP: Accessing Newsgroups, NNTP: Accessing Newsgroups, Ideas for Improvement accessing, NNTP: Accessing Newsgroups, NNTP: Accessing Newsgroups handling messages, Ideas for Improvement NLTK suite, Advanced Language Tools NNTP (Network News Transfer Protocol), NNTP: Accessing Newsgroups, NNTP: Accessing Newsgroups, More Than One Way to Push Bits over the Net nntplib module, Python’s Internet Library Modules, NNTP: Accessing Newsgroups, NNTP: Accessing Newsgroups numeric tools, A Quick Geometry Lesson NumPy programming extension, A Quick Geometry Lesson, Extending and Embedding O object references, Deferring Calls with Lambdas and Object References, Deferring Calls with Lambdas and Object References, Reloading Callback Handlers Dynamically callback handlers as, Reloading Callback Handlers Dynamically deferring calls, Deferring Calls with Lambdas and Object References, Deferring Calls with Lambdas and Object References object relational mappers, Other Database Options (see ORMs) Object Request Broker (ORB), Python Internet Development Options object types, storing in shelves, Storing Built-in Object Types in Shelves object-oriented databases (OODBs), Persistence Options in Python object-oriented programming, Step 3: Stepping Up to OOP (see OOP) objects, Step 1: Sharing Objects Between Pages—A New Input Form, Step 1: Sharing Objects Between Pages—A New Input Form, Persistence Options in Python, Pickled Objects, Pickle Details: Protocols, Binary Modes, and _pickle, Pickled Objects, Changing Classes of Objects Stored in Shelves, Objects are unique only within a key, What Is Embedded Code?

pages: 196 words: 58,122

AngularJS by Brad Green, Shyam Seshadri

combinatorial explosion, continuous integration, Firefox, Google Chrome, Kickstarter, MVC pattern, node package manager, single page application, web application, WebSocket

malicious sites, JSON Vulnerability mandatory fields, Validating User Input manual testing, End-to-End/Integration Tests mathematics functions, Expressions menus, conditional disabling of, CSS Classes and Styles method calls, Communicating Over $http minification, Compilation, Building Your Project minimum/maximum field lengths, The Templates mobile apps, Talking to Servers, Compilation mock data, Organizing Dependencies with Modules model data observing changes with, Observing Model Changes with $watch publishing with scopes, Publishing Model Data with Scopes, Scopes–Scopes storage of, Model View Controller (MVC) model objects, creating, Model View Controller, Working with RESTful Resources model properties, binding elements to, Form Inputs model variables, Model View Controller Model View Controller (MVC) basics of, Model View Controller (MVC), Model View Controller models as basis for apps, The Model basics of, Model View Controller, Relationship Between Model, Controller, and Template model trees in Batarang, Model tab module class, Convenience Methods modules creation of, Model View Controller module methods, AngularJS Module Methods–Convenience Methods number needed, How Many Modules Do I Need? organization of, Where’s the Main Method?

(Unless You Really Want Them) camel-cased names, Naming Your Directive check boxes, Form Inputs, The Check Box child controller, Controllers child scopes, Scopes Chrome browser, Templates Chrome desktop apps, Talking to Servers classes, Client-Side Templates, CSS Classes and Styles click event handler, A Few Words on Unobtrusive JavaScript click notification, A Few Words on Unobtrusive JavaScript client-side templates, Client-Side Templates, Compilation Closure Compiler, Compilation code minification, Compilation code optimization, Compilation combo boxes, The Combo Boxes comparisons, Expressions compilation, Compilation compile property, API Overview, Compile and Link Functions computed results, Observing Model Changes with $watch Config block, Loading and Dependencies configuration files, Project Organization controller property, API Overview controller unit tests, Unit Tests (see also unit tests) controllers adding with Yeoman, Adding New Routes, Views, and Controllers basics of, Model View Controller, Model View Controller, Relationship Between Model, Controller, and Template communication between, The Teams List App: Filtering and Controller Communication defining, Model View Controller file location of, Project Organization in Angular, Model View Controller (MVC), An Example: Shopping Cart nesting of, Separating UI Responsibilities with Controllers, Controllers separating UI responsibilities with, Separating UI Responsibilities with Controllers vs. modules, Organizing Dependencies with Modules working example of, Controllers convenience methods, Communicating Over $http, Convenience Methods cookies, XSRF, Cookies CORS, Talking to Servers credit card objects, Working with RESTful Resources cross-browser compatibility, A Few Words on Unobtrusive JavaScript, Validating User Input CSS classes and styles, CSS Classes and Styles–CSS Classes and Styles currency filter, Formatting Data with Filters, Internationalization and Localization custom error messages, The Templates D data formatting with filters, Formatting Data with Filters passing among scopes, Scopes data binding and templates, Model View Controller–Watching multiple things basics of, Data Binding native speed, Performance Considerations in watch() strategies for, Scopes date filter, Formatting Data with Filters date/time localization, Internationalization and Localization datepickers, Wrapping a jQuery Datepicker debugger breakpoints, Performance Considerations in watch() debugging, Other Awesome Tools declarations, The Declaration declarative event handlers, A Few Words on Unobtrusive JavaScript deepWatch, Observing Model Changes with $watch default headers, Setting HTTP Headers dependency injection basics of, Dependency Injection management of, Service dependencies, Integrating AngularJS with RequireJS organizing with modules, Organizing Dependencies with Modules, Loading and Dependencies dependency loops, Performance Considerations in watch() deployment packages, Integrating AngularJS with RequireJS directive definition object, The Directive Definition Object–Templates directive factory function, Changing the DOM with Directives directives API overview, API Overview–Controllers basics of, Directives, Relationship Between Model, Controller, and Template, Directives creating custom, Changing the DOM with Directives, The Templates, API Overview HTML validation and, Directives discounts, automatic application of, Observing Model Changes with $watch display:block, Hiding and Showing display:none, Hiding and Showing do-what-I-mean declaration, Moving On doA() function, A Few Words on Unobtrusive JavaScript doB() function, A Few Words on Unobtrusive JavaScript document.cookie interface, Cookies DOM (Document Object Model) changing with directives, Changing the DOM with Directives manipulation in Angular, Model View Controller (MVC), Directives, Relationship Between Model, Controller, and Template, Manipulating DOM Elements unit tests and, A Few Words on Unobtrusive JavaScript domReady, Integrating AngularJS with RequireJS doSomething() function, A Few Words on Unobtrusive JavaScript double-curly syntax interpolation, Model View Controller, Displaying Text, CSS Classes and Styles E Edit Controller, Controllers email app, Changing Views with Routes and $location end-to-end tests, End-to-End/Integration Tests errors 404 errors, Considerations for src and href Attributes handling of, The $q and the Promise input error, The Templates login errors, Working with Servers and Login NullPointerException error, Expressions Origin null is not allowed, Templates eval() function, Expressions event handlers, Form Inputs event handlers vs. directives, A Few Words on Unobtrusive JavaScript event listeners, Client-Side Templates event properties, Communicating Between Scopes with $on, $emit, and $broadcast expressions, Expressions, Publishing Model Data with Scopes ExpressJS, Without Yeoman F Factory API call, Convenience Methods factory(), Organizing Dependencies with Modules file upload, File Upload in AngularJS–File Upload in AngularJS filters basics of, An Example: Shopping Cart creating, Formatting Data with Filters formatting data with, Formatting Data with Filters using with repeaters, The Teams List App: Filtering and Controller Communication Firebug, Debugging flow-of-control operators, Expressions for loop, Expressions form elements binding to model properties, Form Inputs hiding/showing, Hiding and Showing form validation controls, Validating User Input, The Templates forward buttons, controllers.js, controllers.js full propagation, Performance Considerations in watch() function binding, Binding select G generic services, Organizing Dependencies with Modules GET requests, JSON Vulnerability, Templates global namespace, Model View Controller, A Few Words on Unobtrusive JavaScript global state, drawbacks of, $location Google Closure, Compilation Google’s content delivery network (CDN), Loading the Script GutHub, The Application H Hashbang mode, HTML5 Mode and Hashbang Mode headers, setting, Setting HTTP Headers Hello, World example, Client-Side Templates, Data Binding History API, HTML5 Mode and Hashbang Mode href attribute, Considerations for src and href Attributes HTML Angular template files, Project Organization HTML extensions directives, Directives HTML sanitization, Sanitizing HTML & the Sanitize Module HTML validation, Directives and HTML Validation HTML5, Changing the DOM with Directives, Directives and HTML Validation, $location, HTML5 Mode and Hashbang Mode HTML5 cookies, Cookies HTTP headers, setting, Setting HTTP Headers HTTP protocol, Talking to Servers I i18n/L10n, Internationalization and Localization IDs, Client-Side Templates, A Few Words on Unobtrusive JavaScript, Templates IE (Internet Explorer), Services, restrict if-else operator, Expressions image tags, Considerations for src and href Attributes index.html, How Do I Get It All Working?

If you’re building an all-Angular application, you should include ng-app as part of the <html> tag, like so: <html ng-app> … </html> This tells Angular to manage all DOM elements in the page. If you’ve got an existing app where some other technology expects to manage the DOM, such as Java or Rails, you can tell Angular to manage only a part of the page by placing it on some element like a <div> within the page. <html> … <div ng-app> … </div> … </html> Model View Controller In Chapter 1, we mentioned that Angular supports the Model View Controller style of application design. Though you have a lot of flexibility in designing your Angular app, you will always have some flavor of: A model containing data that represents the current state of your application. Views that display this data. Controllers that manage the relationship between your model and your views. You’ll create your model using object attributes, or even just primitive types containing your data.

pages: 719 words: 181,090

Site Reliability Engineering: How Google Runs Production Systems by Betsy Beyer, Chris Jones, Jennifer Petoff, Niall Richard Murphy

Air France Flight 447, anti-pattern, barriers to entry, business intelligence, business process, Checklist Manifesto, cloud computing, combinatorial explosion, continuous integration, correlation does not imply causation, crowdsourcing, database schema, defense in depth, DevOps,, fault tolerance, Flash crash, George Santayana, Google Chrome, Google Earth, information asymmetry, job automation, job satisfaction, Kubernetes, linear programming, load shedding, loose coupling, meta analysis, meta-analysis, microservices, minimum viable product, MVC pattern, performance metric, platform as a service, revision control, risk tolerance, side project, six sigma, the scientific method, Toyota Production System, trickle-down economics, web application, zero day

Workflow uses the leader-follower (workers) distributed systems design pattern [Sha00] and the system prevalence design pattern.4 This combination enables very large-scale transactional data pipelines, ensuring correctness with exactly-once semantics. Workflow as Model-View-Controller Pattern Because of how system prevalence works, it can be useful to think of Workflow as the distributed systems equivalent of the model-view-controller pattern known from user interface development.5 As shown in Figure 25-4, this design pattern divides a given software application into three interconnected parts to separate internal representations of information from the ways that information is presented to or accepted from the user.6 Figure 25-4. The model-view-controller pattern used in user interface design Adapting this pattern for Workflow, the model is held in a server called “Task Master.” The Task Master uses the system prevalence pattern to hold all job states in memory for fast availability while synchronously journaling mutations to persistent disk.

We have found that continuous data processing with strong guarantees, as provided by Workflow, performs and scales well on distributed cluster infrastructure, routinely produces results that users can rely upon, and is a stable and reliable system for the Site Reliability Engineering team to manage and maintain. 1 Wikipedia: Extract, transform, load,,_transform,_load 2 Wikipedia: Big data, 3 Jeff Dean’s lecture on “Software Engineering Advice from Building Large-Scale Distributed Systems” is an excellent resource: [Dea07]. 4 Wikipedia: System Prevalence, 5 The “model-view-controller” pattern is an analogy for distributed systems that was very loosely borrowed from Smalltalk, which was originally used to describe the design structure of graphical user interfaces [Fow08]. 6 Wikipedia: Model-view-controller, Chapter 26. Data Integrity: What You Read Is What You Wrote Written by Raymond Blum and Rhandeev Singh Edited by Betsy Beyer What is “data integrity”? When users come first, data integrity is whatever users think it is.

decision-making skills, Structured and Rational Decision Making defense in depth, for data integrity, The 24 Combinations of Data Integrity Failure Modes, Sunday, February 27, 2011, late in the evening, Defense in Depth demand forecasting, Demand Forecasting and Capacity Planning dependency hierarchies, Setting Reasonable Expectations for Monitoring, Dependencies among resources deployment, Deployment(see also continuous build and deployment) development environment, Our Development Environment development/ops split, The Sysadmin Approach to Service Management DevOps, Google’s Approach to Service Management: Site Reliability Engineering Direct Server Response (DSR), Load Balancing at the Virtual IP Address disaster recovery tools, Testing Disaster disaster role playing, Disaster Role Playing disaster testing, Preparedness and Disaster Testing-Defense in Depth and BreadthDisaster and Recovery Testing (DiRT), Preparedness and Disaster Testing disk access, Disk Access Diskerase process, Recommendations distractibility, Distractibility distributed consensus systemsbenefits of, Managing Critical State: Distributed Consensus for Reliability coordination, use in, Distributed Coordination and Locking Services deploying, Deploying Distributed Consensus-Based Systems-Quorum composition locking, use in, Managing Critical State: Distributed Consensus for Reliability monitoring, Monitoring Distributed Consensus Systems need for, Managing Critical State: Distributed Consensus for Reliability overview of, Conclusion patterns for, System Architecture Patterns for Distributed Consensus-Reliable Distributed Queuing and Messaging performance of, Distributed Consensus Performance-Disk Access principles, How Distributed Consensus Works quorum composition, Quorum composition quorum leasing technique, Quorum Leases(see also consensus algorithms) distributed periodic scheduling (see cron) DNS (Domain Name System)EDNS0 extension, Load Balancing Using DNS load balancing using, Load Balancing Using DNS-Load Balancing Using DNS DoubleClick for Publishers (DFP), Case Study: Migrating DFP to F1-Case Study: Migrating DFP to F1 drains, Planned Changes, Drains, or Turndowns DTSS communication files, Origin of the Pipeline Design Pattern dueling proposers situation, Multi-Paxos: Detailed Message Flow durability, Indicators E early detection for data integrity, Third Layer: Early Detection(see also data integrity) Early Engagement Model, Evolving the Simple PRR Model: Early Engagement-Disengaging from a service “embarrassingly parallel” algorithms, Trouble Caused By Uneven Work Distribution embedded engineers, Embedding an SRE to Recover from Operational Overload-Conclusion emergency preparedness, Sunday, February 27, 2011, late in the eveningcross-industry lessons, Preparedness and Disaster Testing emergency responsechange-induced emergencies, Change-Induced Emergency-What we learned essential elements of, Emergency Response Five Whys, Ask “what,” “where,” and “why”, Example Postmortem guidelines for, Emergency Response initial response, What to Do When Systems Break lessons learned, Keep a History of Outages overview of, Conclusion process-induced emergencies, Process-Induced Emergency solution availability, All Problems Have Solutions test-induced emergencies, Test-Induced Emergency encapsulation, Load Balancing at the Virtual IP Address endpoints, in debugging, Examine engagements (see SRE engagement model) error budgetsbenefits of, Benefits best practices for, Error Budgets forming, Forming Your Error Budget guidelines for, Pursuing Maximum Change Velocity Without Violating a Service’s SLO motivation for, Motivation for Error Budgets error rates, Indicators, The Four Golden Signals Escalator, Escalator ETL pipelines, Origin of the Pipeline Design Pattern eventual consistency, Managing Critical State: Distributed Consensus for Reliability executor load average, Utilization Signals F failures, best practices for, Fail Sanely(see also cascading failures) fake backends, Production Probes false-positive alerts, Tagging feature flag frameworks, Feature Flag Frameworks file descriptors, File descriptors Five Whys, Ask “what,” “where,” and “why”, Example Postmortem flow control, A Simple Approach to Unhealthy Tasks: Flow Control FLP impossibility result, How Distributed Consensus Works Flume, Challenges with the Periodic Pipeline Pattern fragmentation, Load Balancing at the Virtual IP Address G gated operations, Enforcement of Policies and Procedures Generic Routing Encapsulation (GRE), Load Balancing at the Virtual IP Address GFE (Google Frontend), Life of a Request, Load Balancing in the Datacenter GFS (Google File System), Detecting Inconsistencies with Prodtest, Highly Available Processing Using Leader Election, Extended Infrastructure-Tracking the State of Cron Jobs, Overarching Layer: Replication global overload, Per-Customer Limits Global Software Load Balancer (GSLB), Networking Gmail, Gmail: Predictable, Scriptable Responses from Humans, Gmail—February, 2011: Restore from GTape Google Apps for Work, Target level of availability Google Compute Engine, Indicators Google production environmentbest practices for, Fail Sanely-SRE Teams complexity of, Software Engineering in SRE datacenter topology, Hardware development environment, Our Development Environment hardware, Hardware Shakespeare search service, Shakespeare: A Sample Service-Job and Data Organization software infrastructure, Our Software Infrastructure system software, System Software That “Organizes” the Hardware-Monitoring and Alerting Google Workflow systemas model-view-controller pattern, Workflow as Model-View-Controller Pattern business continuity and, Ensuring Business Continuity correctness guarantees, Workflow Correctness Guarantees development of, Introduction to Google Workflow stages of execution in, Stages of Execution in Workflow graceful degradation, Load Shedding and Graceful Degradation GTape, Gmail—February, 2011: Restore from GTape H Hadoop Distributed File System (HDFS), Storage handoffs, Clear, Live Handoff “hanging chunk” problem, Trouble Caused By Uneven Work Distribution hardwaremanaging failures, System Software That “Organizes” the Hardware software that “organizes”, System Software That “Organizes” the Hardware-Monitoring and Alerting terminology used for, Hardware health checks, Stop Health Check Failures/Deaths, Practices hermetic builds, Hermetic Builds hierarchical quorums, Quorum composition high-velocity approach, Principles, High Velocity hotspotting, Picking the Right Subset I idempotent operations, Resolving Inconsistencies Idempotently, Cron Jobs and Idempotency incident managementbest practices for, In Summary effective, Managing Incidents formal protocols for, Feeling Safe incident management process, What we learned, Elements of Incident Management Process incident response, Practices managed incident example, A Managed Incident roles, Recursive Separation of Responsibilities template for, Example Incident State Document unmanaged incident example, Unmanaged Incidents when to declare an incident, When to Declare an Incident infrastructure servicesidentifying risk tolerance of, Identifying the Risk Tolerance of Infrastructure Services improved SRE through automation, Faster Action integration proposals, Enforcement of Policies and Procedures integration tests, Integration tests, Integration intent-based capacity planningAuxon implementation, Introduction to Auxon-Introduction to Auxon basic premise of, Our Solution: Intent-Based Capacity Planning benefits of, Our Solution: Intent-Based Capacity Planning defined, Intent-Based Capacity Planning deploying approximation, Approximation driving adoption of, Raising Awareness and Driving Adoption-Designing at the right level precursors to intent, Precursors to Intent requirements and implementation, Requirements and Implementation: Successes and Lessons Learned selecting intent level, Intent-Based Capacity Planning team dynamics, Team Dynamics interruptscognitive flow state and, Cognitive Flow State dealing with, Dealing with Interrupts dealing with high volumes, General suggestions determining approach to handling, Factors in Determining How Interrupts Are Handled distractibility and, Distractibility managing operational load, Managing Operational Load on-call engineers and, On-call ongoing responsibilities, Ongoing responsibilities polarizing time, Polarizing time reducing, Reducing Interrupts ticket assignments, Tickets IRC (Internet Relay Chat), A Recognized Command Post J jobs, Managing Machines Jupiter network fabric, Hardware L labelsets, Labels and Vectors lame duck state, A Robust Approach to Unhealthy Tasks: Lame Duck State latencydefined, Choosing a Strategy for Superior Data Integrity measuring, Indicators monitoring for, The Four Golden Signals launch coordinationchecklist, The Launch Checklist-Example action items, Launch Coordination Checklist engineering (LCE), Launch Coordination Engineering, Development of LCE-Infrastructure churn(see also product launches) lazy deletion, The 24 Combinations of Data Integrity Failure Modes leader election, Managing Critical State: Distributed Consensus for Reliability, Highly Available Processing Using Leader Election lease systems, Reliable Distributed Queuing and Messaging Least-Loaded Round Robin policy, Least-Loaded Round Robin level of service, Service Level Objectives(see also service level objectives (SLOs)) living incident documents, Live Incident State Document load balancingdatacenterdatacenter services and tasks, Load Balancing in the Datacenter flow control, A Simple Approach to Unhealthy Tasks: Flow Control Google's application of, Load Balancing in the Datacenter handling overload, Handling Overload ideal CPU usage, The Ideal Case, The Pitfalls of “Queries per Second” lame duck state, A Robust Approach to Unhealthy Tasks: Lame Duck State limiting connections pools, Limiting the Connections Pool with Subsetting-A Subset Selection Algorithm: Deterministic Subsetting packet encapsulation, Load Balancing at the Virtual IP Address policies for, Load Balancing Policies-Weighted Round Robin SRE software engineering dynamics, Team Dynamics distributed consensus systems and, Capacity and Load Balancing frontendoptimal solutions for, Power Isn’t the Answer using DNS, Load Balancing Using DNS-Load Balancing Using DNS virtual IP addresses (VIPs), Load Balancing at the Virtual IP Address policyLeast-Loaded Round Robin, Least-Loaded Round Robin Round Robin, Simple Round Robin Weighted Round Robin, Weighted Round Robin load shedding, Load Shedding and Graceful Degradation load tests, Overload Behavior and Load Tests lock services, Lock Service, Distributed Coordination and Locking Services logging, Examine Lustre, Storage M machinesdefined, Hardware, Definitions managing with software, Managing Machines majority quorums, Number of Replicas MapReduce, Challenges with the Periodic Pipeline Pattern mean timebetween failures (MTBF), Testing for Reliability, Expect Testing Fail to failure (MTTF), Emergency Response to repair (MTTR), Emergency Response, Faster Repairs, Testing for Reliability memory exhaustion, Memory Mencius algorithm, Stable Leaders meta-software, The Use Cases for Automation Midas Package Manager (MPM), Packaging model-view-controller pattern, Workflow as Model-View-Controller Pattern modularity, Modularity Moiré load pattern in pipelines, Moiré Load Pattern monitoring distributed systemsavoiding complexity in, As Simple as Possible, No Simpler benefits of monitoring, Why Monitor?

pages: 485 words: 74,211

Developing Web Applications with Haskell and Yesod by Michael Snoyman

create, read, update, delete, database schema, Debian, domain-specific language, don't repeat yourself, full text search, MVC pattern, web application

By using built-in Yesod constructs like defaultLayout and getMessage, you’ll get a consistent look-and-feel throughout your site, including pages automatically generated by Yesod such as error pages and authentication. We haven’t covered all the methods in the Yesod typeclass in this chapter. For a full listing of methods available, you should consult the Haddock documentation. Chapter 7. Routing and Handlers If we look at Yesod as a Model-View-Controller framework, routing and handlers make up the controller. For contrast, let’s describe two other routing approaches used in other web development environments: Dispatch based on file name. This is how PHP and ASP work, for example. Have a centralized routing function that parses routes based on regular expressions. Django and Rails follow this approach. Yesod is closer in principle to the latter technique.

|] handleDateR :: Integer -> Text -> Int -> Handler RepPlain -- text/plain handleDateR year month day = return $ RepPlain $ toContent $ T.concat [month, " ", T.pack $ show day, ", ", T.pack $ show year] getWikiR :: [Text] -> Handler RepPlain getWikiR = return . RepPlain . toContent . T.unwords The arguments have the types of the dynamic pieces for each route, in the order specified. Also, notice how we are able to use both RepHtml and RepPlain. The Handler Monad The vast majority of code you write in Yesod sits in the Handler monad. If you are approaching this from an MVC (Model-View-Controller) background, your Handler code is the Controller. Some important points to know about Handler: It is an instance of MonadIO, so you can run any IO action in your handlers with liftIO. By the way, liftIO is exported by the Yesod module for your convenience. Like Widget, Handler is a fake-monad-transformer. It wraps around a ResourceT IO monad. We discuss this type at length in the conduits appendix, but for now, we’ll just say it let’s you safely allocate resources.

Chapter 13. Yesod’s Monads As you’ve read through this book, there have been a number of monads that have appeared: Handler, Widget, and YesodDB (for Persistent). As with most monads, each one provides some specific functionality: Handler gives access to the request and allows you to send responses, a Widget contains HTML, CSS, and JavaScript, and YesodDB let’s you make database queries. In Model-View-Controller (MVC) terms, we could consider YesodDB to be the model, Widget to be the view, and Handler to be the controller. So far, we’ve presented some very straightforward ways to use these monads: your main handler will run in Handler, using runDB to execute a YesodDB query, and defaultLayout to return a Widget, which in turn was created by calls to toWidget. However, if we have a deeper understanding of these types, we can achieve some fancier results.

pages: 203 words: 14,242

Ship It!: A Practical Guide to Successful Software Projects by Jared R. Richardson, William A. Gwaltney

continuous integration, David Heinemeier Hansson, Donald Knuth, index card, MVC pattern, place-making, Ruby on Rails, web application

Software Development Times, March 2001. 185 Index A C Accidental choices, 3 Agile development, 175 Agility, 11, 64, 106, 160 Ambient orb, 33 Analysis paralysis, 107 Ant, 166 AntHill, 169 Approving code, 97 Architecture and collaboration, 111 Aristotle, 1 Automake, 165 Automated testing maintenance of, 153 Automatic build systems, 98, 99, 9 Canned data, 107 see also Mock objects Capability maturity model, 175 Carmack, John, 12 Circular dependency, 138 Clover, 179 Clumping, bugs, 37 CMM, see Capability maturity model Cobertura, 179 Cockburn, Alistair, 98 Code change notifications, 6, 94, 143 Code freeze, 66 Code libraries, 20 Code reviews, 6, 88, 143 and team cohesion, 146 virtual, 95 Code, legacy, 129 Cognitive overload, 74 Collaboration, 55 Conflicts, 19 Continuous integration, 10, 30, 134, 137, 143, 169 Continuous testing, 133 Continuum, 169 Cooking ham, 8 Covey, Stephen, 60 Craftsmanship, 101 Critical path, 53 Cross-platform testing, 133 CruiseControl, 30, 169 CruiseControl.NET, 10, 169 Crystal, 176 CVS, 24, 162 B Backups, 23 Batch file, 26, 165 BitKeeper, 162 Blog, 85n Broken builds, 34 Broken windows, 119 Buddy builds, 10 Bugs distribution, 37 finding, 90 introducing, 13 regression, 31 reproducing, 135 Bugzilla, 172 Build machine, 17 Build times, 34 Builds, 25, 30 automating, 98, 129 Burn rate, 79 Bus number, 114 Buy-in, see Participation D Daily meetings, 6, 78 example, 83 D AMAGE C ONTROL rules for, 87 DamageControl, 169 Deadlines, 65, 69 Death March project, 156 Decoupling, 110 see also Circular dependancy Defect detection, 90 Defect-driven testing, 46, 154 Deliberate choices, 3 Deliverables, 9 Dependancy, circular, 138 Deprecated routines, 93 Dillard, Annie, 2n Disappearing products, 20 Documentation, 59 Done, determining when, 64, 159 E E-Tester, 179 EDIF, 51 Email notification, 99 Encapsulation, 109, 123 Estimation, 60, 63, 156 Excellence, 2 Expansion, 12 Expectations, 139 eXtreme Programming, 175 F Feature boxing, 65 Feature creep, 40, 158 Feature list, 72 Features, fluff, 63, 74 Features vs. issues, 39 Feedback, 64, 160, 161 Fit, 179 Fitnesse, 179 FogBugz, 172 Ford, Henry, 128 Foundation, 4 Functional tests, 44 Future expansion, 12 G Goals, 64 Grandma, 9 Groovy, 166 H Habits, 2, 155 187 M EETINGS Ham, 8 Heroism, 83 Hippocratic Oath, 93 HTMLUnit, 179 HTTPUnit, 179 I IDE, 16n IDE in batch mode, 27 Information radiators, 98 Infrastructure, 5 Infrastructure overload, 107 Integration tests, 44 Interfaces, 108, 109, 113 Interruptions, 74, 82 Introducing bugs, 13 Introducing practices, 150 Issue distribution, 37 Issues vs. features, 39 Iteration, 106 J Jelly, 51 JIRA, 172 JUnit, 178 JUnitPerf, 178 JWebUnit, 179 L Lava lamps, 33 Leaders, growing, 85 Legacy code, 129 Librarian, 16 Library code, 20 List, The, 57 Load tests, 44 LoadRunner, 179 Losing work, 13 M MAD reviews, 88 make, 165 Manager, nontechnical, 70 Manifesto, agile, 11 Maven, 51, 167 Maven 2, 167 MbUnit, 178 McCarthy, Justin, 9 Meeting alternatives, 82 Meetings daily, 6, 78 M ENTORING frequency, 78 Mentoring, 90, 155 MetaCheck, 42 Micromanagement, 145 Milestone, 116 Mock client tests, 44, 45, 129, 132 Mock Object, 108 Model-View-Controller , 123 Monitoring, 76 Morale, 124 MVC, see Model-View-Controller Myopia, 82 N NAnt, 10, 166 Notification, code change, 6 NUnit, 10, 178 O Open formats, 51 P Pair programming, 88 Parking lot therapy, 141 Participation, 147 Partitioning test data, 18 Patterns, 91 Peer pressure, 90 Performance tests, 44 Perl, 166 Perl mantra, 150n Plante, Dominique, 9 Plog, 85 Post-it Notes, failure of, 37 PR-Tracker, 172 Practice introduction, 150 Prioritization, 59, 61, 62, 64, 74 Problem solving, 96, 118 shared, 81 Process, 5 defined, 105 Production environment, 116 Products, disappearing, 20 Python, 166 Q Quarry worker’s creed, 4 R Rake, 166 188 T ESTING Rational unified process, 176 Raving fan, 151 Raymond, Eric S., 92 Refactoring, 90, 92 Regression, 31 Repository, 16 Requirements, 7, 64, 75, 124, 125, 160 Return on investment, see ROI Reviews, code, 6 Rogues, 141 ROI, 33, 90 RSS feed, 33, 62, 99 defined, 62 Rubber ducking, 89 Ruby, 166 RUP, see Rational unified process S SCM, 14, 19 Scrum, 176 Sharing code, 16 Shell scripts, 26, 165 Sign your work, 92, 101 Smoke tests, 44 Software practices, 1 Source code management system, 14, 19 Spolsky, Joel, 57 Spreadsheet, 57 Sprint, see Iteration Stakeholders, 60, 70, 73 defined, 71 Stealth practice, 152 Subversion, 10, 21, 24, 162 SUnit, 178 Supertools, 15 System object, 109 Systir, 179 T TDB, see Tracer bullet development Teams building, 146 communication, 81 and cooking, 110 trusting, 65 Tech lead, 6 defined, 69 Techniques, 5 Test Driven Refactoring, 131 Testing T ESTING HARNESS partitioning data, 18 Testing harness, 42 Testing, kinds of, 43 The List, 6, 57 example, 67 personal use, 60 rules for, 61 Third-party code, 20 Throwing code out, 120 Time boxing, 65 Toolkit, 3 Tracer bullet development, 6, 104, 175 benefits, 123 example, 120 Tracer bullets defined, 104 Truck number, see Bus number Tumbleweed developers, 79, 80 U Undo button, 19 Unit tests, 43 189 XP V VC, see Source code management system Version control, see Source code management system Visual SourceSafe, 162 W Watercooler, 146 Waterfall model, 119 Watir, 179 wiki, 58, 69 WinRunner, 179 Wizard code, 54 Work, losing, 13 X X10, 33 XML, 51 XP, see eXtreme programming Pragmatic Starter Kit Series Version Control.

pages: 680 words: 157,865

Beautiful Architecture: Leading Thinkers Reveal the Hidden Beauty in Software Design by Diomidis Spinellis, Georgios Gousios

Albert Einstein, barriers to entry, business intelligence, business process, call centre, continuous integration, corporate governance, database schema, Debian, domain-specific language, don't repeat yourself, Donald Knuth,, fault tolerance, Firefox, general-purpose programming language, iterative process, linked data, locality of reference, loose coupling, meta analysis, meta-analysis, MVC pattern, peer-to-peer, premature optimization, recommendation engine, Richard Stallman, Ruby on Rails, semantic web, smart cities, social graph, social web, SPARQL, Steve Jobs, Stewart Brand, traveling salesman, Turing complete, type inference, web application, zero-coupon bond

* * * [56] Note that what most graphical user interfaces call a window, Emacs calls a frame, since Emacs uses the term “window” as described earlier. This is unfortunate, but Emacs’s terminology was established well before the widespread use of graphical user interfaces, and Emacs’s maintainers seem uninclined to change it. Emacs’s Architecture Emacs’s architecture follows the widely used Model-View-Controller pattern for interactive applications, as shown in Figure 11-2. In this pattern, the Model is the underlying representation of the data being manipulated; the View presents that data to the user; and the Controller takes the user’s interactions with the View (keystrokes, mouse gestures, menu selections, and so on) and manipulates the Model accordingly. Throughout this chapter, I’ll capitalize Model, View, and Controller when I’m referring to elements of this pattern.

Throughout this chapter, I’ll capitalize Model, View, and Controller when I’m referring to elements of this pattern. In Emacs, the Controller is almost entirely Emacs Lisp code. Lisp primitives manipulate buffer contents (the Model) and the window layout. Redisplay code (the View) updates the display without explicit guidance from the Lisp code. Neither the buffer’s implementation nor the redisplay code can be customized by Lisp code. Figure 11-2. The Model-View-Controller pattern in Emacs The Model: Buffers Emacs edits text files, so the heart of Emacs’s Model is the buffer type, which holds text. A buffer is simply a flat string, where newline characters mark line endings; it is not a list of lines, nor is it a tree of nodes, like the document object model that web browsers use to represent HTML documents. Emacs Lisp has primitive operations on buffers that insert and delete text, extract portions of buffer text as strings, and search for matches of exact strings or regular expressions.

The latter used the same dynamic programming techniques employed by file comparison programs such as diff to find the smallest set of operations sufficient to transform the old screen into the new screen. In modern times, although Emacs still uses these algorithms to minimize update work, most of this effort is wasted, as faster processors and faster links between the computer and the display allow simpler algorithms to perform perfectly well. The Controller: Emacs Lisp The heart of Emacs is its implementation of its own dialect of Lisp. In Emacs’s realization of the Model-View-Controller pattern, Lisp code dominates the Controller: almost every command you invoke, whether from the keyboard, a menu, or by name, is a Lisp function. Emacs Lisp is the key to Emacs’s ability to successfully accommodate the wide range of functionality that Emacs has grown to offer. The Five-Minute Lisp Tutorial People new to Lisp often find the language hard to read. This is mostly because Lisp has fewer syntactic constructs than most languages, but works those constructs harder to get an even richer vocabulary of features.

pages: 323 words: 65,306

Programming in CoffeeScript by Mark Bates

don't repeat yourself,, MVC pattern, node package manager, Ruby on Rails, single page application, web application

Unless otherwise indicated, you should be able to run the examples in your terminal, like so: > coffee So now that you know how to run the examples in this book, as soon as you have CoffeeScript installed, why don’t you meet me at Chapter 1 and we can get started? See you there. Notes 1. 2. 3. 4. 5.–view–controller 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. Part I: Core CoffeeScript In this first half of the book we are going to cover everything you’ve ever wanted to know, and everything you’ll ever need to know, about CoffeeScript.

Then we learned how to use views and events to manage the elements on our page and how they interact with each other. This chapter just scratches the surface of what Backbone.js has to offer in terms of writing highly responsive, well-organized front ends for your applications. I encourage you to seek out some of the great tutorials, blog posts, and screencasts on Backbone to learn more about it. Notes 1. 2.–view–controller 3. 4. Seriously, I’m not just plugging Backbone in this chapter because Jeremy also wrote CoffeeScript. I really do love it and use it all the time. 5. 6. 7. 8. 9. Index @ alias, 51–52 => (fat arrow), 154–156 \ (back slashes), 5 / (forward slashes), 76 A adding compilers to browsers, 6–7 form to client-side todo list application, 242–247 jQuery to client-side todo list application, 240–241 views to todo list application, 268–273 aliases, 46–47 @ alias, 51–52 and alias, 49–50 Boolean aliases, 50–51 not alias, 48–49 or alias, 49–50 and alias, 49–50 anonymous wrapper function, 20–22 APIs, writing todo API, 225–226 app server building with Node.js, 199–213 testing with Node.js, 214–215 arguments, 70–72 default arguments, 72–75 splats, 75–79 arithmetic operators, 33–35 arrays, 81–90 destructing assignment, 86–90 iterating, 105–106 slicing, 92–94 swapping assignment, 85–86 testing inclusion, 83–84 values injecting, 95–96 replacing, 94–95 Ashkenas, Jeremy, 255 assignment operators, 35–39 asynchronous programming, 151–154 attributes, retrieving from objects, 101–103 B back slashes (\), 5 Backbone, 255–256 configuring for todo list application, 256–259 todo model, writing, 256–259 todos creating, 265–268 listing with view, 263–265 bare flag, 9–10 beforeEach function, 181–187 binding, 151–158 block comments, 30 Boolean aliases, 50–51 Bootstrap, building client-side todo list application, 237–240 browsers, in-browser compilation, 6–7 build task (Cake), 167 building objects, 96–101 todo list application client-side, 237–252 controller, cleaning up, 232–236 Express, setting up, 218–222 MongoDB, setting up, 222–225 server-side, 217 todo API, writing, 225–226 by keyword, 106–107 C Cake, 161 tasks invoking, 167–169 options, 163–167 running, 163 writing, 162–163 Cakefiles, 161 calling functions, 68–70 classes defining, 123–124 extending, 137–145 inheritance, 137–145 scope, 127–137 class-level functions, 145–150 clean task (Cake), 167 cleaning up todo list application controller, 232–236 client-side todo list application, building, 237–252 closing REPL, 5 code, not repeating, 68 coffee command, 8–9 CoffeeScript, declaring variables, 19–20 collections arrays destructing assignment, 86–90 injecting values, 95–96 iterating, 105–106 replacing values, 94–95 slicing, 92–94 swapping assignment, 85–86 testing inclusion, 83–84 ranges, reverse ranges, 91–92 command-line compilation, 7–8 comments, 29–30 block comments, 30 inline comments, 29–30 comparison operators, 39–42 compile flag, 7–8 compiling command-line compilation, 7–8 in-browser compilation, 6–7 comprehensions, 116–118 concatenation, forward slashes (/), 76 conditional statements if statement, 53–54 if/else if statement, 56–58 if/else statement, 54–56 inline conditionals, 60 switch case statements, 60–63 unless statement, 58–60 configuring Backbone for todo list application, 256–259 Jasmine, 172–175 constructor function, 126–127 creating objects, 96–101 custom matchers (Jasmine), defining, 187–190 D declaring variables in CoffeeScript, 19–20 in JavaScript, 18–19 default arguments, 72–75 defining Cake tasks, 162–163 classes, 123–124 functions, 68–70 arguments, 70–72 default arguments, 72–75 parentheses, 72 matchers (Jasmine), 187–190 regular expressions, 31 deleting models from views (todo list application), 273–274 todos in client-side todo list application, 252 “describe” block (Jasmine), writing, 175 destructing assignment, 86–90 do keyword, 119–120 dot notation, 101 E executing CoffeeScript files, 11 existential operator, 43–46 Express, building todo list application, 218–222 extended regular expressions, 31 extending classes, 137–145 F fat arrow (=>), 154–156 flags bare flag, 9–10 compile flag, 7–8 output flag, 9 print flag, 10 watch flag, 10–11 for loops by keyword, 106–107 when keyword, 107, 109–110 form, adding to client-side todo list application, 242–247 function keyword, 16 functions, 65–68 anonymous wrapper function, 20–22 arguments, 70–72 default arguments, 72–75 splats, 75–79 beforeEach, 181–187 binding, 151–158 class-level, 145–150 constructor, 126–127 defining, 68–70, 125–126 overriding, 142–145 prototype functions, 110, 150–151 G-H Hello World program, Node.js, 195–197 heredocs, 28–29 HTML files in-browser compilation, 6–7 I if statement, 53–54 if/else if statement, 56–58 if/else statement, 54–56 in-browser compilation, 6–7 inheritance, 137–145 injecting array values, 95–96 inline comments, 29–30 inline conditionals, 60 installing Jasmine, 172 Node.js, 194–195 interpolation, string interpolation, 23–25 iterating arrays, 105–106 J-K Jasmine “describe” block, writing, 175 installing, 172 matchers, defining, 187–190 setting up, 172–175 testing with, 175–176 beforeEach function, 181–187 unit testing, 176–181 JavaScript Backbone, 255–256 todo model, writing, 256–259 todos, listing with a view, 263–265 Node.js, 193–194 app server, building, 199–213 app server, testing, 214–215 Hello World program, 195–197 installing, 194–195 streaming APIs, writing, 197–199 variables, declaring, 18–19 jQuery, adding to client-side todo list application, 240–241 keywords, var, 19 L listing existing todos in todo list application, 247–248 literal strings, 25–28 long options, 163 loops comprehensions, 116–118 do keyword, 119–120 for loops by keyword, 106–107 when keyword, 107, 109–110 until loops, 114–115 while loops, 113–114 M-N MongoDB, setting up, 222–225 Mongoose, finding todos in todo list application, 227–228 new keyword, 124 Node.js, 193–194 app server building, 199–213 testing, 214–215 Hello World program, 195–197 installing, 194–195 streaming APIs, writing, 197–199 NPM (Node Package Management), 193 Express, setting up, 218–222 O objects attributes, retrieving, 101–103 building, 96–101 destructing assignment, 103–105 iterating, 108–113 operators aliases, 46–47 @ alias, 51–52 and alias, 49–50 Boolean aliases, 50–51 not alias, 48–49 or alias, 49–50 arithmetic operators, 33–35 assignment operators, 35–39 comparison operators, 39–42 existential operator, 43–46 string operators, 42–43 options for Cake tasks, 163–167 or alias, 49–50 output flag, 9 overriding functions, 142–145 P parentheses, 16–17 comprehensions, 117 functions, calling, 72 print flag, 10 prototype function, 110 prototype functions, 150–151 Q-R querying todo list application, 227–228 quitting REPL, 5 ranges, 90–96 reverse ranges, 91–92 regular expressions, extended regular expressions, 31 REPL, 3–5 \ (back slashes), 5 Node.js, 194 quitting, 5 replacing array values, 94–95 retrieving attributes from objects, 101–103 reverse ranges, 91–92 running Cake tasks, 163 S scope in classes, 127–137 servers (Node.js), creating, 195–197 server-side, building todo list application, 217 setting up Jasmine, 172–175 short options, 163 significant whitespace, 14–16 slicing arrays, 92–94 splats, 75–79 streaming APIs, writing with Node.js, 197–199 string interpolation, 23–25 string operators, 42–43 strings heredocs, 28–29 literal strings, 25–28 switch case statements, 60–63 synchronous programming, 151 syntax function keyword, 16 parentheses, 16–17 ranges, 90 significant whitespace, 14–16 T tasks Cake invoking, 167–169 options, 163–167 running, 163 writing, 162–163 TDD (test-driven development), 171 terminating REPL, 5 testing with Jasmine, 175–176 beforeEach function, 181–187 matchers, defining, 187–190 TDD, 171 unit testing, 176–181 testing inclusion, Node.js app server, 214–215 todo list application Backbone configuring, 256–259 todos, creating, 265–268 todos, listing with a view, 263–265 client-side building, 237–252 exisiting todos, listing, 247–248 form, creating, 242–247 jQuery, adding, 240–241 todos, deleting, 252 todos, updating, 248–251 controller, cleaning up, 232–236 server-side building, 217 todo API, writing, 225–226 todos creating, 228–230 finding, 227–228 updating, 230–232 views adding, 268–273 deleting models from, 273–274 todo list application, building Express, setting up, 218–222 MongoDB, setting up, 222–225 Twitter Bootstrap todo list application client-side, building, 237–240 U unit testing with Jasmine, 176–181 unless statement, 58–60 until loops, 114–115 updating todo list application, 230–232 todos in client-side todo list application, 248–251 V var keyword, 19 variables, declaring in CoffeeScript, 19–20 in JavaScript, 18–19 views adding to todo list application, 268–273 models, deleting from (todo list application), 273–274 W-X-Y-Z watch flag, 10–11 when keyword, 109–110 while loops, 113–114 writing Cake tasks, 162–163 “describe” block (Jasmine), 175 todo API, 225–226 todo model with Backbone, 256–259 Footnotes Acknowledgments 1 Many at my publishing house thought that my acknowledgments section, as well as other parts of this book, were a bit risqué, so the original has been edited down to what you see here.

pages: 135 words: 31,098

ClojureScript: Up and Running by Stuart Sierra, Luke Vanderhart

domain-specific language, Firefox, MVC pattern, Paul Graham, web application

If you want more precise control over how your code is compiled, you can invoke the ClojureScript compiler directly from Clojure. Future versions of Clojure and ClojureScript will likely include some kind of conditional evaluation or “feature expressions,” making it possible to maintain a single source file that targets multiple host environments. In any case, the possibilities of having a unified language across servers and web browsers are exciting. Consider some examples: The classic Model-View-Controller pattern, in which the Model can be mirrored on both client and server Unit-testing client and server code in the same process Debugging client code before running it in a browser Summary Being able to work in the same language and data model in both web browsers and web servers is the most compelling feature of ClojureScript. With a little care, most algorithmic or data-centric code can be made to work identically in Clojure and ClojureScript.

pages: 612 words: 187,431

The Art of UNIX Programming by Eric S. Raymond

A Pattern Language, Albert Einstein, barriers to entry, bioinformatics, Clayton Christensen, combinatorial explosion, commoditize, correlation coefficient, David Brooks, Debian, domain-specific language, don't repeat yourself, Donald Knuth, Everything should be made as simple as possible, facts on the ground, finite state, general-purpose programming language, George Santayana, Innovator's Dilemma, job automation, Larry Wall, MVC pattern, pattern recognition, Paul Graham, peer-to-peer, premature optimization, pre–internet, publish or perish, revision control, RFC: Request For Comment, Richard Stallman, Robert Metcalfe, Steven Levy, transaction costs, Turing complete, Valgrind, wage slave, web application

Owen Taylor, maintainer of the GTK+ library widely used for writing user interfaces under X, beautifully brings out the engineering benefits of this kind of partitioning at the end of his note Why GTK_MODULES is not a security hole; he finishes by writing "[T]he secure setuid program is a 500 line program that does only what it needs to, rather than a 500,000 line library whose essential task is user interfaces". This is not a new idea. Xerox PARC's early research into graphical user interfaces led them to propose the “model-view-controller” pattern as an archetype for GUIs. The “model” is what in the Unix world is usually called an “engine”. The model contains the domain-specific data structures and logic for your application. Database servers are archetypal examples of models. The “view” part is what renders your domain objects into a visible form. In a really well-separated model/view/controller application, the view component is notified of updates to the model and responds on its own, rather than being driven synchronously by the controller or by explicit requests for a refresh. The “controller” processes user requests and passes them as commands to the model.

The “controller” processes user requests and passes them as commands to the model. In practice, the view and controller parts tend to be more closely bound together than either is to the model. Most GUIs, for example, combine view and controller behavior. They tend to be separated only when the application demands multiple views of the model. Under Unix, application of the model/view/controller pattern is far more common than elsewhere precisely because there is a strong “do one thing well” tradition, and IPC methods are both easy and flexible. An especially powerful form of this technique couples a policy interface (often a GUI combining view and controller functions) with an engine (model) that contains an interpreter for a domain-specific minilanguage. We examined this pattern in Chapter 8, focusing on minilanguage design; now it's time to look at the different ways that such engines can form components of larger systems of code.

Scala in Action by Nilanjan Raychaudhuri

continuous integration, create, read, update, delete, database schema, domain-specific language, don't repeat yourself,, failed state, fault tolerance, general-purpose programming language, index card, MVC pattern, type inference, web application

draggable method Driver class DRY (don’t-repeat-yourself) code DSL DTO (data transfer object) dynamic languages, transitioning from Dynamic type dynamic typing E e.hasMoreElements() method e.withFilter efficiency Elem type EmployeePayrollVisitor end-to-end test environment, for test-driven development equals method Erlang error detection errorLogger() method eta-expansion evenFilter event-based actors exception handling overview extensible components challenge of solving expression problem extensible languages, Scala as external load balancer ExternalPriceCalculator, 2nd, 3rd external-price-calculator-actor-dispatcher externalPriceSource externalPriceSourceCalculator, 2nd ExternalVendor, 2nd ExternalVendor.findAll ExternalVendorProxyActor, 2nd Extractor object, 2nd F F[_] type factory pattern fault tolerance File class file.getName() method FileToCount type, 2nd filter method, 2nd find method findAllByPhase method, 2nd findAllStoriesByPhase method findByDescription, 2nd findCalculator function finder method, 2nd findLowestPrice method findOne method, 2nd FindPrice message, 2nd, 3rd firstName parameter flatMap function, 2nd floating-point types foldLeft method, 2nd, 3rd foldRight method, 2nd forAll method for-comprehensions overview using with collections fork-join fullClasspath Function type Function1 trait functional languages, Scala as Functional Object pattern functional objects functional programming, 2nd ADTs advantages of, 2nd defined function composition function currying higher-order functions methods vs. functions monads managing state using methods used with moving from OOP to modeling purely functional programs object-oriented patterns pure vs. impure programming partial functions pure functional programs recursion in functional style, dependency injection Future divide and conquer mixing with actors vs using actors G Gen class, 2nd, 3rd GenTraversableOnce, 2nd GET method Get method getChronologyUsed() method getCount method getEntity() method getName() method getOrElse method getOrElseUpdate method getResource() method gets method getSender() method Global object greet method GreetingsActor H handle method head :: tail head recursion Hewitt, Carl hierarchy of classes of collections of parallel collections higher-kinded types, 2nd higher-order functions, 2nd Hindley-Milner type host parameter HTTP method, 2nd, 3rd http.proxy environment variable HttpClient library HttpGet method HttpServlet HttpServletRequest Hughes, John I I/O monad identifiers immutable collections immutable data, vs. mutable immutable objects implicit conversion implicit keyword implicit parameters dependency injection overview, 2nd implicits import statements importance, of testing impure programming, vs. pure programming InCompleteOrder Infix Operation pattern init() method, 2nd, 3rd, 4th input Int object Int type, 2nd, 3rd integer types Integer.parseInt integration test, 2nd, 3rd interactive mode internal load balancer InternalPriceCalculator, 2nd, 3rd InternalPriceCalculatorActor internal-price-calculator-actor-dispatcher interoperability with Java Java classes in Scala checked exceptions generics static members Scala classes in Java Scala web applications using Java frameworks model, view, controller using Spring configuration inTransaction method, 2nd invariant, 2nd io.monads package IOMonad type IOResource isDefinedAt method isEmpty method isLeft method isolation isRight method Iterable trait J JapanPayroll method JAR file Java byte code Java class Java Database Connectivity. See JDBC. Java driver, 2nd, 3rd, 4th Java interface, 2nd Java Virtual Machine. See JVM.

TestFindByQuery.scala testing asynchronous messaging systems behavior-driven development specifications for using Specs2 dependency injection cake pattern implicit parameters in functional style structural typing using Spring framework importance of test-driven development setting up environment using JUnit using ScalaCheck example of generators for testing string behavior TestPricingSystem testShouldReturnExternalPrice() this() method, 2nd, 3rd threads, concurrent programming using, challenges of throwableToLeft toString method total function toXml method Trait class traits, 2nd, 5th and class linearization stackable transaction parameter TransactionFailure Traversable parameter trait, 2nd try-finally block Tuple, overview tx method, 2nd type abstraction bounds inference parameterization parameters projection variance type classes, ad hoc polymorphism with modeling orthogonal concerns using solving expression problem using TypedActor types, 7th character floating-point higher-kinded types integer phantom types string structural types XML U unapply method, 2nd, 3rd unapplySeq method Unicode method Unit method universal traits Unix pipes SBT on UntypedActor up$extension method Updatable trait UpdatableCollection class, 2nd uppercase characters, finding url property UrlBasedViewResolver class USContractorPayrollSystem user story UseResource class USPayroll class USPayroll method util.Random class V validate method, 2nd ValidationException, 2nd value classes rules var prefixes variables, overview Vector collection Vector() method views views.index() method W WAR file weather function web applications connecting to databases saving to using Squeryl creating web pages for Kanban boards creating view for defined moving cards in setting up project with SBT SBT adding dependencies build file for for Mac for Unix for Windows project structure for Scalaz HTTP module configuring with SBT overview setting up servlet using Java frameworks model, view, controller using Spring configuration web.xml file weKanban application, 4th, 5th setting up project user stories WeKanbanApplication, 2nd, 3rd, 4th WeKanbanProjectDefinition.scala file, 2nd WeKanbanSchema object while loop Windows, SBT on with keyword withDispatcher method withFilter WordCount implementation using actors WordCount type WordCountMaster class WordCountWorker class, 2nd X XML types XmlConverter xs.clear() method, 2nd List of Figures Chapter 1.

pages: 211 words: 58,677

Philosophy of Software Design by John Ousterhout

conceptual framework, fault tolerance, iterative process, move fast and break things, move fast and break things, MVC pattern, revision control, Silicon Valley

Style guidelines make code easier to read and can reduce some kinds of errors. Interfaces. An interface with multiple implementations is another example of consistency. Once you understand one implementation of the interface, any other implementation becomes easier to understand because you already know the features it will have to provide. Design patterns. Design patterns are generally-accepted solutions to certain common problems, such as the model-view-controller approach to user interface design. If you can use an existing design pattern to solve the problem, the implementation will proceed more quickly, it is more likely to work, and your code will be more obvious to readers. Design patterns are discussed in more detail in Section 19.5. Invariants. An invariant is a property of a variable or structure that is always true. For example, a data structure storing lines of text might enforce an invariant that each line is terminated by a newline character.

pages: 355 words: 81,788

Monolith to Microservices: Evolutionary Patterns to Transform Your Monolith by Sam Newman

Airbnb, business process, continuous integration, database schema, DevOps, fault tolerance, ghettoisation, inventory management, Jeff Bezos, Kubernetes, loose coupling, microservices, MVC pattern, price anchoring, pull request, single page application, software as a service, source of truth, telepresence

Further down the line, once you’re happy that the migration has been successful, you can remove the functionality from the monolith. Refactoring the Monolith I’ve observed that often the biggest barrier to making use of existing code in the monolith in your new microservices is that existing codebases are traditionally not organized around business domain concepts. Technical categorizations are more prominent (think of all the Model, View, Controller package names you’ve seen, for example). When you’re trying to move business domain functionality, this can be difficult: the existing codebase doesn’t match that categorization, so even finding the code you’re trying to move can be problematic! If you do go down the route of reorganizing your existing monolith along business domain boundaries, I thoroughly recommend Working Effectively with Legacy Code by Michael Feathers (Prentice Hall, 2004).

pages: 643 words: 53,639

Rapid GUI Programming With Python and Qt by Mark Summerfield

Debian, Guido van Rossum, loose coupling, MVC pattern, software patent, sorting algorithm, web application

A solution is provided in chap13/pythoneditor_ans.pyw. 14 ● Using the Convenience Item Widgets ● Creating Custom Models ● Creating Custom Delegates Model/View Programming Model/view programming is a technique that involves separating data from its visual representation. It was first popularized as the MVC (model/view/ controller) paradigm used in the Smalltalk programming language. A model is a class that provides a uniform interface through which data items can be accessed. A view is a class that can present the data items from a model to the user on-screen. A controller is a class that mediates between the user interface (e.g., mouse events and key presses) to provide a means by which users can manipulate data items. View Controller or Delegate Model Dataset Figure 14.1 Model/view/controller and model/view/delegate The MVC approach offers several benefits. For example, huge datasets can be handled, because only the data that is actually displayed or edited is read or written from or to the data source.

pages: 713 words: 93,944

Seven Databases in Seven Weeks: A Guide to Modern Databases and the NoSQL Movement by Eric Redmond, Jim Wilson, Jim R. Wilson

AGPL, Amazon Web Services, create, read, update, delete, data is the new oil, database schema, Debian, domain-specific language,, fault tolerance, full text search, general-purpose programming language, Kickstarter, linked data, MVC pattern, natural language processing, node package manager, random walk, recommendation engine, Ruby on Rails, Skype, social graph, web application

Because Mongo is focused on large datasets, it works best in large clusters, which can require some effort to design and manage. Unlike Riak, where adding new nodes is transparent and relatively painless for operations, setting up a Mongo cluster requires a little more forethought. Parting Thoughts Mongo is an excellent choice if you are currently using a relational database to store your data through an ORM out of habit. We often recommend it to Rails, Django, and Model-View-Controller (MVC) developers, since they can then perform validations and field management through the models at the application layer and because schema migrations become a thing of the past (for the most part). Adding new fields to a document is as easy as adding a new field to your data model, and Mongo will happily accept the new terms. We find Mongo to be a much more natural answer to many common problem scopes for application-driven datasets than relational databases.

pages: 554 words: 108,035

Scala in Depth by Tom Kleenex, Joshua Suereth

discrete time, domain-specific language, fault tolerance, MVC pattern, sorting algorithm, type inference

Asynchronous I/O and actors are a natural pairing, as the execution models for these are similar. Using an actor to perform blocking I/O is asking for trouble. That actor can starve other actors during this processing. This can be mitigated, as we’ll discuss in section 9.4. Although many problems can be successfully modeled in actors, some will benefit more. The architecture of a system designed to use actors will also change fundamentally. Rather than relying on classic Model-View-Controller and client-based parallelism, an actors system parallelizes pieces of the architecture and performs all communication asynchronously. Let’s look at a canonical example of a good system design using actors. This example uses several tools found in the old Message Passing Interface (MPI) specification used in supercomputing. MPI is worth a look, as it holds a lot of concepts that have naturally translated into actor-based systems. 9.1.1.

pages: 603 words: 141,814

Python for Unix and Linux System Administration by Noah Gift, Jeremy M. Jones

Amazon Web Services, bash_history, Bram Moolenaar, cloud computing, create, read, update, delete, database schema, Debian, distributed revision control, Firefox, Guido van Rossum, industrial robot, inventory management, job automation, Mark Shuttleworth, MVC pattern, skunkworks, web application

Django Django is a full-stack web application framework. It contains a templating system, database connectivity by way of an object-relational mapper, and, of course, Python itself for writing the logic pieces of the application. Related to being a “full stack” framework, Django also follows a Model-View-Template (MVT) approach. This Model-View-Template approach is similar, if not identical, to a common approach called Model-View-Controller (MVC). Both are ways of developing applications so that the pieces of the application are not unnecessarily comingled. The database code is separated into an area referred to in both approaches as the “model.” The business logic is separated into an area referred to as the “view” in MVT and the “controller” in MVC. And the presentation is separated into an area referred to as the “template” in MVT and the “view” in MVC.

pages: 834 words: 180,700

The Architecture of Open Source Applications by Amy Brown, Greg Wilson

8-hour work day, anti-pattern, bioinformatics,, cloud computing, collaborative editing, combinatorial explosion, computer vision, continuous integration, create, read, update, delete, David Heinemeier Hansson, Debian, domain-specific language, Donald Knuth,, fault tolerance, finite state, Firefox, friendly fire, Guido van Rossum, linked data, load shedding, locality of reference, loose coupling, Mars Rover, MITM: man-in-the-middle, MVC pattern, peer-to-peer, Perl 6, premature optimization, recommendation engine, revision control, Ruby on Rails, side project, Skype, slashdot, social web, speech recognition, the scientific method, The Wisdom of Crowds, web application, WebSocket

Compared to WikiCalc, the server's role has been greatly reduced. Its only responsibility is responding to HTTP GETs by serving entire spreadsheets serialized in the save format; once the browser receives the data, all calculations, change tracking and user interaction are now implemented in Javascript. Figure 19.6: SocialCalc Class Diagram The Javascript components were designed with a layered MVC (Model/View/Controller) style, with each class focusing on a single aspect: Sheet is the data model, representing an in-memory structure of a spreadsheet. It contains a dictionary from coordinates to Cell objects, each representing a single cell. Empty cells need no entries, and hence consume no memory at all. Cell represents a cell's content and formats. Some common properties are shown in Table 19.1. RenderContext implements the view; it is responsible for rendering a sheet into DOM objects.

Seeking SRE: Conversations About Running Production Systems at Scale by David N. Blank-Edelman

Affordable Care Act / Obamacare, algorithmic trading, Amazon Web Services, bounce rate, business continuity plan, business process, cloud computing, cognitive bias, cognitive dissonance, commoditize, continuous integration, crowdsourcing, dark matter, database schema, Debian, defense in depth, DevOps, domain-specific language,, fault tolerance, fear of failure, friendly fire, game design, Grace Hopper, information retrieval, Infrastructure as a Service, Internet of things, invisible hand, iterative process, Kubernetes, loose coupling, Lyft, Marc Andreessen, microservices, minimum viable product, MVC pattern, performance metric, platform as a service, pull request, RAND corporation, remote working, Richard Feynman, risk tolerance, Ruby on Rails, search engine result page, self-driving car, sentiment analysis, Silicon Valley, single page application, Snapchat, software as a service, software is eating the world, source of truth, the scientific method, Toyota Production System, web application, WebSocket, zero day

Principles 1 and 2 (interfaces and incident command) SREs can interpret the first two principles as an equivalent to our understanding that teams need to respect one another’s scope of responsibilities and plans. In incident management, each individual is empowered with a specific scope, and random freelancing outside of the parameters of engagement is discouraged. In organizing, this often means keeping your tactics and actions physically separated from others’ so as to contain risks. Model-View-Controller paradigms, virtual machines, containers, and microservices are all highly specific variations on this theme. SREs define clear interfaces between, and SLOs for, systems and ensure that each component has a specific role, to avoid a tangled web of interdependencies or dependence upon implementation details. The operational principle is of isolation of the consequence of failures. Principles 3 and 4 (blameless retrospectives and psychological safety) The parallels of Principles 3 and 4 to SRE lie in how we approach postmortems and blameless interactions with each other during and after an incident.

pages: 1,302 words: 289,469

The Web Application Hacker's Handbook: Finding and Exploiting Security Flaws by Dafydd Stuttard, Marcus Pinto

call centre, cloud computing, commoditize, database schema, defense in depth, easy for humans, difficult for computers, Firefox, information retrieval, lateral thinking, MITM: man-in-the-middle, MVC pattern, optical character recognition, Ruby on Rails, Turing test, web application

These factors have meant that applications written in PHP have suffered from a disproportionate number of security vulnerabilities. In addition, several defects have existed within the PHP platform itself that often could be exploited via applications running on it. See Chapter 19 for details on common defects arising in PHP applications. Ruby on Rails Rails 1.0 was released in 2005, with strong emphasis on Model-View-Controller architecture. A key strength of Rails is the breakneck speed with which fully fledged data-driven applications can be created. If a developer follows the Rails coding style and naming conventions. Rails can autogenerate a model for database content, controller actions for modifying it, and default views for the application user. As with any highly functional new technology, several vulnerabilities have been found in Ruby on Rails, including the ability to bypass a "safe mode," analogous to that found in PHP.