This document provides an overview of the Python programming language across multiple sections. It covers fundamental Python concepts like data types, lists, strings, tuples, dictionaries, control flow, functions, modules and packages. It also discusses object-oriented programming concepts in Python including classes, inheritance and exceptions. Further sections explore using Python in integrated development environments like Emacs and debugging tools. Regular expressions and system commands in Python are also summarized. The document serves as a comprehensive reference to the Python language.
This document summarizes the features of the Bash shell version 4.3, last updated in February 2014. It provides definitions of key terms, an overview of basic shell features like syntax, commands, parameters and expansions. It also describes shell scripting, builtin commands, variables and other Bash-specific features. The manual is intended as a reference for using and programming with the Bash shell.
The document provides an overview of the C preprocessor, which is a macro processor that transforms C code before compilation. It covers preprocessing tasks like handling headers, macros, conditionals, and other directives. It also describes the traditional mode for backward compatibility with older code and implementations.
This document provides bibliographic information and copyright details for the book "Advanced Cardiovascular Exercise Physiology" by Denise L. Smith and Bo Fernhall. It lists the book's authors, publisher, subject headings, International Standard Book Number, and copyright information. The book is part of the Advanced Exercise Physiology Series published by Human Kinetics and focuses on cardiovascular system physiology and exercise physiology.
01 of 03 parts
Get Part 2 from https://www.slideshare.net/ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-2
Get Part 3 from https://www.slideshare.net/ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-3
C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations. C provides constructs that map efficiently to typical machine instructions and has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computers, from supercomputers to PLCs and embedded system.
This document is the Bash Reference Manual for version 4.2 of the GNU Bash shell. It provides documentation on Bash's features, including basic shell syntax and operations, shell commands, parameters, expansions, redirections, and built-in commands. The manual is published by the Free Software Foundation and was last updated in December 2010.
This document provides lecture notes for a C++ course. It notes that the document is a work in progress and needs polishing. It describes the tools used for the course, including GNU/Linux, GNU C++ compiler, emacs text editor, and UNIX commands. It also provides information on copyright and allows for free redistribution of the document without modification. The document then outlines the various chapters that will be covered in the course, including memory and CPU concepts, shell and C++ basics, expressions and functions, arrays and pointers, debugging, algorithms and sorting.
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...ssuserd6b1fd
C programming language notes for beginners and Collage students. Written for beginners. Colored graphics. Function by Function explanation with complete examples. Well commented examples. Illustrations are made available for data dealing at memory level.
AlgoXY is a free book about elementary
algorithms and data structures. This book doesn't only focus on an
imperative (or procedural) approach, but also includes purely functional
algorithms and data structures. It doesn't require readers to
master any programming languages, because all the algorithms are
described using mathematical functions and pseudocode.
This document summarizes the features of the Bash shell version 4.3, last updated in February 2014. It provides definitions of key terms, an overview of basic shell features like syntax, commands, parameters and expansions. It also describes shell scripting, builtin commands, variables and other Bash-specific features. The manual is intended as a reference for using and programming with the Bash shell.
The document provides an overview of the C preprocessor, which is a macro processor that transforms C code before compilation. It covers preprocessing tasks like handling headers, macros, conditionals, and other directives. It also describes the traditional mode for backward compatibility with older code and implementations.
This document provides bibliographic information and copyright details for the book "Advanced Cardiovascular Exercise Physiology" by Denise L. Smith and Bo Fernhall. It lists the book's authors, publisher, subject headings, International Standard Book Number, and copyright information. The book is part of the Advanced Exercise Physiology Series published by Human Kinetics and focuses on cardiovascular system physiology and exercise physiology.
01 of 03 parts
Get Part 2 from https://www.slideshare.net/ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-2
Get Part 3 from https://www.slideshare.net/ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-3
C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations. C provides constructs that map efficiently to typical machine instructions and has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computers, from supercomputers to PLCs and embedded system.
This document is the Bash Reference Manual for version 4.2 of the GNU Bash shell. It provides documentation on Bash's features, including basic shell syntax and operations, shell commands, parameters, expansions, redirections, and built-in commands. The manual is published by the Free Software Foundation and was last updated in December 2010.
This document provides lecture notes for a C++ course. It notes that the document is a work in progress and needs polishing. It describes the tools used for the course, including GNU/Linux, GNU C++ compiler, emacs text editor, and UNIX commands. It also provides information on copyright and allows for free redistribution of the document without modification. The document then outlines the various chapters that will be covered in the course, including memory and CPU concepts, shell and C++ basics, expressions and functions, arrays and pointers, debugging, algorithms and sorting.
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 1 of 5 by...ssuserd6b1fd
C programming language notes for beginners and Collage students. Written for beginners. Colored graphics. Function by Function explanation with complete examples. Well commented examples. Illustrations are made available for data dealing at memory level.
AlgoXY is a free book about elementary
algorithms and data structures. This book doesn't only focus on an
imperative (or procedural) approach, but also includes purely functional
algorithms and data structures. It doesn't require readers to
master any programming languages, because all the algorithms are
described using mathematical functions and pseudocode.
This document provides an introduction to reverse engineering for beginners. It covers basic code patterns and fundamentals across different CPU architectures like x86, ARM, and MIPS. Example code is shown for simple functions, "Hello World", and printf with multiple arguments on each architecture. The document also discusses important concepts like the stack, function prologues and epilogues, and tools that can be used. Later sections provide more advanced examples and exercises to help readers learn reverse engineering.
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...ssuserd6b1fd
C++ programming language notes for beginners and Collage students. Written for beginners. Colored graphics. Function by Function explanation with complete examples. Well commented examples. Illustrations are made available for data dealing at memory level.
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...ssuserd6b1fd
If you are beginners in 8051 micro controller and wants to be a professional in 8051 programming then read this notes. It surely helped you in understanding of 8051 from bottom to top.
This document discusses the Greasemonkey scripting tool. It covers getting started with Greasemonkey, creating a basic "Hello World" script, debugging scripts, common scripting patterns, case studies of existing scripts, and advanced topics. The chapters discuss installing and managing Greasemonkey and scripts, adding metadata to scripts, coding and editing scripts, debugging with the JavaScript console, DOM inspector, and other tools, executing scripts on domains and subdomains, testing for elements and attributes, inserting/removing content, styling elements, and more.
This document provides an introduction to the C++ programming language. It discusses the history and evolution of C++. The document outlines some key differences between C and C++, such as namespaces, references, and classes. It also introduces several important C++ concepts, like object-oriented programming, the string data type, input/output streams, and classes. The document serves as a textbook for C++ programming courses taught at the University of Groningen.
This document is a draft of a book on mathematics for programmers. It covers various topics in mathematics including prime numbers, modular arithmetic, probability, combinatorics, Galois fields, and logarithms. The document provides explanations, examples, and applications of these mathematical concepts for use in computer programming. It is intended to help programmers understand and apply core mathematical principles in their work.
This thesis submitted by Joshua Landwehr to the University of Delaware examines the Tapestry execution and synchronization models for parallel programming. Tapestry uses a threaded dependency model where actors are represented as threads and dependencies between actors control execution flow. The thesis describes the key components of the Tapestry model including actors, states, arcs, loops, pipelines, and how it supports various execution models. It also provides details on the Tapestry framework, threads implementation, and fibers runtime and evaluates Tapestry on benchmarks like Fibonacci and N-Queens.
This document is a manual for Cinelerra CV, an open source non-linear video editor for Linux. It discusses installing and configuring Cinelerra CV, including hardware and software requirements and instructions for different Linux distributions. It also covers compiling Cinelerra from source, configuring audio and video drivers, and playback settings. The manual is distributed under the GNU GPL license.
This document contains information about the ChucK programming language, including:
- The authors and developers of ChucK, led by Ge Wang and Perry Cook.
- Links to documentation, tutorials, code repositories, and more.
- An overview of the ChucK Manual, which covers topics like installation, language basics, concurrency, and events.
The document describes the ns network simulator. It discusses how ns has evolved from version 1 to version 2, with changes including decomposing complex objects into simpler components, using OTcl as the configuration interface instead of Tcl, and separating the interface code from the main simulator. It also provides information on how to access documentation for ns.
This document is the CUDA API Reference Manual for version 5.0. It provides documentation on the CUDA API, including sections that describe the synchronization behavior of functions like memcpy and kernel launches. It also includes indexes of deprecated functions, modules, and data structures. The majority of the document consists of in-depth documentation of the functions within each CUDA API module, including parameters, return values, and usage examples.
This document provides lecture notes on applied cryptography and data security. It covers topics such as symmetric and asymmetric cryptosystems, cryptanalysis techniques, stream and block ciphers like DES and AES, public key cryptography including RSA, and the discrete logarithm problem. The notes are intended for education on the fundamentals of cryptography and cybersecurity.
This document is a Python tutorial that provides an overview of the Python programming language. It covers topics like using the Python interpreter, basic syntax like variables and data types, control flow tools like if/else statements and for loops, defining functions, working with data structures like lists, tuples and dictionaries, modules and packages, input/output functions, exceptions and errors, and an introduction to classes. The tutorial is intended to help new Python programmers get started with the basics of the language.
This document provides an overview and introduction to using Biopython, an open source Python library for biological sequence analysis. It covers topics such as installing Biopython, working with sequence objects, parsing sequence files, connecting to biological databases, multiple sequence alignments, and BLAST searches. The goal is to explain the key capabilities and functionalities available in Biopython through examples and tutorials.
This is the printout version of my lecture slides for the OS course. It includes more details (quations from books, references, etc.) than the slides version.
How use Modelica? Read this note for better understanding. Professionally written and explained. Good for software development by beginners in Modelica .
The document discusses potential title and font ideas for a new folk music magazine. It considers titles like "The Wall" and "The Record Shop" before deciding to focus on the folk music revival with artists like Jake Bugg and Mumford & Sons. The proposed title "Some folk" is meant to reference both an amount of folk music and a group of folk musicians. Possible fonts aim to represent both the history of folk music and its current popularity. The final choice is a variation of Helvetica, popular in the 1970s, to signify folk music's timeless nature but with a modern twist for the genre's revival.
The document discusses a school trip from Lycée Jean Calvin in Noyon, France that will include visits to Spain and England. The trip will include a visit to the city of Toledo in Spain as well as a concert performed by the students of Lycée Jean Calvin.
The document provides an introduction to business ecosystems. It discusses how strong ecosystems emerge in some places and not others, and whether ecosystems can be intentionally shaped. The study examined IT, biotech and cleantech ecosystems in the US, Canada and Europe. It found the best ecosystems have open and innovative "mother companies" and serial entrepreneurs who remain and reinvest in the region. The Danish biotech ecosystem lags top US clusters due to a lack of experienced management teams to scale new companies. To strengthen ecosystems, established companies, capital groups, universities and politicians need to actively support entrepreneurs and collaborations.
This document provides an overview and instructions for a course in Python programming. It discusses the recommended course literature, including Learning Python and Python in a Nutshell books. It also describes using the IDLE integrated development environment for writing and running Python code on Windows and Unix systems. The document then begins covering basic Python concepts like variables, data types, strings, lists, dictionaries and objects.
This document provides an introduction to reverse engineering for beginners. It covers basic code patterns and fundamentals across different CPU architectures like x86, ARM, and MIPS. Example code is shown for simple functions, "Hello World", and printf with multiple arguments on each architecture. The document also discusses important concepts like the stack, function prologues and epilogues, and tools that can be used. Later sections provide more advanced examples and exercises to help readers learn reverse engineering.
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...ssuserd6b1fd
C++ programming language notes for beginners and Collage students. Written for beginners. Colored graphics. Function by Function explanation with complete examples. Well commented examples. Illustrations are made available for data dealing at memory level.
Notes of 8051 Micro Controller for BCA, MCA, MSC (CS), MSC (IT) & AMIE IEI- b...ssuserd6b1fd
If you are beginners in 8051 micro controller and wants to be a professional in 8051 programming then read this notes. It surely helped you in understanding of 8051 from bottom to top.
This document discusses the Greasemonkey scripting tool. It covers getting started with Greasemonkey, creating a basic "Hello World" script, debugging scripts, common scripting patterns, case studies of existing scripts, and advanced topics. The chapters discuss installing and managing Greasemonkey and scripts, adding metadata to scripts, coding and editing scripts, debugging with the JavaScript console, DOM inspector, and other tools, executing scripts on domains and subdomains, testing for elements and attributes, inserting/removing content, styling elements, and more.
This document provides an introduction to the C++ programming language. It discusses the history and evolution of C++. The document outlines some key differences between C and C++, such as namespaces, references, and classes. It also introduces several important C++ concepts, like object-oriented programming, the string data type, input/output streams, and classes. The document serves as a textbook for C++ programming courses taught at the University of Groningen.
This document is a draft of a book on mathematics for programmers. It covers various topics in mathematics including prime numbers, modular arithmetic, probability, combinatorics, Galois fields, and logarithms. The document provides explanations, examples, and applications of these mathematical concepts for use in computer programming. It is intended to help programmers understand and apply core mathematical principles in their work.
This thesis submitted by Joshua Landwehr to the University of Delaware examines the Tapestry execution and synchronization models for parallel programming. Tapestry uses a threaded dependency model where actors are represented as threads and dependencies between actors control execution flow. The thesis describes the key components of the Tapestry model including actors, states, arcs, loops, pipelines, and how it supports various execution models. It also provides details on the Tapestry framework, threads implementation, and fibers runtime and evaluates Tapestry on benchmarks like Fibonacci and N-Queens.
This document is a manual for Cinelerra CV, an open source non-linear video editor for Linux. It discusses installing and configuring Cinelerra CV, including hardware and software requirements and instructions for different Linux distributions. It also covers compiling Cinelerra from source, configuring audio and video drivers, and playback settings. The manual is distributed under the GNU GPL license.
This document contains information about the ChucK programming language, including:
- The authors and developers of ChucK, led by Ge Wang and Perry Cook.
- Links to documentation, tutorials, code repositories, and more.
- An overview of the ChucK Manual, which covers topics like installation, language basics, concurrency, and events.
The document describes the ns network simulator. It discusses how ns has evolved from version 1 to version 2, with changes including decomposing complex objects into simpler components, using OTcl as the configuration interface instead of Tcl, and separating the interface code from the main simulator. It also provides information on how to access documentation for ns.
This document is the CUDA API Reference Manual for version 5.0. It provides documentation on the CUDA API, including sections that describe the synchronization behavior of functions like memcpy and kernel launches. It also includes indexes of deprecated functions, modules, and data structures. The majority of the document consists of in-depth documentation of the functions within each CUDA API module, including parameters, return values, and usage examples.
This document provides lecture notes on applied cryptography and data security. It covers topics such as symmetric and asymmetric cryptosystems, cryptanalysis techniques, stream and block ciphers like DES and AES, public key cryptography including RSA, and the discrete logarithm problem. The notes are intended for education on the fundamentals of cryptography and cybersecurity.
This document is a Python tutorial that provides an overview of the Python programming language. It covers topics like using the Python interpreter, basic syntax like variables and data types, control flow tools like if/else statements and for loops, defining functions, working with data structures like lists, tuples and dictionaries, modules and packages, input/output functions, exceptions and errors, and an introduction to classes. The tutorial is intended to help new Python programmers get started with the basics of the language.
This document provides an overview and introduction to using Biopython, an open source Python library for biological sequence analysis. It covers topics such as installing Biopython, working with sequence objects, parsing sequence files, connecting to biological databases, multiple sequence alignments, and BLAST searches. The goal is to explain the key capabilities and functionalities available in Biopython through examples and tutorials.
This is the printout version of my lecture slides for the OS course. It includes more details (quations from books, references, etc.) than the slides version.
How use Modelica? Read this note for better understanding. Professionally written and explained. Good for software development by beginners in Modelica .
The document discusses potential title and font ideas for a new folk music magazine. It considers titles like "The Wall" and "The Record Shop" before deciding to focus on the folk music revival with artists like Jake Bugg and Mumford & Sons. The proposed title "Some folk" is meant to reference both an amount of folk music and a group of folk musicians. Possible fonts aim to represent both the history of folk music and its current popularity. The final choice is a variation of Helvetica, popular in the 1970s, to signify folk music's timeless nature but with a modern twist for the genre's revival.
The document discusses a school trip from Lycée Jean Calvin in Noyon, France that will include visits to Spain and England. The trip will include a visit to the city of Toledo in Spain as well as a concert performed by the students of Lycée Jean Calvin.
The document provides an introduction to business ecosystems. It discusses how strong ecosystems emerge in some places and not others, and whether ecosystems can be intentionally shaped. The study examined IT, biotech and cleantech ecosystems in the US, Canada and Europe. It found the best ecosystems have open and innovative "mother companies" and serial entrepreneurs who remain and reinvest in the region. The Danish biotech ecosystem lags top US clusters due to a lack of experienced management teams to scale new companies. To strengthen ecosystems, established companies, capital groups, universities and politicians need to actively support entrepreneurs and collaborations.
This document provides an overview and instructions for a course in Python programming. It discusses the recommended course literature, including Learning Python and Python in a Nutshell books. It also describes using the IDLE integrated development environment for writing and running Python code on Windows and Unix systems. The document then begins covering basic Python concepts like variables, data types, strings, lists, dictionaries and objects.
The student hypothesized that adding salt to water would increase the density and allow an egg to float. They conducted an experiment where they added salt to water in a glass with an egg, stirring after each addition, until the egg floated, confirming their hypothesis that salt increases water's density.
One of the biggest dilemmas faced by decision-making systems is to determine an efficient means to produce classifiers from data base regarding the processing time and the form of simple symbolic representation understandable that facilitates the analysis of the problem in question. In this brief report we will discuss a very popular tool in knowledge discovery in databases process and thus aid in making decisions: the Decision Trees.
This document provides an unofficial reference manual for LaTeX version 2e from March 2018. It was originally translated from help manuals for earlier LaTeX versions. The document contains detailed information about LaTeX commands, environments, document structure, fonts, layout, sectioning, cross-references and more. Permission is granted to distribute copies of the manual provided the copyright information is preserved.
This document is the table of contents for the book "Python Programming and Numerical Methods: A Guide for Engineers and Scientists". It outlines the book's contents which cover topics such as Python basics, variables and data structures, functions, branching statements, iteration, recursion, and object-oriented programming. The book is intended as a guide for engineers and scientists to learn Python programming and numerical methods.
01 of 02 parts
Get Part 2 from https://www.slideshare.net/ArunUmrao/introduction-to-c-programming-for-beginners-by-arunumrao-2-of-2-250786026
Introduction to c++ programming, Introduction to c++ programming, Introduction to c++ programming, Introduction to c++ programming, Introduction to c++ programming,
This document is a preface and table of contents for a book titled "Picking Up Perl" that teaches Perl programming to new users. The preface outlines that the book is a tutorial intended for beginners to learn Perl version 5.6.0. It also covers the book's purpose, acknowledgments, obtaining updates, intended audience, materials covered, and conventions used. The table of contents provides an overview of the 7 chapters and their sections that make up the content of the book, covering topics like scalars, arrays, control structures, hashes, regular expressions and subroutines.
This document is a preface and table of contents for a book titled "Picking Up Perl" that teaches Perl programming to new users. The preface outlines that the book is a tutorial intended for beginners to learn Perl version 5.6.0. It also covers the book's purpose, acknowledgments, obtaining updates, intended audience, topics covered, and conventions used. The table of contents provides an overview of the 7 chapters and their sections that make up the content of the book, including getting started, scalars, arrays, control structures, hashes, regular expressions, and subroutines.
Modelling Time in Computation (Dynamic Systems)M Reza Rahmati
This document presents a dissertation on functional reactive programming (FRP) for real-time reactive systems. The dissertation introduces RT-FRP, a language for programming real-time reactive systems that can guarantee resource bounds while allowing a restricted form of recursion. It presents two variants of RT-FRP called H-FRP and E-FRP for modeling hybrid and event-driven systems respectively. A compiler is presented for compiling E-FRP to an imperative language for implementation. The dissertation contributes new programming languages and techniques for programming reactive and embedded systems with guarantees on resource usage.
This document specifies the devicetree format. It defines the structure and conventions for representing hardware resources and connections in a device tree. This includes node names, properties, memory map representation, interrupt mapping, and the flattened device tree binary format. The goal is to provide a standardized representation of platform hardware across embedded and mobile systems.
The caret package provides functions for training and plotting classification and regression models. It contains tools for preprocessing data, feature selection, tuning models, and assessing model performance. The package documentation lists over 100 functions for tasks like confusion matrix generation, variable importance calculation, hyperparameter tuning, and more. It depends on packages like ggplot2, lattice, and randomForest and is designed to work with many machine learning algorithms for both supervised and unsupervised learning problems.
This document provides an overview and summary of the ns Manual, which documents the Network Simulator ns. It describes ns as being written in C++ and using OTcl as a command and configuration interface. The manual contains documentation on topics like the simulator basics, nodes and packet forwarding, links, queue management, delays, and the differentiated services module. It is intended to help users understand and utilize the various components and capabilities of the ns network simulator.
This document is an introduction to programming using Java version 5.0 from December 2006. It was written by David J. Eck of Hobart and William Smith Colleges. The document covers Java programming concepts such as machine language, asynchronous events, the Java virtual machine, object-oriented programming, and the modern user interface. It is licensed under the Creative Commons Attribution-Share Alike license and its web site is provided. The document contains chapters and exercises to teach Java programming.
This document provides instructions for installing and configuring OpenStack. It describes the OpenStack architecture and services, how to set up the necessary infrastructure components like networking, databases and message queues, and how to deploy the core OpenStack services. It also provides steps for launching a test instance and interacting with basic OpenStack features like networks, block storage and orchestration.
This document is a textbook about the science of computing. It is divided into chapters that cover various topics in computing including: logic circuits, data representation, computational circuits, computer architecture, operating systems, artificial intelligence, and language and computation. The textbook is copyrighted to Carl Burch and is intended to provide an introduction to fundamental concepts in computer science.
This document provides an overview of classes used in a program for lexical analysis and parsing. It describes classes for representing states, non-deterministic finite automata (NFA), deterministic finite automata (DFA), compressed DFAs, symbols, productions, symbol tables, items, item sets, partitions, actions, states, and automata. These classes are used to specify grammars, construct parsing tables, and perform lexical analysis and parsing of input code.
Notes for c programming for mca, bca, b. tech cse, ece and msc (cs) 1 of 5 by...ssuserd6b1fd
C programming language notes for beginners and Collage students. Written for beginners. Colored graphics. Function by Function explanation with complete examples. Well commented examples. Illustrations are made available for data dealing at memory level.
This document is a textbook for high school students studying physics. It is titled "The Free High School Science Texts: A Textbook for High School Students Studying Physics". The textbook is published under the GNU Free Documentation License, which allows users to copy, distribute, and modify the document. The textbook covers various topics in physics, including units, waves, geometrical optics, vectors, forces, and Newton's laws of motion. It provides explanations, examples, and important equations for each topic.
The preface provides an overview of the book. It aims to collect information about zk-SNARKs and present it to audiences without strong cryptography backgrounds. It originated from lecture notes given at cryptography conferences. The book is intended to explain key zk-SNARK concepts with minimal mathematics through illustrative examples. It serves as a work-in-progress to update relevant zk-SNARK technology applications.
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Speck&Tech
ABSTRACT: A prima vista, un mattoncino Lego e la backdoor XZ potrebbero avere in comune il fatto di essere entrambi blocchi di costruzione, o dipendenze di progetti creativi e software. La realtà è che un mattoncino Lego e il caso della backdoor XZ hanno molto di più di tutto ciò in comune.
Partecipate alla presentazione per immergervi in una storia di interoperabilità, standard e formati aperti, per poi discutere del ruolo importante che i contributori hanno in una comunità open source sostenibile.
BIO: Sostenitrice del software libero e dei formati standard e aperti. È stata un membro attivo dei progetti Fedora e openSUSE e ha co-fondato l'Associazione LibreItalia dove è stata coinvolta in diversi eventi, migrazioni e formazione relativi a LibreOffice. In precedenza ha lavorato a migrazioni e corsi di formazione su LibreOffice per diverse amministrazioni pubbliche e privati. Da gennaio 2020 lavora in SUSE come Software Release Engineer per Uyuni e SUSE Manager e quando non segue la sua passione per i computer e per Geeko coltiva la sua curiosità per l'astronomia (da cui deriva il suo nickname deneb_alpha).
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc
How does your privacy program stack up against your peers? What challenges are privacy teams tackling and prioritizing in 2024?
In the fifth annual Global Privacy Benchmarks Survey, we asked over 1,800 global privacy professionals and business executives to share their perspectives on the current state of privacy inside and outside of their organizations. This year’s report focused on emerging areas of importance for privacy and compliance professionals, including considerations and implications of Artificial Intelligence (AI) technologies, building brand trust, and different approaches for achieving higher privacy competence scores.
See how organizational priorities and strategic approaches to data security and privacy are evolving around the globe.
This webinar will review:
- The top 10 privacy insights from the fifth annual Global Privacy Benchmarks Survey
- The top challenges for privacy leaders, practitioners, and organizations in 2024
- Key themes to consider in developing and maintaining your privacy program
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
Full-RAG: A modern architecture for hyper-personalizationZilliz
Mike Del Balso, CEO & Co-Founder at Tecton, presents "Full RAG," a novel approach to AI recommendation systems, aiming to push beyond the limitations of traditional models through a deep integration of contextual insights and real-time data, leveraging the Retrieval-Augmented Generation architecture. This talk will outline Full RAG's potential to significantly enhance personalization, address engineering challenges such as data management and model training, and introduce data enrichment with reranking as a key solution. Attendees will gain crucial insights into the importance of hyperpersonalization in AI, the capabilities of Full RAG for advanced personalization, and strategies for managing complex data integrations for deploying cutting-edge AI solutions.
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Zilliz
Join us to introduce Milvus Lite, a vector database that can run on notebooks and laptops, share the same API with Milvus, and integrate with every popular GenAI framework. This webinar is perfect for developers seeking easy-to-use, well-integrated vector databases for their GenAI apps.
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slackshyamraj55
Discover the seamless integration of RPA (Robotic Process Automation), COMPOSER, and APM with AWS IDP enhanced with Slack notifications. Explore how these technologies converge to streamline workflows, optimize performance, and ensure secure access, all while leveraging the power of AWS IDP and real-time communication via Slack notifications.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
12. Python
None,0,0.0,"" ( ),[]( list),()( tuple),{}( dictionary)
Python
and
or
not
>>> def getTrue():
... print "debug: true"
... return 1
...
>>> def getFalse():
... print "debug: false"
... return 0
...
>>> if getTrue() and getFalse():
... print "ok"
... else:
... print "bad"
...
debug: true # getTrue
debug: false # getTrue , getFalse
bad # getFalse .
>>> if getFalse() and getTrue():
... print "ok"
... else:
... print "bad"
...
debug: false # getFalse
bad # getFalse , getTrue
>>>
and or and expr1 and expr2 expr1
expr1 list expr2
expr2 expr1 expr2
expr2 or expr1 or expr2 expr1
expr1 expr2 expr2
expr1 expr2
expr2 :
annCharles@tom.com 4 , 152 Python
13. §1.3
<cond> and <expr_true> or <expr_false>
: cond expr_true expr_false
:
cond expr_true expr_false
( ) expr_true
( ) expr_false
( ) expr_false
expr_false
expr_false
:
• cond expr_true
• cond expr_false
• expr_true
cond expr_false
:
(<cond> and (<expr_true>,) or (<expr_false>,))[0]
[0]
tuple (<expr_true>,)
tuple [0]
expr_true expr_false
>>> x= cond and "OK" or "BAD"
>>> x
’OK’
>>> cond = 0
>>> x= cond and "OK" or "BAD"
>>> x
’BAD’
>>>
:
<cond> or <expr_false> and <expr_true>
“ ”
annCharles@tom.com 5 , 152 Python
14. Python
“ ” “ ”
C C
cond ? true_expr: false_expr
C
§1.4 (list)
list C++ vector C
[ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
[ ’January’, ’February’, ’March’, ’April’, ’May’,
’June’, ’July’, ’August’, ’September’, ’October’,
’November’, ’December’ ]
[ ’Monday’,’Tuesday’, ’Wednesday’, ’Thursday’ ,
’Friday’, ’Saturday’, ’Sunday’]
§1.4.1 list
a=[’1’,’2’]
[] list
§1.4.2 list list
list 0 C
-len
... ...
-2
-1
0
1
... ...
len-1
>>> a=[0,1,2,3,4,5,6]
annCharles@tom.com 6 , 152 Python
15. §1.4 (list)
>>> i=-len(a)
>>> while i < len(a):
... print "a[",i,"]=",a[i]
... i=i+1
...
a[ -7 ]= 0
a[ -6 ]= 1
a[ -5 ]= 2
a[ -4 ]= 3
a[ -3 ]= 4
a[ -2 ]= 5
a[ -1 ]= 6
a[ 0 ]= 0
a[ 1 ]= 1
a[ 2 ]= 2
a[ 3 ]= 3
a[ 4 ]= 4
a[ 5 ]= 5
a[ 6 ]= 6
while a[-8] a[9]
>>> a[-8]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
>>> a[7]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
§1.4.3 list
list
0
−1 list
>>> a[1:4]
annCharles@tom.com 7 , 152 Python
16. Python
[1, 2, 3]
>>> a[:]
[0, 1, 2, 3, 4, 5, 6]
>>> a[1:]
[1, 2, 3, 4, 5, 6]
>>> a[:3]
[0, 1, 2]
>>> a[:]
[0, 1, 2, 3, 4, 5, 6]
>>> a[1:-1]
[1, 2, 3, 4, 5]
list list list list
§1.4.4 list
• L.append(var)
>>> a=[0,1,2,3,4,5]
>>> a.append(6)
>>> a
[0, 1, 2, 3, 4, 5, 6]
>>>
• L.count(var) var L
>>> a=[0,2,2,2,3,3]
>>> a.count(2)
3
>>> a.count(3)
2
• len(L) L
>>> a=[1,2,3]
>>> len(a)
3
• L.extend(list) list L
>>> a=[1,2,3]
>>> a.extend([4,5,6])
annCharles@tom.com 8 , 152 Python
17. §1.4 (list)
>>> a
[1, 2, 3, 4, 5, 6]
• L.index(var) var L
>>> a=[1,2,3,4,4,5]
>>> a.index(4)
3
>>> a.index(6)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: list.index(x): x not in list
• L.insert(index,var) index var index list
index 0
>>> a=[1,2]
>>> a.insert(0,1)
>>> a
[1, 1, 2]
>>> a.insert(100,100)
>>> a
[1, 1, 2, 100]
>>> a.insert(2,3)
>>> a
[1, 1, 3, 2, 100]
• L.pop() L.pop(index) index
>>> a=[0,1,2,3,]
>>> a.pop()
3
>>> a.pop(0)
0
>>> a
[1, 2]
>>>
• L.remove(var) var
annCharles@tom.com 9 , 152 Python
18. Python
>>> a=["a","b","a","c","a","d"]
>>> a.remove("a")
>>> a
[’b’, ’a’, ’c’, ’a’, ’d’]
>>> a.remove("a")
>>> a
[’b’, ’c’, ’a’, ’d’]
• L.reverse() L
>>> a=[1,2,3,4,5]
>>> a.reverse()
>>> a
[5, 4, 3, 2, 1]
• L.sort() a a
list ?
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]
>>> a=[1,"abc",2,"xxx"]
>>> a.sort()
>>> a
[1, 2, ’abc’, ’xxx’]
L.sort(func) func func(x,y) −1 0 1
§1.4.5 list
list stack
>>> a=[]
>>> a.append(0) #
>>> a.append(1)
>>> a.append(2)
>>> a
[0, 1, 2]
>>> a.pop() #
2
annCharles@tom.com 10 , 152 Python
20. Python
list tree
>>> leaf1=[0,1]
>>> leaf2=[2,3]
>>> leaf3=[4,5]
>>> leaf4=[6,7]
>>> branch1=[leaf1,leaf2]
>>> branch2=[leaf3,leaf4]
>>> root=[branch1,branch2]
>>> root
[[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
§1.4.6 list comprehension
:
[ <expr1> for k in L if <expr2> ]
:
returnList=[]
for k in L:
if <expr2>: returnList.append(<expr1>)
return returnList;
list list expr1 if
>>> a=["123","456","abc","Abc","AAA"]
>>> [ k.center(9) for k in a ]
[’ 123 ’, ’ 456 ’, ’ abc ’, ’ Abc ’, ’ AAA ’]
# a
>>> [ k.upper() for k in a if k.isalpha() ]
[’ABC’, ’ABC’, ’AAA’]
# a
>>> [ k.lower() for k in a if k.isupper() ]
[’aaa’]
# a
>>> [ int(k) for k in a if k.isdigit() ]
[123, 456]
(filter) (mapping)
annCharles@tom.com 12 , 152 Python
21. §1.5 (string)
“ list
” : “ list list
list ”
list 1
[ k+1 for k in list]
list
[ k for k in list if type(k)==types.IntType]
list
[ k + 1 for k in list if type(k)==types.IntType ]
§1.5 (string)
§1.5.1
’hello’
"world"
1.5-1
C echo Java
"abc"
’def’
“abcdef” "abc"+"def" +
"""
this is a very very long string.
And it contains a lot line.
it is suitable to write document of function.
"""
annCharles@tom.com 13 , 152 Python
22. Python
newline
’ ’
" "
a 0x07 ASCII
b 0x08 ASCII
f 0x0c Formfeed (FF) ASCII
n 0x0a ASCII
N{name} Unicode Unicode
r 0x0d ASCII
t 0x09
v 0x0b
u{xxxx} Unicode Unicode
ooo 0xooo ooo
xhh 0xhh hh
1.5-1:
float(str) float("1e-1") 0.1
int(str) int("12") 12
int(str,base) base int("11",2) 2
long(str) int("12") 12
long(str,base) base int("11",2) 2
1.5-2:
§1.5.2
§1.5.3
>>> "Hello" + " " + "World"
’Hello World’
>>> "this is test".capitalize() #
annCharles@tom.com 14 , 152 Python
23. §1.5 (string)
’This is test’
>>> "THIS IS TEST".capitalize()
’This is test’
>>> "THIS IS TEST".lower() #
’this is test’
>>> "this is test".upper() #
’THIS IS TEST’
>>> "This Is Test".swapcase() #
’tHIS iS tEST’
>>> len("Hello World")
11
list list
0
>>> str="Hello World"
>>> str="Hello"
>>> i=-len(str)
>>> while i < len(str):
... print "str[",i,"]=",str[i]
... i=i+1
...
str[ -5 ]= H
str[ -4 ]= e
str[ -3 ]= l
str[ -2 ]= l
str[ -1 ]= o
str[ 0 ]= H
str[ 1 ]= e
str[ 2 ]= l
str[ 3 ]= l
str[ 4 ]= o
>>>
-1 0
annCharles@tom.com 15 , 152 Python
26. Python
s % <tuple> tuple C printf
tuple s
>>> print "%s’s height is %dcm"%("Charles",180)
Charles’s height is 180cm
%s,%d C printf conversion specifier ( )
conversion specifier conversion specifier
%[<mapping key>][<conversion flag>][<Minimum field width>]|
[<precision>][<lenght modifier>]<conversion type>|
% conversion type
conversion type :
• d
>>> "%d and %d" % (-1,2)
-1 and 2
• i d
• o
>>> "%o and %o" % (16,8)
20 and 10
• u
>>> "%u and %u" %(-10,10)
’4294967286 and 10’
−10
1
• x ( )
>>> "%x and %x" % (100,200)
’64 and c8’
• X ( )
>>> "%X and %X" % (100,200)
’64 and C8’
annCharles@tom.com 18 , 152 Python
27. §1.5 (string)
• e ( )
>>> "%e and %e"%(-100,200)
2.000000e+02
• E ( )
>>> "%E and %E"%(-100,200)
2.000000E+02
• f
>>> "%f and %f"%(-0.00001,200.0)
’-0.000010 and 200.000000’
• g 0.0001
>>> "%g and %g"%(-0.00001,2000000.0)
’-1e-05 and 2e+06’
• c ASCII
>>> "%c and %c"%(67,68)
’C and D’
ASCII
• r repr()
>>> "%r"%({"one":1,"two":2})
"{’two’: 2, ’one’: 1}"
print expr(obj)
• s str()
>>> "%s"%({"one":1,"two":2})
"{’two’: 2, ’one’: 1}"
print str(obj)
str expr str expr
Python
mapping key dictionary tuple mapping key key
dictionary %d %(height)
tuple
tuple mapping key
annCharles@tom.com 19 , 152 Python
28. Python
>>> print "%s’s height is %d cm, %s’s weight is %d kg" %
... ("Charles",170,"Charles",70)
Charles’s height is 170 cm, Charles’s weight is 70 kg
>>> print "%(name)s’s height is %(height)d cm"
... ",%(name)s’s weight is %(weight)d kg" %
... {"name":"Charles","height":170,"weight":70}
Charles’s height is 170 cm,Charles’s weight is 70 kg
name mapping key
locals() locals() local name space (
) dictionary key value globals() global
name space ( ) name space( )
>>> def fun(a,b):
... print "a is %(a)d,b is %(b)d" %locals()
...
>>> fun(1,2)
a is 1,b is 2
minimum field width
>>> print "%10d,%10d"%(1,2)
1, 2
precision
>>> print "%10.2f,%10.2f"%(10.123456,20.126456)
10.12, 20.13
conversion flag # alternate form 8
0 0x 0X
>>> print "%#x,%#X,%#o" %(16,16,16)
0x10,0X10,020
0 0 minimum field width
>>> print "%010d,%010d"%(1,2)
0000000001,0000000002
- 0 0
>>> print "%-010d,%-010d"%(1,2)
1 ,2
0 -
annCharles@tom.com 20 , 152 Python
29. §1.5 (string)
>>> print "% 10d,% 10d,% 10d"%(-1,2,-0)
-1, 2, 0
+ + -
>>> print "%+10d,%+10d,%+10d"%(-1,2,0)
-1, +2, +0
lenght modifier
• s.ljust(width) s width
width s
>>> "Hello World".ljust(1)
’Hello World’
>>> "Hello World".ljust(12)
’Hello World ’
>>> "Hello World".ljust(16)
’Hello World ’
• s.rjust(width)
>>> "Hello World".rjust(16)
’ Hello World’
>>> "Hello World".rjust(1)
’Hello World’
• s.center(width) s width s
width
>>> "Hello World".center(1)
’Hello World’
>>> "Hello World".center(16)
’ Hello World ’
• s.lstrip() s.rstrip()
s.lstrip()
>>> "t a t".lstrip()
’a ’
>>> "t a t".rstrip()
annCharles@tom.com 21 , 152 Python
30. Python
’ a’
>>> "t a t".strip()
’a’
python 2.2.3 chars chars
s.strip s.strip("t nr")
(join) (split)
s.join(words) words tuple list join s
words
>>> "n".join(["Hello","World","Python","Said"])
’HellonWorldnPythonnSaid’
>>> print "n".join(["Hello","World","Python","Said"])
Hello
World
Python
Said
s.split(words) words split join
s list
>>> "This is a book".split(" ")
[’This’, ’is’, ’a’, ’book’]
§1.6 (tuple)
tuple
• tuple list tuple pop remove insert
• tuple () a=(0 1 2 3 4)
• tuple tuple
• tuple
>>> a,b=(1,2)
>>> print a,b
1 2
>>> t=(1,2)
>>> a,b=t
>>> print a,b
1 2
annCharles@tom.com 22 , 152 Python
31. §1.7 (sequence)
>>> a,b=b,a+1
>>> print a,b
>>> 2,2
• tuple : (1 )
tuple list
§1.7 (sequence)
sequence string list tuple
• in object sequence
>>> x=12
>>> l=[12,13]
>>> if x in l : print "x is in l"
...
x is in l
>>> str="abcd"
>>> if "a" in str: print " ok "
...
ok
>>> if 2 in T : print "OK"
...
OK
• sequence len(seq)
• seq[i]
• sequence seq[start:end]
• + sequence
• * sequence "a"*3 aaa (1,2)*3 (1,2,1,2,1,2)
• list comprehension
§1.8 (dictionary)
dictionary pair key value
key integer string1 value dictionary
key dictionary tuple tuple
tuple pair pair key value D[key] value
1
hash cmp
annCharles@tom.com 23 , 152 Python
32. Python
§1.8.1
# dictionary {}
# pair pair key value
>>> pricelist={"clock":12,"table":100,"xiao":100 }
# dictionary value key
>>> pricelist["clock"]
12
>>> del pricelist["clock"]
>>> pricelist
{’table’: 100, ’xiao’: 100}
# dict(L) dictionary
# L list L tuple
# tuple key value
>>> pricelist=dict([(’clock’,12),("table",100),("xiao",100)])
>>> pricelist
{’table’: 100, ’xiao’: 100, ’clock’: 12}
>>> pricelist=dict([(x,10*x) for x in [1,2,3]])
>>> pricelist
{1: 10, 2: 20, 3: 30}
# key pair
>>> pricelist["apple"]=12 #
>>> pricelist
{’table’: 100, ’apple’: 12, ’xiao’: 100, ’clock’: 12}
# key
>>> pricelist["appled"]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: appled
§1.8.2 dictionary
a={"one":1,"two":2,"three":3,"four":4}
dictionary
D.clear()
>>> a.clear()
>>> a
{}
annCharles@tom.com 24 , 152 Python
33. §1.8 (dictionary)
dictionary
D.copy()
dictionary
>>> a
{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}
>>> b=a.copy()
>>> b
{’four’: 4, ’one’: 1, ’three’: 3, ’two’: 2}
>>> b["four"]=5
>>> b
{’four’: 5, ’one’: 1, ’three’: 3, ’two’: 2}
>>> a
{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}
>>> c=a
>>> c["four"]=5
>>> a
{’four’: 5, ’three’: 3, ’two’: 2, ’one’: 1}
>>> c
{’four’: 5, ’three’: 3, ’two’: 2, ’one’: 1}
c=a c a c
a b=a.copy() b b a
D.get(key)
D key D[key] None
>>> a
{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}
>>> print a.get("abc")
None
>>> print a.get("four")
4
>>> print a.get("abc",100)
100
D.get(key,default) D.get(key) key default
None D.get(key) D.get(key,None)
annCharles@tom.com 25 , 152 Python
34. Python
D.haskey(key)
D key key in D.keys()
>>> a
{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}
>>> print a.has_key("one")
1
>>> print a.has_key("abc")
0
D.items()
list tuple(pair) tuple key
value
>>> a
{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}
>>> a.items()
[(’four’, 4), (’three’, 3), (’two’, 2), (’one’, 1)]
D.copy() dict(D.items()) copy()
D.keys()
list D key
>>> a
{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}
>>> a.keys()
[’four’, ’three’, ’two’, ’one’]
a.copy() dict([(k,a[k]) for k in a.keys() ])
>>> dict([ (k,a[k]) for k in a.keys()])
{’four’: 4, ’one’: 1, ’three’: 3, ’two’: 2}
copy a.copy()
D.values()
list D value
>>> a
{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}
>>> a.values()
[4, 3, 2, 1]
annCharles@tom.com 26 , 152 Python
35. §1.9
D.update(E)
E
for k in E.keys():
D[k]=E[k]
>>> a
{’four’: 4, ’three’: 3, ’two’: 2, ’one’: 1}
>>> b={"five":5,"three":30}
>>> b
{’five’: 5, ’three’: 30}
>>> b.update(a)
>>> b
{’four’: 4, ’five’: 5, ’one’: 1, ’three’: 3, ’two’: 2}
dictionary dictionary
D.popitem()
pair D
>>> print a.popitem()
(’four’, 4)
>>> print a.popitem()
(’three’, 3)
>>> print a.popitem()
(’two’, 2)
>>> print a.popitem()
(’one’, 1)
>>> print a.popitem()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: popitem(): dictionary is empty
§1.9
§1.9.1 if
annCharles@tom.com 27 , 152 Python
36. Python
if <expr1>: <one_line_statement>
if <expr1>:
<statement-block>
if <expr1:
<statement-block>
else:
<statement-block>
if <expr1>:
<statement-block>
elif <expr2>:
<statement-block>
elif <expr3>:
<statement-block>
...
else:
<statement-block>
• if None 0 ""( ) [] ( list) {}(
dictionary ) ()( tuple )
•
•
• Python Pascal
begin ... end C { } Python
C “{” if
tab
4 8
• Python switch elif 2
• else
>>> if x>0:
2
switch
annCharles@tom.com 28 , 152 Python
37. §1.9
... print "x is positive"
... elif x==0:
... print "x is zero"
... elif x < 0:
... print "x is negative"
... else:
... print "x is not a number"
...
§1.9.2 for while break continue range()
for
for x in <sequence>:
<statement-block>
else:
<else-block>
• sequence string tuple dictionary
>>> for x in "abc" : print x
...
a
b
c
>>> for x in [1,2,3]: print x
...
1
2
3
>>> D={"one":1,"two":2,"three":3}
>>> for x in D: print "D[",x,"]=",D[x]
...
D[ three ]= 3
D[ two ]= 2
D[ one ]= 1
• break C
annCharles@tom.com 29 , 152 Python
38. Python
• else a ( break)
else-block C
for(i=0;i<len;i++){
if(a[i]==100) break;
}
if(i==len){/*100 not found*/
/*do something*/
}
Python
>>> a
[1, 2, 3, 4]
>>> for x in a:
... if x==100: break
... else:
... print "100 not found"
...
100 not found
else break
else
a 100 else
break if 3 else
if else
if x==100 a x not x==100
else
• x x a
>>> a=[1,2,3,4]
>>> for x in a:
... x=x+1
...
>>> x
5
>>> a
[1, 2, 3, 4]
3
annCharles@tom.com 30 , 152 Python
39. §1.9
x a Dictionary x
Dictionary name space
>>> D={"one":1,"two":2,"three":3}
>>> for x in D:
... D[x] += 1;
...
>>> D
{’three’: 4, ’two’: 3, ’one’: 2}
range() range([start,]stop,[,step]) start
stop step start 0 step 1 list
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10,2)
[1, 3, 5, 7, 9]
>>> range(1,10,-1)
[]
list
range() list
>>> a
[1, 2, 3, 4]
>>> for x in range(len(a)):
... a[x]=a[x]+2
...
>>> a
[3, 4, 5, 6]
>>>
while
while <expr1>:
<block>
else:
<else-block>
annCharles@tom.com 31 , 152 Python
40. Python
expr1 block
break expr1 else-block
>>> i=0
>>> while i < 3:
... print i ; i=i+1
...
0
1
2
>>> while i < 3:
... print i; i = i +1
... else:
... print i , "is 3"
...
0
1
2
i is 3
i=i+1
§1.10
§1.10.1
:
def <function_name> ( <parameters_list> ):
<code block>
:
• function_name
• parameters_list
• code block if while
annCharles@tom.com 32 , 152 Python
42. Python
SyntaxError: non-default argument follows default argument
§1.10.3
>>> def printValues(name,height=170,weight=70):
... print("%s’s height is %d cm,"
... " his weigth is %d kgn"%(name,height,weight))
...
>>> printValues("Charles")
Charles’s height is 170 cm, his weigth is 70 kg
>>> printValues("Charles",175)
Charles’s height is 175 cm, his weigth is 70 kg
>>> printValues("Charles",175,85)
Charles’s height is 175 cm, his weigth is 85 kg
>>>
>>> printValues("Charles",weight=85)
Charles’s height is 170 cm, his weigth is 85 kg
§1.10.4
C printf()
>>> def printf(format,*arg):
... print format%arg
...
>>> printf ("%d is greater than %d",1,2)
1 is greater than 2
*arg *
tuple printf arg
>> def printf(format,*arg):
... print type(arg)
... print format%arg
>>> printf("a",1)
<type ’tuple’>
annCharles@tom.com 34 , 152 Python
43. §1.10
arg tuple tuple arg
dictionary
>>> def printf(format,**keyword):
... for k in keyword.keys():
... print "keyword[%s] is %s"%(k,keyword[k])
...
>>> printf("ok",One=1,Two=2,Three=3)
keyword[Three] is 3
keyword[Two] is 2
keyword[One] is 1
**keyword **
One=1,Two=2,Three=3 dictionary keyword
keys ["One","Two","Three"] values [1,2,3]
*arg **keyword
>>> printf("%d is greater than %d",2,1,Apple="red",One="1")
2 is greater than 1
keyword[Apple]=red
keyword[One]=1
>>> def testfun(fixed,optional=1,*arg,**keywords):
... print "fixed parameters is ",fixed
... print "optional parameter is ",optional
... print "Arbitrary parameter is ", arg
... print "keywords parameter is ",keywords
...
>>> testfun(1,2,"a","b","c",one=1,two=2,three=3)
fixed parameters is 1
optional parameter is 2
Arbitrary parameter is (’a’, ’b’, ’c’)
keywords parameter is {’three’: 3, ’two’: 2, ’one’: 1}
annCharles@tom.com 35 , 152 Python
44. Python
§1.10.5 Doc String
LISP Python
__doc__
string __doc__ string __doc__ None
>>> def testfun():
... """
... this function do nothing, just demostrate the use of the
... doc string.
... """
... pass
...
>>> print testfun.__doc__
this function do nothing, just demostrate the use of the
doc string.
>>>
pass C {} __doc__
>>> print " ".join.__doc__
S.join(sequence) -> string
Return a string which is the concatenation of the strings in the
sequence. The separator between elements is S.
>>> print range.__doc__
range([start,] stop[, step]) -> list of integers
Return a list containing an arithmetic progression of
integers. range(i, j) returns [i, i+1, i+2, ..., j-1];
start (!) defaults to 0.When step is given, it specifies
the increment (or decrement). For example, range(4) returns
[0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of
4 elements.
§1.10.6 lambda
functional programming lambda LISP
annCharles@tom.com 36 , 152 Python
45. §1.10
functional programming language functional programming
lambda
>>> f = lambda a,b: a+b
>>> f(1,2)
3
>>> f("abc","def")
’abcdef’
f def f(a,b): return a+b
lambda
>>> def incfun(a):
... return lambda x: x+a
...
>>> incfun(2)(12)
14
>>> incfun(2)(13)
15
>>> incfun(4)(13)
17
>>>
§1.10.7 (scope)
LGB python local name space (
) global name space( ) buildin name space (
) global
>>> a=1
>>> def testfun():
... a=2
... print a
...
>>> testfun()
2
>>> a
1
testfun() a local name space a global name space a
global name space
annCharles@tom.com 37 , 152 Python
46. Python
>>> a=1
>>> def testfun():
... global a
... a=2
... print a
...
>>> testfun
<function testfun at 0x8176264>
>>> testfun()
2
>>> a
2
>>>
§1.10.8 (nested)
Python
>>> def outfun(a,b):
... def innerfun(x,y):
... return x+y
... return innerfun(a,b)
...
>>> outfun(1,2)
3
C C static
Pascal
§1.10.9 function
python
>>> def change(x,y):
... x=2
... y[0]="hello"
...
>>> x=1
>>> y=[1,2]
annCharles@tom.com 38 , 152 Python
47. §1.11 (module) (package)
>>> change(x,y)
>>> x
1
>>> y
[’hello’, 2]
x y name space
x y function local name space
name function function x=2
name x bind name
y[0]="hello" y bind y
name space
§1.11 (module) (package)
§1.11.1 module
module class (current direc-
tory) testmodule.py
"""
this only is a very simple test module
"""
age=0 # a sample attribute
def sayHello(): # a sample function in a module
print "Hello"
if __name__ == "__main__"
sayHello()
module function doc string
doc string doc string import
module
>>> import testmodule
>>> print testmodule.__doc__
this only is a very simple test module
>>>
annCharles@tom.com 39 , 152 Python
48. Python
testmodule attribute
>>> testmodule.age
0
>>> testmodule.age=1
>>> testmodule.age
1
>>> testmodule.sayHello
<function sayHello at 0x8174a34>
>>> testmodule.sayHello()
Hello
>>> sayHello=testmodule.sayHello
>>> sayHello()
Hello
>>> sayHello
<function sayHello at 0x8174a34>
>>>
>>> othermodule=testmodule
>>> othermodule.age=100
>>> testmodule.age
100
modname.attribute module attribute
module class module attribute name space
module name space module attribute
module attribute module name space name
sayHello=testmodule.sayHello() global name space
name map( ) testmodule name space name object
sayHello function object sayHello
name space module
object testmodule name global name space name
testmodule object module object othermodule = testmodule
module functions modulename.funcname
import module python
>>> from testmodule import age, sayHello
>>> age
0
>>> sayHello
annCharles@tom.com 40 , 152 Python
49. §1.11 (module) (package)
<function sayHello at 0x81631a4>
>>> sayHello()
Hello
>>> testmodule
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name ’testmodule’ is not defined
>>>
import testmodule
age=testmodule.age
sayHello=testmodule.sayHello
from testmodule import
name space testmodule name import testmodule
name space testmodule name
from testmodule import * testmodule name space name
name space name name
import testmodule testmodule.py
reload(testmodule) testmodule
§1.11.2 module
python module import testmodule
• testmodule.py
• (environment variables) PYTHONPATH PATH
• PYTHONPATH unix
.:/usr/local/lib/python
python sys.path module sys.path
>>> import sys
>>> print sys.path
[’’, ’/usr/lib/python2.2’, ’/usr/lib/python2.2/plat-linux2’,
’/usr/lib/python2.2/lib-dynload’,
’/usr/lib/python2.2/site-packages’]
annCharles@tom.com 41 , 152 Python
50. Python
module module module
module module
§1.11.3 package( )
package module package
• testpackage
• testpackage __init__.py
• testpackage testmodule py
testmodule.py
python
>>> import testpackage.testmodule
>>> testpackage.testmodule.sayHello()
Hello
package module name space
package package
modules
§1.12 name space( )
name space name space
python
name space? name space (name) (object) (map)
name object name object (bind)
name object
python object function module class package
objects
objects ? name! object name object
object name object Charles
Charles Charles
Charles
Python name space : build-in name space ( )
global name space ( ) local name space( ) name space
name name name space
annCharles@tom.com 42 , 152 Python
51. §1.12 name space( )
local name space name bind global
name space name
object name space object.name object name
space name object name space “ ” object
name space name name space name
name “ ” object name
space “ ” name “ ” object
name space “ ” name
“ ”
name space
name space
python file unix
object module class function instance name
space name space name space
module name space module import
module python module module
name space global name space name space module
attribute __name__ module module __name__ __main__
>>> print __name__
__main__
module __name__ attribute module
module
if __name__ == "__main__"
sayHello() #
modoule module import name space
name __name__ module import
__name__ “__main__”
python testmodule.py module import
module name space global name space , python global name space
__name__ “__main__”
function function local name space function
function exception local name space
>>> def testfun():
... print locals()
annCharles@tom.com 43 , 152 Python
52. Python
... print globals()
...
>>>
>>> testfun()
{}
{’__builtins__’: <module ’__builtin__’ (built-in)>, ’__name__’: ’__main__’,
’testfun’: <function testfun at 0x8174dd4>, ’__doc__’: None}
>>>
locals() globals() global name space local name space name space
dictionary dictionary (key name) pair key
name value name object
scope( )? scope python (textually) “
” name :
• “ ” unqualified reference name name
• unqualified reference . name a unqualified name a.b
LGB scope :
scope local name space scope module global name space
scope buildin name space scope unqualified
name L local G gloabl B buildin
global unqualified name scope global name space
function alias alias=module_name.funcname function
>>> def sayHello():
... print "Hello"
...
>>> saidHello=sayHello
>>> saidHello
<function sayHello at 0x8174bb4>
>>> sayHello
<function sayHello at 0x8174bb4>
>>> sayHello()
Hello
annCharles@tom.com 44 , 152 Python
53. §1.12 name space( )
>>> saidHello()
Hello
sayHello saidHello object
a=[1,2] name space name
[1,2] object (bind) namespace
name object java (reference)
C pointer( )
del name space name
>>> a=1
>>> a
1
>>> del a
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name ’a’ is not defined
name space name object (bind)
name bind object java
C C++
python name object
object referece counter name object bind
bind reference count 1 bind 1 reference counter
0
python
tuple dictionary list string int
long float module function class methord module
class Basic Basic
print "1" + "2"
12
print 1 + "2"
3
"1"+"2" "3" "12"
name space name
space name
annCharles@tom.com 45 , 152 Python
54. Python
(variable) (name)
module class
alias ( )
§1.13
Python (OO) Python
C GTK C Unix
“ ”
open write read close ioctrl ( )
(encapsulation) (Inheritance) (Polymorphism)
(abstraction) (interface) (implemetation)
>>> class SimplestClass:
... pass
...
class
§1.13.1
>>> class SampleClass:
... def __init__(self):
... print "OK, I was born."
...
>>> a=SampleClass()
OK, I was born.
>>> AClass = SampleClass
>>> b=AClass()
OK, I was born.
>>>
Python C++ object
__init__
annCharles@tom.com 46 , 152 Python
55. §1.13
class (function)
C++ template class
template
AClass = SampleClass function alias class alias
class name space
name space
(virtual function)
instance( ) obj=ClassName()
obj name space
§1.13.2 (method)
class methord __init__ methord
self C++ Java this
methord self
methord self
: class methord obj class
A instance sayHello(self) class A methord
obj.sayHello() A.sayHello(obj)
name space class name space
instance name space
class methord self methord local name space class instance
obj=A_Class() instance instance name
space name space A_Class name space
“ ” class instance name space class name space
>>> class A:
... def sayHello(self):
... print "hello"
...
>>> obj=A()
>>> obj.sayHello()
hello
>>> A.sayHello(obj)
hello
self instance
annCharles@tom.com 47 , 152 Python
56. Python
§1.13.3 (property)
class name space class
obj a
obj.a =1 class methord self.a=1
obj.a=1 instance name
space class instance
del instance
>>> class A:
... name="abc"
...
>>> obj1=A()
>>> obj2=A()
>>> obj1.name="xyz" # obj1 name
>>> obj2.name # obj2
’abc’
>>> obj1.name # name space
’xyz’ # .
>>> class B:
... def __init__(self):
... self.a=1
...
>>> obj1=B()
>>> obj2=B()
>>> obj1.a #obj1 obj2
1 # a
>>> obj2.a
1
>>> del obj2.a # obj2 a
>>> obj2.a # , obj2.a
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: B instance has no attribute ’a’
>>> obj2.b=1 # obj2.b
>>> obj2.b #obj2 b, a
1 #obj1 a, b
#class B instance
annCharles@tom.com 48 , 152 Python
57. §1.13
§1.13.4 (inherit)
class <name>(superclass1,superclass2,...):
name space superclass name space
name name space name
space class name space
superclass.methord(self,...) name space
§1.13.5 (overload)
C++ class
name space instance name space class name
name space bind
superclass.methord(childInstance) name space
§1.13.6 class attribute
C++ Java class instance
python name space
instance name space class object
name space instance name space __class__ name
instance class __class__ python obj.__class__ obj
class
>>> class A:
... count = 0
... def __init__(self):
... self.__class__.count= self.__class__.count + 1
... # self.count
>>> A.count # A instance
0
>>> a=A() # A instance
>>> a.count # a.count A.count name space
1
>>> a.count = 2 # a.count
>>> a.count
2
annCharles@tom.com 49 , 152 Python
58. Python
>>> A.count # A.count
1 # A instance
>>> a.__class__ # a name space __class__ name
<class __main__.A at 0x81566d4>
>>> a.__class__ is A # name A class bind .
1 # , ,
>>> b=A() # instance
>>> A.count # __init__ self.__class__ 1
2 # self.__class__ A .
# A instance .
§1.13.7 Abstrace Class
Java interface C++ abstract class python
class AbstractClass:
def AbstrctMethord(self):
raise NotImplementedError
exception abstract class
§1.13.8 Python
OO ( )
OO
Python java C++ SmallTalk Python name
space
Pyton
( )
§1.13.9 Python class methord
Python class methord __init__
• __init__ obj=A_Class(arg,...)
self A_Class
• __del__(self) name object
bind
annCharles@tom.com 50 , 152 Python
59. §1.13
• __repr__(self) repr() eval()
• __str__(self) __repr__
__str__
>>> class A:
... def __repr__(self):
... return "A()"
... def __str__(self):
... return "ok, I am here"
...
>>> x=A()
>>> print x
ok, I am here
>>> print repr(x)
A()
>>> b = eval(repr(x))
>>> b
A()
>>>
eval(str) python
C++
• __cmp__(self,other) 0 1 −1
>>> class Dog:
... def __cmp__(self,other):
... if other > 0 : return 1;
... elif other < 0 : return -1;
... else: return 0
...
>>> dog = Dog()
>>> if dog > -10 : print "ok"
...
>>> if dog < -10 : print "ok"
...
ok
>>> if dog == 0 : print "ok"
annCharles@tom.com 51 , 152 Python
60. Python
...
ok
>>>
__cmp__
? python
• __nozero__(self) None "" ()
0
1
>>> class Dog:
... alive=0
... def __nonzero__(self):
... if self.alive==0 : return 0
... else: return 1
...
>>> dog = Dog()
>>> dog.alive
0
>>> if dog : print "the dog is alive"
... else: print " the dog is dead"
...
the dog is dead
>>> dog.alive =1
>>> if dog : print "the dog is alive"
... else: print " the dog is dead"
...
the dog is alive
>>>
• __len__(self) len object
len(obj)
>>> class EmptyClass:
... pass
...
>>> obj=EmptyClass()
annCharles@tom.com 52 , 152 Python
61. §1.13
>>> len(obj)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: EmptyClass instance has no attribute ’__len__’
>>> class Dog :
... def __len__(self):
... return 1000
...
>>> dog = Dog()
>>> len(dog)
1000
__len__ __len__
len(dog) ?
EmailBody class len(a_email_body)
• __getitem__(self,key) self[key] list dictionary tuple
>>> class Zoo:
... def __getitem__(self,key):
... if key == "dog" : return "dog"
... elif key == "pig" : return "pig"
... elif key == "wolf" : return "wolf"
... else : return "unknown"
...
>>> zoo=Zoo()
>>> zoo["dog"]
’dog’
>>> zoo["pig"]
’pig’
>>> zoo["wolf"]
’wolf’
__getitem__ sequence python object
__getitem__ protocol ( ) java interface
for
annCharles@tom.com 53 , 152 Python
62. Python
>>> class A:
... def __getitem__(self,key):
... print "debug: key is %s"%key
... if key >=0 and key <=5: return key * key
... raise IndexError
... return None
...
>>> a=A()
>>> for k in a: print k
...
debug: key is 0
0
debug: key is 1
1
debug: key is 2
4
debug: key is 3
9
debug: key is 4
16
debug: key is 5
25
debug: key is 6
>>>
raise IndexError return None for 0
key a while
__tmp__ = 0
while(1):
try :
k = a[__tmp__]
... # for
__tmp__ = __tmp__ +1
except IndexError:
break
for k in a for
while for
annCharles@tom.com 54 , 152 Python
63. §1.13
• __setitem__(self,key,value) obj[key]=value
>>> class A:
... def __setitem__(self,key,value):
... print "debug: you want to set [%s] to [%s]"%
... (key,value)
...
>>> a=A()
>>> a["key"]="value"
debug: you want to set [key] to [value]
>>>
• __delitem__(self,key) del obj[key]
>>> class A:
... def __delitem__(self,key):
... print "debug: you want to del [%s]"%(key,)
...
>>> a=A()
>>> del a["key"]
debug: you want to del [key]
__delitem__ __setitem__ __getitem__
__getslice__(self,i,j) __setslice__(self,i,j,value)
__delsclice__(self,i,j)
0
>>> class A:
... def __getslice__(self,i,j):
... print "you want to get the slice %d:%d"%(i,j)
... def __setslice__(self,i,j,value):
... print "you want to set the slice %d:%d to %s"%
... (i,j,value)
... def __delslice__(self,i,j):
... print "you want to del the slice %d:%d"%(i,j)
...
>>> a=A()
>>> print a[1:2]
you want to get the slice 1:2
annCharles@tom.com 55 , 152 Python
64. Python
None
>>> print a[:]
you want to get the slice 0:2147483647
None
>>> a[2:3]= [1,2]
you want to set the slice 2:3 to [1, 2]
>>> del a[:]
you want to del the slice 0:2147483647
>>>
• __contains__(self,other) object sequence in
>>> class A:
... def __contains__(self,other):
... if other=="ok" : return 1
... return 0
...
>>> a=A()
>>> if "ok" in a: print "ok in a"
... else : print "ok not in a"
...
ok in a
• __call__(self,arg1,arg2,...) object
>>> class A:
... def __call__(self,*arg):# ,
... for k in arg:
... print k
...
>>> a=A()
>>> a("hello","World")
hello
World
>>>
•
annCharles@tom.com 56 , 152 Python
65. §1.14 (exception)
__add__(self,other) self + other
__sub__(self,other) self - other
__mul__(self,other) self * other
__div__(self,other) self / other
__mod__(self,other) self % other
__divmod__(self,other) divmod(self,other)
__pow__(self,other) self ** other
__pow__(self,other,modulo) pow(self,other,modulo)
__lshift__(self,other) self << other
__rshift__(self,other) self >> other
python class
list dictionary list
python module lib class
lunix /usr/lib/python2/ UserList.py UserDict.py
§1.14 (exception)
§1.14.1
C
int fun1()
{
...
if ( open(...) == -1 ){
return -1;
}
...
}
int fun2()
annCharles@tom.com 57 , 152 Python
66. Python
{
...
if (fun1()==-1){
return -1;
}
...
}
int main()
{
...
if(fun2()==-1){
return -1;
}
}
C
•
•
“ ” :
unsigned int r;
r=read(fd,buffer,len_of_buffer);
for(i=0;i<r;i++){
// do something
}
read −1 for
r
“ ”
•
read −1 errno
annCharles@tom.com 58 , 152 Python
68. Python
• exception exception except
ExceptionType exception ExceptioinType
• statement 2
• exception
try exception
• try
1/0 0
exception return C exception
exception
lib module exception try except
try :
... # statements 1
except (ExceptionType1,ExceptionType2) :
... # statements 2
except (ExceptionType3,ExceptionType4) :
... # statements 3
except:
... # statements 4
except exception exception try
else exception else
:
try:
f = open("/home/chunywang/tmp/test.py","r")
except IOError:
print "can not open file"
else:
for i in f.readlines(): print i
try:
f = open("/home/chunywang/tmp/test.py","r")
annCharles@tom.com 60 , 152 Python
69. §1.14 (exception)
for i in f.readlines(): print i
except IOError:
print "can not open file"
try IOError
open readlines() exception
try exception exception
except exception
try:
try:
f = open("/home/chunywang/tmp/test.py","r")
except IOError:
print "can not open file"
else:
for i in f.readlines(): print i
except IOError:
print "read faid"
:
try:
f = open("/home/chunywang/tmp/test.py","r")
except IOError:
print "can not open file"
else:
try:
for i in f.readlines(): print i
except IOError:
print "read faid"
try:
f = open("/home/chunywang/tmp/test.py","r")
except IOError:
print "can not open file"
return None
for i in f.readlines(): print i
annCharles@tom.com 61 , 152 Python
79. Python
§3.1
import
print obj.__doc__
§3.1.1
3.1-1
:
>>> help(dir)
Help on built-in function dir:
dir(...)
dir([object]) -> list of strings
Return an alphabetized list of names comprising (some of)
the attributes of the given object, and of attributes
reachable from it:
No argument: the names in the current scope.
Module object: the module attributes.
Type or class object: its attributes, and recursively the
annCharles@tom.com 71 , 152 Python
80. Python
help(obj) obj
callable(obj) obj
repr(obj) obj
eval
eval(str) str python
dir(obj) obj name space name
hasattr(obj name) obj name space
name
getattr(obj name) obj name space name
setattr(obj name value) obj name space name
value object
delattr(obj name) obj name space name
vars(obj) object name space
dictionary
locals() name space dictionary
globals() name space dictionary
type(obj) obj
isinstance(obj cls) obj cls instance
issubclass(subcls supcls) subcls supcls
3.1-1: Python
attributes of its bases.
Otherwise: its attributes, its class’s attributes, and
recursively the attributes of its class’s base classes.
>>> callable(dir) #
1
>>> a=1
>>> callable(a) #
0
>>> a=dir # aliase
>>> callable(a)
1
annCharles@tom.com 72 , 152 Python
84. Python
[’__builtins__’, ’__doc__’, ’__module__’, ’a’, ’abc’]
>>> x=A()
>>> x.abc() #
ok
>>>
C++ Java
Python Python
C++ C++ C++ ?
C++ Python
C++ Python
C++
C++
python profile
module python “ ” “ ”
compile
>>> c=compile("print ’hello’","abc","single")
>>> exec c
hello
>>> c=compile("raise 1 ","abc","single")
>>> exec c
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "abc", line 1, in ? # abc
TypeError: exceptions must be strings, classes, or instances,
not int
compile Python
“single” “exec” “eval”
>>> code="print ’Hello World’"
annCharles@tom.com 76 , 152 Python
85. §3.1
>>> c=compile(code,"abc","exec")
>>> profile.run("for i in range(10000): exec c")
10002 function calls in 0.250 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.090 0.090 0.250 0.250 <string>:1(?)
10000 0.160 0.000 0.160 0.000 abc:1(?)
1 0.000 0.000 0.250 0.250 profile:0(for i in
range(10000): exec c)
0 0.000 0.000 profile:0(profiler)
>>> profile.run("for i in range(10000): exec code")
10002 function calls (2 primitive calls) in 0.720 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
10001/1 0.720 0.000 0.720 0.720 <string>:1(?)
1 0.000 0.000 0.720 0.720 profile:0(for i in
range(10000): exec code)
0 0.000 0.000 profile:0(profiler)
0.250 CPU seconds 0.720 CPU second
3
eval(str)
>>> a=2
>>> eval("a==1")
0
>>> eval("a=1")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 1
a=1
^
annCharles@tom.com 77 , 152 Python
86. Python
SyntaxError: invalid syntax
§3.2
sys import sys
(command line arguments) sys.argv list
sys.stdout sys.stdin sys.stderr
sys.exit(exit_code)
modules sys.modules dictionary
module sys.modules["os"] module os
sys.platform
sys.path list module package
os import os
os.environ dictionary
os.environ["HOME"] HOME
os.chdir(dir)
os.cwd()
os.getegid() id
os.getgid() id
os.getuid() id
os.geteuid() id
os.setegid() id
os.setgid() id
os.setuid() id
os.seteuid() id
os.getgroups()
os.getlogin()
os.getenv
os.putenv
os.umask umask
3.2-3:
3.2-3 python
annCharles@tom.com 78 , 152 Python
87. §3.2
shell
os.system() shell
#!/usr/bin/python
import os,sys
cmd=sys.stdin.readline()
while cmd:
os.system(cmd)
cmd=sys.stdin.readline()
os.system(cmd)
os shell
>>> os.mkdir(’/tmp/xx’) #
>>> os.system("echo ’hello’ > /tmp/xx/a.txt")
0
>>> os.listdir(’/tmp/xx’)
>>> os.listdir(’/tmp/xx’)
[’a.txt’]
>>> os.rename(’/tmp/xx/a.txt’,’/tmp/xx/b.txt’)
>>> os.listdir(’/tmp/xx’)
[’b.txt’]
>>> os.remove(’/tmp/xx/b.txt’)
>>> os.listdir(’/tmp/xx’)
[]
>>> os.rmdir(’/tmp/xx’)
>>> os.listdir(’/tmp/xx’) #
Traceback (most recent call last):
File "<stdin>", line 1, in ?
OSError: [Errno 2] No such file or directory: ’/tmp/xx’
chown chmod unlink symlink link Unix
os POSIX Unix
Python Unix POSIX
Advanced Programming In Unix Environments Unix
annCharles@tom.com 79 , 152 Python
89. §3.2
# Windows
>>> os.path.ismount(os.getcwd())
1
# Windows
>>> os.path.samefile(os.getcwd(),’/home/Charles’)
1
# .
>>> def test_find(filename,dirname,names):
... if filename in names:
... print os.path.join(dirname,filename)
...
>>> os.path.walk(’/home/Charles’,test_find,"a.c")
/home/Charles/tmp/a.c
os.path.walk(p,func,arg)
os.path.walk p
p func func(arg,dirname,names)
walk arg dirname names list
dirname 4
a.c Unix Windows
§3.2.1
file string integer float
f=open("filename","r")
filename “r” “w” “rw”
“rb” “wb”
§3.2.2
open file
>>> f=open("/tmp/x.txt","w")
>>> f.write("a")
>>> f.close()
>>> f=open("/tmp/x.txt","r")
>>> f.read()
’a’
>>> f.read()
annCharles@tom.com 81 , 152 Python
90. Python
’’
f.read(size) size size
f.read(size)
f.open("/tmp/x.txt","r")
c=f.read(1)
while c:
print c
c=f.read(1)
f.readline()
f.readlines() list list
“n”
f.write(str)
f.tell()
f.seek(off,where) where= 0 1
2 off
sys sys.stdout sys.stderr sys.stdin
>>> import sys
>>> a=sys.stdin.readline()
Hello #
>>> sys.stdout.write(a)
Hello #
>>>
writeline write writelines
§3.2.3
Python
f.close()
§3.3 regular expression
regular expression ( ) regexp Unix
vi emacs sed awk perl python re
annCharles@tom.com 82 , 152 Python
91. §3.3 regular expression
regexp module perl regexp regexp
(set) regexp (match
regexp Python match
regexp match
§3.3.1 regexp
regexp
>>> p=re.compile("abc")
>>> if p.match("abc") : print "match"
...
match
>>>
re.compile("abc") pattern (
) pattern match match object
None metacharacter ( )
^ $ * + ? { [ ] | ( )
§3.3.2
[]
• [abc] a b c a b c [abc]
metacharacter [] metacharacter
:
>>> a=".^$*+?{|()"
>>> p = re.compile("["+a+"]")
>>> for i in a:
... if p.match(i):
... print "[%s] is match"%i
... else:
... print "[%s] is not match"%i
...
[.] is match
[^] is match
[$] is match
[*] is match
annCharles@tom.com 83 , 152 Python
92. Python
[+] is match
[?] is match
[{] is match
[] is not match
[|] is match
[(] is match
[)] is match
metacharacter [] metacharacter
“^[]” ^ []
[]
• [] [] “[” “]” ?
>>> p=re.compile("[][]")
>>> p.match("]")
<_sre.SRE_Match object at 0x815de60>
>>> p.match("]")
<_sre.SRE_Match object at 0x81585e8>
>>> p.match("[")
<_sre.SRE_Match object at 0x8158330>
[ ]
• ^ [] [] [^abc]
a b c ^ []
^ ^
• - [a-zA-Z] [0-9]
• []
d [0-9]
D [^0-9]
s [ tnrfv]
S [^ tnrfv]
w [a-zA-Z0-9_]
W [^a-zA-Z0-9_]
t tab
x20 ascii 0x20
[] “.” []
n [^n]
annCharles@tom.com 84 , 152 Python
93. §3.3 regular expression
§3.3.3
regexp
• {m,n} m ( m ) n ( n ) ab{1,3}c
abc abbc abbbc ac abbbbc m n m
0 n
• * {,} (0 ) 1
• + {1,} 1
• ? {0,1} 0 1
[ab]* ababab
a ababab a ababab
python
>>> re.compile("a*").match(’aaaa’).end()
4
>>> re.compile("a*?").match(’aaaa’).end()
0
match object end
* + ? {m,n} ? *? +? ?? {m,n}?
§3.3.4
regexp
regexp regexp
re.compile("") r
raw python regexp r
>>> a=r"a"
>>> print a
a
>>> a=r""a"
>>> print a
"a
>>>
§3.3.5 re
regexp
annCharles@tom.com 85 , 152 Python
94. Python
• re.compile RegexObject regexp
• pattern match search MatchObject
• match object
RegxObject :
• RE_obj.match(str,[pos[,endpos]]) str RE_obj
MatchObject None str
>>> re.compile("a").match("abab")
<_sre.SRE_Match object at 0x81d43c8>
>>> print re.compile("a").match("bbab")
None
• RE_obj.search(str,[pos[,endpos]]) str RE_obj
>>> re.compile("a").search("abab")
<_sre.SRE_Match object at 0x81d43c8>
>>> print re.compile("a").search("bbab")
<_sre.SRE_Match object at 0x8184e18>
match()
• RE_obj.findall(str) str RE_obj tuple
MatchObject
• m.start() RE_obj.match() MatchObject start()
0
• m.end() ( )
>>> s="I say:helloworld"
>>> m=re.compile("hello").search(s)
>>> for i in range(m.start(),m.end()):
... print s[i]
...
h
e
l
l
o
>>>
annCharles@tom.com 86 , 152 Python
95. §3.3 regular expression
• m.span() tuple (m.start(),m.end())
• m.pos() m.endpos() m.re() m.string()
MatchObject
RE_obj.match(str,[pos[,endpos]]),RE_obj.search(str,[pos[,endpos]])
pos endpos RE_obj str
m.re().search(m.string(),m.pos(),m.endpos())
m
• m.finditer() iterator MatchObject
>>> for m in re.compile("[ab]").finditer("tatbxaxb"):
... print m.span()
...
(1, 2)
(3, 4)
(5, 6)
(7, 8)
§3.3.6 regexp
regexp
• | regexp A B regexp A|B A B
| Good|Bad “Good” “Bad”
“Goodad” “GooBad”
• ^ “^abc” “abc” “xabc”
search ^ ^
metacharacter ^
• $ ^ $
• A (MULTILINE) A ^
A ^
• Z (MULTILINE) Z $
Z ^
• b
locale
binfob “info” “information”
annCharles@tom.com 87 , 152 Python
96. Python
>>> print re.compile(r"binfob").match("info ") # raw
<_sre.SRE_Match object at 0x817aa98> #b
>>> print re.compile("binfob").match("info ") # raw
None #b
>>> print re.compile("binfob").match("binfob ")
<_sre.SRE_Match object at 0x8174948>
r raw b 0x8 raw
b
• B
metacharacter
: ^abc “abc” 3 1
§3.3.7 (Group)
regexp
email email header( )
email body ( ) email header email
name: Charles
Address: BUPT
telephone: 62281234
email: annCharles@tom.com
name: Ann
Address: BUPT
telephone: 62284321
email: CharlesWang@peoplemail.com.cn
Charles Ann BUPT
? Group !
>>> x="""
... name: Charles
... Address: BUPT
... telephone: 62281234
... email: annCharles@tom.com
...
1
lex “ˆabc” “abc”
annCharles@tom.com 88 , 152 Python
97. §3.3 regular expression
... name: Ann
... Address: BUPT
... telephone: 62284321
... email: CharlesWang@peoplemail.com.cn
... """
>>> p=re.compile(
... r"^name:(.*)n^Address:(.*)n^telephone:(.*)n^email:(.*)n",re.M)
>>> for m in p.finditer(x):
... print "here is your friends list"
... print "%s,%s,%s,%s"%m.groups()
...
here is your friends list
Charles, BUPT, 62281234, annCharles@tom.com
here is your friends list
Ann, BUPT, 62284321, CharlesWang@peoplemail.com.cn
p.compile() (.*) group
MatchObject groups() group Charles
MatchObject start() end() span() group() group
0 1
regexp group m.start(1) name m.start(2)
Address group ( :
>>> re.compile("(a(b)c)d").match("abcd").groups()
(’abc’, ’b’)
>>>
( abc b p.finditer(x)
MatchObject print m.groups()
m.groups() tuple string group
: (bw+)s+1
m.group(1) name
group group
m.group(’name’) name
:
>>> p=re.compile(r"^name:(?P<name>.*)n^Address:(?P<address>.*)n"
r"^telephone:(?P<telephone>.*)n^email:(?P<email>.*)n",re.M)
>>> for m in p.finditer(x):
annCharles@tom.com 89 , 152 Python
98. Python
... print m.groups()
(’ Charles’, ’ BUPT’, ’ 62281234’, ’ annCharles@tom.com’)
(’ Ann’, ’ BUPT’, ’ 62284321’, ’ CharlesWang@peoplemail.com.cn’)
>>> matchs=[m for m in p.finditer(x)]
>>> matchs[0].group(’name’)
’ Charles’
>>> matchs[0].group(’address’)
’ BUPT’
>>> matchs[0].group(’telephone’)
’ 62281234’
>>> matchs[0].group(’email’)
’ annCharles@tom.com’
>>> matchs[1].group(’name’)
’ Ann’
>>> matchs[1].group(’address’)
’ BUPT’
>>> matchs[1].group(’telephone’)
’ 62284321’
>>> matchs[1].group(’address’)
’ BUPT’
>>> matchs[1].group(’email’)
’ CharlesWang@peoplemail.com.cn’
(?P<xxx>.*) (.*) m.group(’xxx’)
group group regexp
python Perl 5
Python (?=<xxx>)
regexp : (bw+)s+1
(?P<n>bw+)s+(?=<n>) group
group Non-capture group
group MatchObject group
(?:...) Non-capture group :
§3.3.8 Compile Flag
re.compile RegxObject flag RegxObject
annCharles@tom.com 90 , 152 Python
99. §3.4 struct
DOTALL S . n
IGNORECASE I
LOCALES L w W b B locale
MULTILINE M ^ $
VERBOSE X verbose
§3.4 struct
C struct
struct{
...
} header;
write(fd,(void*) &header,sizeof(struct));
read(fd,(void*) &header,sizeof(struct));
Python
struct pack unpack cacsize
C :
$cat a.c
#include <stdio.h>
struct testheader{
int version;
char tag[4];
} ;
struct testheader header={0x00010002,"WAVE"};
int main(int argc, char **argv)
{
FILE * fp = fopen("test.dat","wb");
if(!fp) return 1;
fwrite((void*)&header,1,sizeof(header),fp);
fclose(fp);
return 0;
}
$gcc -o x a.c
$./x
$xxd test.dat
0000000: 0200 0100 5741 5645 ....WAVE
annCharles@tom.com 91 , 152 Python
100. Python
C xxd
little endian
>>> import struct
>>> data = open(’test.dat’,’rb’).read()
>>> start,stop = 0 , struct.calcsize(’hh4s’)
>>> ver1,ver2,tag= struct.unpack(’hh4s’,data[start:stop])
>>> ver
2
>>> subver
1
>>> tag
’WAVE’
unpack struct
3.4-4 3.4-4
C Python
x char ( )
c char 1
b signed char Integer
B unsigned char Integer
h signed short Integer
H unsigned short Integer
i signed int Integer
I unsigned int Integer
l signed long Integer
L unsigned long Integer
q signed long Integer
Q unsigned long Integer
f float Float
d double Float
s char[] String
p char[] String
P void* Integer
3.4-4: struct
annCharles@tom.com 92 , 152 Python
101. §3.5 Cmd
@ native native
= native standard
< little-endian standard
> big-endian standard
! network (= big-endian) standard
3.4-5:
• q Q 64
•
>>> struct.unpack(’2h4s’,data[start:stop])
(2, 1, ’WAVE’)
• x
>>> struct.unpack(’xxh4s’,data[start:stop])
(1, ’WAVE’)
• s 4s 4 p
“Pascal String” 256
• P 64 long integer 32 integer
struct Intel CPU
little-endian SPARC CPU big-endian C
3.4-5: :
>>> data
’x02x00x01x00WAVE’
>>> struct.unpack(’!hh4s’,data)
(512, 256, ’WAVE’)
>>> struct.unpack(’<hh4s’,data)
(2, 1, ’WAVE’)
pack unpack
§3.5 Cmd
/usr/lib/python2.2 cmd.py
annCharles@tom.com 93 , 152 Python
103. §3.5 Cmd
%python demo_cmd.py
welcome a simple command interface demo demo
(Cmd) help
Undocumented commands:
======================
help say_hello
(Cmd) say_hello
hello!
(Cmd) say_hello Charles
hello! Charles
do_foo foo
do_foo argc foo xxx xxx
cmd_loop
cmd_loop readline
Cmd help
§3.5.2
default(self,line)
line
Cmd
print ’*** Unknown syntax:’, line
§3.5.3 EOF
EOF
(Control-D)
% echo "say_hello Charles" | python demo_cmd.py
EOF
def do_EOF(self,arc):
return 1
do_EOF Control-D
do_xxx cmd_loop
“ exit”
annCharles@tom.com 95 , 152 Python
104. Python
def do_exit(self,arc):
return 1
§3.5.4
:
def emptyline(self):
pass
emptyline
§3.5.5
Bash tab
:
def complete_say_hello(self,text,line,begingidx,endidx):
x=["Charles","Smith","Tom"]
return [ k for k in x if k.find(text)==0]
“say hello” tab
Charles Smith Tom
“C” tab “Charles”
complete_say_hello say_hello text
line beginidx text line endidx
text line
tab init
x=CmdInterface("?")
“?”
§3.5.6
init
sys.stdin sys.stdout
annCharles@tom.com 96 , 152 Python
105. §3.5 Cmd
§3.5.7
Cmd “Cmd” prompt
:
x=CmdInterface()
x.prompt="?"
x.cmdloop(welcome)
§3.5.8
help “Undocumented commands:”
Cmd
• Undocumented commands:
• Documented commands:
• Miscellaneous help topics:
topic
say_hello Undocumented commands.
:
def help_say_hello(self):
print """
say_hello [<person>]
say hello to somebody
"""
say_hello Documented commands. “ help say hello”
help_say_hello
:
def help_test(self):
print """
this is only a test topic
"""
“test” Miscellaneous help topics “help test” help_test
“?test” “?say hello”
annCharles@tom.com 97 , 152 Python
116. Python
-h, --help show this help message and exit
-v, --verbose make lots of noise [default]
-q, --quiet be vewwy quiet (I’m hunting wabbits)
-fFILE, --file=FILE write output to FILE
-mMODE, --mode=MODE interaction mode: one of ’novice’,
’intermediate’[default], ’expert’
%
:
(a) usage %prog sys.argv[0]
usage
’usage : %prog [options]’
(b) option help
help
(c) meta-variable
-mMODE -fFILE metavar metavar option
5. option
option
:
:
$./opt.group1.py --help
usage: opt.group1.py [options] arg1 arg2
options:
-h, --help show this help message and exit
-v, --verbose make lots of noise [default]
-q, --quiet be vewwy quiet (I’m hunting wabbits)
-fFILE, --file=FILE write output to FILE
-mMODE, --mode=MODE interaction mode: one of ’novice’,
’intermediate’[default], ’expert’
Dangerous Options:
annCharles@tom.com 108 , 152 Python
117. §3.7
Caution: use these options at your own risk. It is
believed that some of them bite.
-g Group option.
$
:
(a) OptionGroup parser group
group option group
(b) parser group option
(c) add_option_group group parser
6. usage parser version
-v --version option
parser = OptionParser(usage="%prog [-f] [-q]",
version="%prog 1.0")
%prog sys.argv[0]
§3.7
time
C C
:
• epoch ( ) epoch epoch epoch
0 epoch epoch 0 UNIX epoch 1970
1 1 0 0 0
epoch
C
UNIX 2038
• 2000 Python C 2000
epoch
python-lib
annCharles@tom.com 109 , 152 Python