--- layout: post status: publish published: true title: Simple Is Beautiful author: display_name: Tomas Restrepo login: tomasr email<EMAIL_ADDRESS>url: http://winterdom.com/ author_login: tomasr author_email<EMAIL_ADDRESS>author_url: http://winterdom.com/ wordpress_id: 255 wordpress_url: http://winterdom.com/2008/02/simpleisbeautiful date: '2008-02-21 05:47:45 +0000' date_gmt: '2008-02-21 05:47:45 +0000' categories: - Vista tags: [] comments: - id: 191 author: Mike author_email<EMAIL_ADDRESS>author_url: http://blog.prilliman.com date: '2008-02-21 12:45:21 +0000' date_gmt: '2008-02-21 12:45:21 +0000' content: | Well, if you truly don't like the Vista default background there is nothing keeping you from changing it. Go grab a copy of Stardock's Logon Studio (free) and create any background you want. http://www.stardock.com/products/logonstudio/ - id: 192 author: Tomas Restrepo author_email<EMAIL_ADDRESS>author_url: http://www.winterdom.com/weblog/ date: '2008-02-21 13:01:54 +0000' date_gmt: '2008-02-21 13:01:54 +0000' content: | Mike: Yes, I'm aware of those products, though not a big fan of them myself (already have way too much crap running on my machine). Actually, my subtle point was that it can be a bit surprising to see how the Windows Server builds sometimes capture things better than the consumer builds do. In fact, it's pretty of a surprise (to me at least) how Windows Server keeps getting better and better while the Windows Desktop, well, not so much.  Windows Server 2008 is even better, from what I've seen (IIS7 rocks). - id: 193 author: Mike author_email<EMAIL_ADDRESS>author_url: http://blog.prilliman.com date: '2008-02-21 13:26:15 +0000' date_gmt: '2008-02-21 13:26:15 +0000' content: | You'll get no arguments from me on any of your points. I've been running Vista x64 on my office workstation and using the various Windows 2008 Betas/CTPs/RCs on a spare machine for what seems like years now. Now that W2K8 is fully baked that will all be changing and I will repave my workstation with Windows Server as the primary OS and virtualize anything else (I think services developers should be developing/testing on the actual platforms they are coding for anyway). I'll still run Vista Ultimate at home and on my laptop, but the work box is definitely going to get repaved real soon - I just need to find the time to do it. And yes, IIS7 totally rocks. ---
Am I the only one that thinks the Windows Server 2008 logon screen, with it's very simple blue background, is so much better looking that Vista's ugly and distracting "aurora" background?
There's just something highly appealing to me about keeping things simple and elegant...


--- layout: post title: Dreaded Blue Screen of Death strikes Olympics | Crave - CNET categories: [] tags: - bsod - dumb - geek - windows status: publish type: post published: true meta: _original_post_id: '' _original_import_author: John Duprey author: ---
August 12, 2008 3:39 PM PDTDreaded Blue Screen of Death strikes Olympics
via news.cnet.com


Data Acquisition Systems¶
Data acqusition systems consist of three main components:
Sensors to measure physical systems.
Signal conditioning/conversion.
A computing device with interfacing drivers and software for data monitoring/collection.
Sensors¶
Sonsors are sometimes called transducers, they are devices that covert physical quantities in the real world to electrical signals such voltage, current and resistance, etc. Most sensors needs electric excitaion (DC/AC power supply) and will output either analog or digital signals representing measured physical quantities.
Common Sensors |
|
|---|---|
Sensors |
Phenomenon |
Thermocouple |
Temperature |
Photo Sentor |
Light |
Microphone |
Sound |
Loadcell |
Force |
Strain gauge |
Strain |
Accelerometer |
Acceleration |
Hygrometer |
Humidity |
Seismometer |
Ground motion |
Signal Conversion/Conditioning¶
Signal conversion and conditioning are the essential components of a data acquisition system. The output signals from the sensors can be catagorized as Analog and Digital.
Analog Signal¶
Analog signals cover a wide range of physical phenomenon. The colors we see, the tones we hear, the temperatures that we feel, etc. There are infinite numbers of such analog signals.
In the perspective of data acquisition, analog signals are continuous and features three primary characteristics:
Level (Amplitude)
Shape
Frequency
Common analog signals include voltage, current, resistance, etc. Analog signals always inherently contain some degree of noise. Therefore, signal conditioning is usually needed for raw analog signals. Analog signals also need to be convereted to digital signals for communication and storage in computing devices.
Digital Signal¶
Digital signals are finite, with a predefined range, meaning there is a limited values set they can be. How many values in a predefined values set depends on the total number of levels defined in the set. Due to the binary nature of modern computing devices, the number of levels is defined by 2N, where the exponent N is called bit
, the bit
value is widely adopted in the industry for representing the resolution of digital signals.
Digital signals are discrete and features two primary characteristics:
State
Rate
Digital signals are more resistant to noise, therefore they are widely used for data transmission protocols such as HDMI for video and audio, MIDI, I2 S, and AC`97 for audio. Many instruments for laboratory are developed with proprietary digital commmunication protocols. Keep in mind that not all instrument manufactures are willing to disclose their communication protocol because of intellectual property protection or other reasons. Knowing whether the communication protocol is available for an instrument of interest can be extremely beneficial for future expandability and maintainability.
Analog to Digital Conversion¶
The most common signal types we encounter in the laboraotry are analog. However, analog signals cannot be directly stored in computing devices without being converted in to digital signals. An analog to digital converter (ADC) does exactly that. An analog to digital converter takes discrete samples from the continuous analog signal with a preset sampling rate (frequency). reverse process of converting digital signals to analog signals can be performed by a digital to analog converter (DAC)
Keep in mind that higher bit
resolution of an ADC means steeper price tag. When choosing a ADC, consider a resonable resolution with a acceptable budget.
Digital Sampling and Nyquist Frequency¶
Becasue ADCs convert analog signals to digital signals by sampling, the sampling rate has to be much faster than the maximum frequency of the input analog signal in order to get a relatively good conversion. Take a look at the graph below:
The Nyquist Sampling Rate is defined as two times the highest frequency of the input signal. The Nyquist sampling rate is the minimum sampling rate required to avoid aliasing. However, in laboratory tests, ADC sampling rate should be at least ten times higher than the highest input frequency.


If this option is enabled, IntelliJ IDEA will check if there are pending incoming commits that have not been
fetched to your local repository, and will mark such branches in the Branches
popup.
Select how you want to IntelliJ IDEA to query the remote to check for incoming commits:
- Auto:
IntelliJ IDEA will check for updates in the background if HTTP or Git protocol is used to access the remote. If
SSH is used, this check will not be performed so that external authentication applications don't popup
unexpectedly.
- Always:
IntelliJ IDEA will check for updates in the background even if SSH is used to access the remote.
- Never:
IntelliJ IDEA will not query the remote for incoming commits, and a warning will be displayed in the Branches popup, allowing you to run the check manually.


{% extends "layout_bsa.html" %} {% block page_title %} Help paying for NHS Costs prototype {% endblock %} {% block content %} You're signed out You're now signed out of the assessor view for 'Apply for help with NHS costs'. Sign in to your assessor view {% endblock %}
You're now signed out of the assessor view for 'Apply for help with NHS costs'.
Sign in to your assessor view


A service provides capabilities mostly for plugins to use. Services are instantiated once by the framework and that same instance shared across all plugins. Services are accessed via interfaces to allow them to be switched out for different implementations.
There are a few service providers that come with StaticGenie
They can be configured within the /config.ts
file.
Responsible for storing, freezing and passing around the global model. It’s primary use is for plugins to add data to it during the plugins initialisation. Once all plugins have initialised the model is then frozen and passed to plugins generate methods. Where plugins can query it for data to base it’s generated pages on. The service providers data is used by the theme service provider and hence, the global model data is made available to every layout via the key global.*
.
The global model uses the service name globalmodel
and can be fetched like this; services.get("globalmodel")
It’s methods/properties you can use within your plugins are defined on it’s iGlobalModel
interface located in /src/services/globalmodel.ts
.
The default global model class is GlobalModel
.
Responsible for writing the pages once they have been built. This will define where the pages end up such as the console or the file system.
The page writer uses the service name pagewriter
and can be fetched like this; services.get("pagewriter")
It’s methods/properties you can use within your plugins are defined on it’s iPageWriter
interface located in /src/services/pagewriter.ts
.
There are two page writer classes available, although, you will likely not need to change it from the default:
PageWriterFile
- The default which will write the pages to the file system within the /www
directoryPageWrtierConsole
- Will write the files to the consoleResponsible for showing which pages were or were not generated (but should have been generated).
The report uses the service name report
and can be fetched like this; services.get("report")
It’s methods/properties you can use within your plugins are defined on it’s iReport
interface located in /src/services/report.ts
.
The default report class is ReportConsole
which will print the report to the console.
Responsible for passing the model to the correct layout and rendering the result.
The theme uses the service name theme
and can be fetched like this; services.get("theme")
It’s methods/properties you can use within your plugins are defined on it’s iTheme
interface located in /src/services/theme.ts
.
The default theme class is ThemeEJS
which allows for EJS syntax within the .ejs layouts/partials.
In the event you want to create a service. Such as interacting with Twitter or something more elaborate. Read more about creating a service


MyBatisNotes
- MyBatisNotes
- Basic config
- Configtration XML
- Acquiring(获取) a SqlSeesion from SqlSessionFactory
- Exploring Mapped SQL Statements
- Scope and Lifecycle(生命周期)
- When your javabean property name is different from the field in the table
- Difference between $ and
- realize not case sensitive(大小写敏感)
- Transmit multi parameters to mapper.xml
- Insert
- Update
- Some Question I have met
- Refers
Basic config
Maven dependency
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--MyBatis Generator -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<!--日志处理,mabatis 默认用这个，带log4j-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<!--Mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!--Mybatis spring插件-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
springmvc-config
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--引入数据库连接配置-->
<properties resource="db.properties" />
<!-- 定义数据源-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
<!--<environment id="test">-->
<!--</environment>-->
<!--<environment id="production">-->
<!--</environment>-->
</environments>
<mappers>
<!--<mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
<package name="com.mapper" />
</mappers>
</configuration>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=123456
Deploy Log4j
New a log4j.properties file.
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
If you want to tune(调整) the logging at a finer level you can turn logging on for specific statements instead of the whole mapper file.
log4j.logger.org.mybatis.example.BlogMapper.selectBlog=TRACE
By the contrary you may want want to enable logging for a group of mappers.
log4j.logger.org.mybatis.example=TRACE
There are queries that can return huge result sets. In that cases you may want to see the SQL statement but not the results. For that purpose SQL statements are logged at the DEBUG level
log4j.logger.org.mybatis.example=DEBUG
Configtration XML
typeAliases
A type alias is simply a shorter name for a Java type. It's only relevant to the XML configuration and simply exists to reduce redundant typing of fully qualified classnames
<typeAliases>
<typeAlias alias="Author" type="domain.blog.Author"/>
</typeAliases>
With this configuration, Blog
can now be used anywhere that domain.blog.Blog
could be.
You can also specify a package where MyBatis will search for beans.
<typeAliases>
<package name="domain.blog"/>
</typeAliases>
Each bean found in domain.blog
, if no annotation is found, will be registered as an alias using uncapitalized non-qualified class name of the bean. That isdomain.blog.Author
will be registered as author
. If the @Alias
annotation is found its value will be used as an alias. See the example below
@Alias("author")
public class Author {
...
}
Acquiring(获取) a SqlSeesion from SqlSessionFactory
you can acquire an instance of SqlSession. The SqlSession contains absolutely every method needed to execute SQL commands against the database. You can execute mapped SQL statements directly against the SqlSession instance. For example:
SqlSession session = sqlSessionFactory.openSession();
try {
Blog blog = session.selectOne(
"org.mybatis.example.BlogMapper.selectBlog", 101);
} finally {
session.close();
}
there is now a cleaner approach(方法). Using an interface (e.g. BlogMapper.class) that properly describes the parameter and return value for a given statement, you can now execute cleaner and more type safe code, without error prone(容易出错) string literals and casting.
SqlSession session = sqlSessionFactory.openSession();
try {
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
} finally {
session.close();
}
Exploring Mapped SQL Statements
In either of the examples above, the statements could have been defined by either XML or Annotations. Let's take a look at XML first.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
Note: A note about namespaces
Namespaces were optional in previous versions of MyBatis, which was confusing and unhelpful. Namespaces are now required and have a purpose (1)beyond simply isolating(孤立) statements with longer, fully-qualified names.(2)Namespaces enable the interface bindings as you see here, and even if you don’t think you’ll use them today,
There's one more trick to Mapper classes like BlogMapper. Their mapped statements don't need to be mapped with XML at all. Instead they can use Java Annotations. For example,
public interface BlogMapper {
@Select("SELECT * FROM blog WHERE id = #{id}")
Blog selectBlog(int id);
}
However, Java Annotations are both limited and messier for more complicated statements. Therefore, if you have to do anything complicated, you're better off with XML mapped statements.
Scope and Lifecycle(生命周期)
It's very important to understand the various scopes and lifecycles classes we've discussed so far. Using them incorrectly can cause severe concurrency(并发) problems.
NOTE Object lifecycle and Dependency Injection Frameworks
Dependency Injection frameworks can create thread safe, transactional SqlSessions and mappers and inject them directly into your beans so you can just forget about their lifecycle. You may want to have a look at MyBatis-Spring or MyBatis-Guice sub-projects to know more about using MyBatis with DI frameworks.
SqlSessionFactoryBuilder
There is no need to keep it around once you've created your SqlSessionFactory. Therefore the best scope for instances of SqlSessionFactoryBuilder is method scope
SqlSessionFactory
Once created, the SqlSessionFactory should exist for the duration of your application execution. There should be little or no reason to ever dispose of it or recreate it.Therefore the best scope of SqlSessionFactory is application scope. This can be achieved a number of ways. The simplest is to use a Singleton pattern or Static Singleton pattern.
SQLSession
Each thread should have its own instance of SqlSession. Instances of SqlSession are not to be shared and are not thread safe. Therefore the best scope is request or method scope. Never keep references to a SqlSession instance in a static field or even an instance field of a class. Never keep references to a SqlSession in any sort of managed scope(托管作用域), such as HttpSession of the Servlet framework. If you're using a web framework of any sort, consider the SqlSession to follow a similar scope to that of an HTTP request.
SqlSession session = sqlSessionFactory.openSession();
try {
// do work
} finally {
session.close();
}
Mapper Instances
Mappers are interfaces that you create to bind to your mapped statements. Instances of the mapper interfaces are acquired from the SqlSession. As such, technically the broadest scope of any mapper instance is the same as the SqlSession from which they were requested.However, the best scope for mapper instances is method scope. While it's not a problem to keep them around throughout a request, similar to the SqlSession, you might find that managing too many resources at this level will quickly get out of hand.
When your javabean property name is different from the field in the table
- Use alias in SQL statement,such as
<select id = "selectById" parameterType = "Integer" returnType="User">
select 'user_id' as userID,'username','password' from 'User' where userID = #{id}
</select>
- use a
<ResultMap>
<resultMap type="Blog" id="BlogResultMap">
<id column="id" property="id" jdbcType="Interger">
<result column="author_id" property="authorID" jdbcType="INTEGER" />
</resultMap>
<select id = "selectById" parameterType = "Integer" resultMap="UserResultMap">
select * from 'Blog' where authorID = #{id}
</select>
Of course, if you use mybatis generator you won't meet this question QAQ.
Difference between $ and
Configuration properties
For example:
<properties resource="org/mybatis/example/config.properties">
<property name="username" value="dev_user"/>
<property name="password" value="F2Fa3!33TYyg"/>
</properties>
Then the properties can be used like next:
<dataSource type="POOLED">
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
String Substitution(替换)
By default, using the #{}
syntax will cause MyBatis to generate PreparedStatement
properties and set the values safely against the PreparedStatement
parameters (e.g. ?). While this is safer, faster and almost always preferred, sometimes you just want to directly inject an unmodified string into the SQL Statement. For example, for ORDER BY, you might use something like this:
ORDER BY ${columnName}
Here MyBatis won't modify or escape the string.（修改或转义字符串）
String Substitution can be very useful when the metadata(i.e. table name or column name) in the sql statement is dynamic, for example, if you want to select
from a table by any one of its columns, instead of writing code like:
@Select("select * from user where id = #{id}")
User findById(@Param("id") long id);
@Select("select * from user where name = #{name}")
User findByName(@Param("name") String name);
@Select("select * from user where email = #{email}")
User findByEmail(@Param("email") String email);
// and more "findByXxx" method
you can just write:
@Select("select * from user where ${column} = #{value}")
User findByColumn(@Param("column") String column, @Param("value") String value);
Note that if you do not specify param name with @Param annotation, and your param is a single type and only one params. You should write ${value} instead of ${parammeterName}. If the params in $ is a String, you should add ' ' between ${value}
<select id="select1" resultMap="BaseResultMap" parameterType="string">
select * from Student where username like #{name}
</select>
<select id="select2" resultMap="BaseResultMap" parameterType="string">
select * from Student where username like '%${value}%'
</select>
Or write as
List<Student> list = mapper.select2("'%root%'");
//if you use #
List<Student> list = mapper.select1("%root%");
Summary(总结)，# is placeholder(占位符) ?, $ is String concatenation(字符串拼接); If the params is a String should add ' '; When you use paras means column you should use $.
realize not case sensitive(大小写敏感)
just upper or lower the select condition, the follwing sql function are used in mysql
<select id="select2" resultMap="BaseResultMap" parameterType="string">
select * from Student where lower(username) like lower('%${value}%')
</select>
or
select * from user where username like binary('admin') and password like binary('admin');
Sometimes some database will not case sensitive by default, such as MySQL, you can check your database first.
## Order Chinese charactors
Use convert function to convert the coding into gbk.
In MySQL, you can use
CAST(expr AS type), CONVERT(expr,type) , CONVERT(expr USING transcoding_name).
select * from user order by CONVERT(username USING GBK);
Transmit multi parameters to mapper.xml
There are three way to realize it.
- use index
- use @Param annotation, the params value should as the same as spaceholder params in the mapper.xml
- use a map.The key in map should as the same as spaceholder params in the mapper.xml
<select id = "select1" reesultMap = "BaseMap">
select * from User limit #{1}, #{2}
</select>
<select id = "select2" reesultMap = "BaseMap">
select * from User limit #{offset}, #{pagesize}
</select>
<select id = "select3" reesultMap = "BaseMap">
select * from User limit #{offset}, #{pagesize}
</select>
// method2 in mapper file
List<User> select2(@Param(value="offset")offset,@Param(value="pagesize") pagesize);
//method3 in mapper file
List<User> select2(Map<String,object> map);
//method3 when use interface
HashMap<String,object> map = new HashMap<String,Object>();
map.put("offset",2);
map.put("pagesize",2);
Insert
As mentioned, insert is a little bit more rich in that it has a few extra attributes and sub-elements that allow it to deal with key generation in a number of ways.
First, if your database supports auto-generated key fields (e.g. MySQL and SQL Server), then you can simply set useGeneratedKeys="true"
and set the keyProperty
to the target property and you're done. For example, if the Author
table above had used an auto-generated column type for the id, the statement would be modified as follows:
<insert id="insertAuthor" useGeneratedKeys="true"
keyProperty="id">
insert into Author (username,password,email,bio)
values (#{username},#{password},#{email},#{bio})
</insert>
The useGeneratedKey can be setted in the mybatis config file too.
<settings>
<setting name = "useGeneratedKeys" value ="true"/>
</settings>
MyBatis has another way to deal with key generation for databases that don't support auto-generated column types, or perhaps don't yet support the JDBC driver support for auto-generated keys.
Note that the keyProperty is the name of bean property.
<insert id="insertAuthor">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
<!--select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1 -->
<!--the follwing sql is used in oracle -->
select seq.nextval as id from dual
</selectKey>
insert into Author
(id, username, password, email,bio, favourite_section)
values
(#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>
<insert id="insert1" >
<selectKey keyProperty="userId" resultType="java.lang.Integer" order="AFTER">
<!--the follwing sql is used in MySQL -->
select LAST_INSERT_ID()
</selectKey>
insert into Student (user_id,username,password,email) values (#{userId},#{username},#{password},#{email});
</insert>
| order | This can be set to BEFORE or AFTER . If set to BEFORE , then it will select the key first, set the keyProperty and then execute the insert statement. If set to AFTER , it runs the insert statement and then the selectKey statement – which is common with databases like Oracle that may have embedded sequence calls inside of insert statements. |
|---|---|
Update
You should remember that if your entity's property is not set value, it will be set NULL value by default.So there has two solution:
- Select for result first, and then alter the new value. But it will be excute two sql statement.
- Use Dynamic SQL. If the value is null, just don't update that column in your sql statement.
Some Question I have met
-
When I use Mybatis generator it throws a Exception, "The server time zone value '�й���ʱ��' is unrecognized or represents more than one time zone"
-
add
?serverTimezone=UTC
after your sql connect URL, such as
connectionURL="jdbc:mysql://localhost:3306/homework?serverTimezone=UTC"
- set your mysql's time zone(时区)
set global time_zone='+8:00'
refers to l.shane
-
When use generator could not generator correctly. It create a filed
currentConnections
that my table does not exists. The reason is that my table name called "users" or "user", just use another table name. -
When you write SQL statement in mapper.xml, you should write its column name but not property name.


About
Military
Elections
Community
Gallery
More
Welcome to France: Persistent History!
Welcome, Guest.


Validity
Thanks for installing Validity.
Validity has been updated to version<EMAIL_ADDRESS>FAQ
- How do I report a bug in Validity?
-
If you think you've found a bug in Validity, please raise an issue
on the project's GitHub page at
https://github.com/renyard/validity/issues.
- How to I request a new feature in Validity?
-
Please raise an issue on the project's
GitHub page.
- How can I support the development of Validity?
-
There are several ways that you can contribute to the continued
development of Validity:
-
If you like the extension, please leave a review on the Chrome
Web Store. If you've encountered any problems or would like to
make a feature request, please raise an issue on the project's
GitHub page.
-
Code contributions are also always welcome and appreciated
for bug fixes and new features.
For a bug fix, please raise a pull request.
Change Log


Your browser doesn't support the features required by impress.js, so you are presented with a simplified version of this presentation.
For the best experience please use the latest Chrome, Safari or Firefox browser.
Promises
Artūrs Mekšs
AMekss
@arturs_mekss
Who am I?
- I'm working as an application developer since 2003
- I'm building stuff in javascript since 2006
- I'm working at Tieto as a Ruby developer
- I'm still learning and discovering new things
My JavaScript open source foot print
jquery.quicktip.js - drop in replacement for default browser tool tips. Aims to be the simplest solutions for that. Doesn't do anything fancy but show nice tool tips.
My JavaScript open source foot print
namespace.js - your best friend for dealing with javascipt global variable space.
Let's make a javascript MVC application from scratch and see namespace.js in action ..
First we need some model and a view
Then we can use it in our controller
The same but for comments in coffee
Of course in production I usually use Backbone for MVC
But let's get back to our post MVC
Promises to rescue
What is Promises?
- In common usage, the terms Promise, Deferred, and Future are roughly synonymous.
- A Deferred/Promise object can be viewed as a three states state machine:
Brief history of Promises
- - The term was first used by C++ engineers on the Xanadu project
- - Promises were later used in the E programming language
- - E programming language inspired Python developers to implement them in the form of the Twisted framework’s Deferreds
Brief history of Promises in JavaScript
- - Promises hit the JavaScript mainstream in 2007 when the Dojo framework, taking a cue from Twisted, added an object called dojo.Deferred
- - In 2009, citing dojo.Deferred as an influence, Kris Zyp proposed the CommonJS Promises/A spec.
- - In January 2011 within version 1.5 it was introduced in jQuery by $.Deferred object
- - Other popular choices beside jQuery is Q.js and FuturesJS
Making promises with jQuery
- - jQuery 1.5+ ($.ajax, $.get, and $.post) return Promises
- - Up until jQuery 1.8 there were changes and new feature in the API so it's better to use jQuery 1.8+ for making promises
- - You can make your own promises via $.Deferred object
Why $.Deferred object?
Well
Deferred object is
Promise, or private representation of it. You can
resolve or
reject promise via it.
While promise is public object and can only accept callbacks or return its state (
pending/resolved/rejected).
Progress notifications
There are
private notify method and public
progress special type of callback witch can be triggered any number of times.
$.Deferred vs CommonJS Promises/A
Notable differences: jQuery uses the term resolve as the opposite of fail, whereas Promises/A uses fulfill. Under Promises/A, a Promise is said to be “resolved” when it’s either fulfilled or failed.
Q.js is straight forward CommonJS Promises/A implementation and provide convenient way to convert promises
Let's try promises in action ..

- - While with promises there is possible to build simple flow controls, but generally it's better to use flow control libs for that e.g. async.js
Books to read
Happy hacking! :)
Paldies! Thank you!


RT @windyoona: I just had to. http://oona.windytan.com/0x800/ 3/22/2014, 2:21:53 PM Favs: 0 Retweets: 0 link


health surveillance Health data disease case prefectural Boffa reporting Disease reported epidemic-prone centers cases weekly case-based department diseases []. Control Ministry October public national {border-style Guinean information provided Guinea px;} –March #ffffff;} Prevention staff center feedback Division Surveillance care training prefecture support time [cited reports assessment evaluation including level outbreak used (i.e., June World analysis community community-based routine EVD Medicine available period priority review telephone yellow Centers Data Global However, Prefectural quality response Boffa, Department Infectious Sciences activities counts diseases, hospital included interviewee measles, px; technical {font-family (e.g., International Organization. additional cholera did font-size immediate inform interviewees levels meningitis, meningococcal report rural study team zero (cholera, DHIS Diseases Guinea, control double; focus implementation indicated meningitis received results sensitivity system, use (Fig Director Ebola Health. Security aggregate assessed assessment, baseline border-color border-width cases, cases. centers, collab: collection definitions department. documentation identified interviews low management notebooks prefectures prepare provision regional registers requested solid; structure surveillance, verbal written {font-style {font-weight ;(): Africa Excel Guinea. Information Medical Microsoft Organization Public Therefore, U.S. administrative analysis, analysis. attributes based bold capacity central characteristics. complete conducted courier; distribution em; epidemiologic event-based field future geographic indicate level. methods observed occurred outbreaks partners period, peripheral policy presented provide provides pt;} register review. routinely seven summaries surveillance. system’s tools virus work −March


The Wonderful Sober Monitor Picker
May The Odds Be Ever In Your Favor
Syllabuzzed 8/26
Name
Status
Rush Week Toga 9/2
Name
Status
Halloween 10/29
Name
Status
Ugly Christmas 12/8
Name
Status


Writing Maintainable JavaScript
by Paul Istoan
Solutions PMG
Mintel
Responsibility to future programmers
Comfort can work against us in the long run
Well written prose
Design Patterns book
Modules
Modules help us organize our code
Modules help us avoid polluting the global namespace
.
├── css
│ └── style.css
├── index.html
└── js
├── app.js
├── collections
│ └── cart.js
├── lib
│ ├── backbone.js
│ ├── jquery.js
│ ├── require.js
│ └── underscore.js
├── models
│ └── item.js
└── views
├── cartcollectionview.js
├── itemcollectionview.js
└── itemview.js
[3]
RequireJS
define(["lib/backbone"], function(Backbone) {
function ItemView() {
// ...
});
return ItemView;
});
[4]
Helps with organizing our code into small modules with specific intent
Helps us avoid polluting the global namespace
define(["lib/backbone", "views/ItemView"]
function(Backbone, ItemView) {
function ItemCollectionView () {
// ...
});
return ItemCollectionView;
});
Design Patterns
One of the most influential books in the field of software engineering.
Presents 23 essential software design patterns that came out of recurring
solutions to common problems.
Changes the way you approach writing software.
3 Types of Patterns
Creational : help you build objects
Structural : help you compose objects
Behavioral : help you organize functionality
Sample App: Contacts
Add - Mediator Pattern
Search - Abstract Factory Pattern
Export - Adapter Pattern
Common Themes
Program to interfaces, not to implementations.
Favor composition over inheritance.
Abstract Factory “Provide an interface for creating families of related or dependent
objects without specifying their concrete classes.”
config.js
{
searchFields: [{
type: 'range',
name: 'Age'
}, {
type: 'phoneNumber',
name: 'Phone Number'
}, {
type: 'text',
name: 'First Name'
}, {
type: 'text',
name: 'Last Name'
}]
}
Creational Design Patterns
Abstract Factory
Builder
Factory Method
Prototype
Singleton
Adapter “Convert the interface of a class into another interface clients expect.
Adapter lets classes work together that couldn't otherwise because of incompatible
interfaces.”
Structural Design Patterns
Decorator
Facade
Flyweight
Proxy
Mediator “Define an object that encapsulates how a set of objects interact.

Behavioral Design Patterns
Chain of responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template method
Visitor
Conclusions
Program to interfaces, not to implementations.
Favor composition over inheritance.
Program to interfaces
Easy to swap out implementations, configurable
Maintainable
Favor composition
Inheritance is rigid
Composition allows finer grained control over what parts to implement
in what modules
Example to follow
Other Resources
Focus on writing maintainable code
The value of using patterns
Identifying when to apply a pattern
Identifying when not to apply a pattern
Not the kinds of book you read once and put away
Using frameworks to set patterns
Being a professional
Investing in design phase
Writing less code


there were many times during the kata exercises i ran into simple problems such as code errors or failing challenges in repl. this is really when the value of using console.log hit me, and i learnt i can use this javascript function to essentially see the inner workings behind the code and paint a clearer picture in my head of what everything was supposed to look like
confident, although this is a tricky one. i know how to write pseudocode and have found it quite useful but there are some occasions where i have no idea at all and psseudocode becomes useless on those occasions
confident, i like trying anything and everything i can think of
competent. while i admit this helps some people i do not find this technique useful
confident. I like raeding error messages they give a really good hint as to what is going wrong and on what line. and im starting to understand what specific errors actually mean
competent. i actually dont use this as much as i should.There are many times i could use this and i simply forget to use it. im working hard on making this a habbit because i have found its really useful and telling
confident. google has its uses and i can usually find the information im looking for
not entirely confident yet. i'm hesistant because i think i if i keep trying i can get the answer myself but sometimes its just more efficent and time saving to ask someone else.
competent. sometimes i feel like my questions might be a bit dumb so i have to get over that feeling.
not entirely confident yet. i've never really reflected on my work before, only more personal
aspects of myself so thinking about my work side is really new for me.


‘Thank you so much’ to ref was not sarcastic, says Guardiola after Anfield loss
Pep Guardiola insisted he was not being sarcastic when he shook the hand of the referee after Manchester City’s 3-1 defeat at Liverpool.
The City boss appeared to thank Michael Oliver for his performance in a theatrical way after the final whistle at Anfield.
Guardiola had been enraged during the Premier League clash as his side were twice denied penalties for possible handballs against Trent Alexander-Arnold.
The first was the most controversial, coming immediately before Fabinho opened the scoring. The second came late on as City rallied in response to further goals from Mohamed Salah and Sadio Mane.
It was not sarcastic. All the time I go to referees I say 'thank you so much'.
“It was not sarcastic,” Guardiola said. “I say, ‘Thank you so much’ all the time. I said the same at Tottenham game at home. All the time I go to referees I say thank you so much.”
City’s late rally did produce a reply from Bernardo Silva but Premier League leaders Liverpool did not surrender an advantage that saw them move nine points clear of the champions.
The result left City in fourth place, also behind Leicester and Chelsea, but Guardiola – becalmed by the time he held his post-match press conference – spoke of his pride at the performance.
The Spaniard said: “Today we showed in the most difficult stadium in the world the reasons we are champions, (it was) one of the proudest performances of my career.
“Unfortunately we lost, but congratulations to Jurgen (Klopp) and this fantastic team for the victory. It was a good game for both sides, for the Premier League, for the billions of people who watched this game it was good advertising.
“Maybe you have to buy Jurgen and myself a bottle of wine for that!
“We tried, but we can’t expect not to concede chances at Anfield.
“We created more than ever and I’m so proud to be manager of these players.”
Guardiola refused to be drawn when asked about the controversial refereeing decisions.
He said: “You’ll have to ask (referees chief) Mike Riley and the big bosses about that. I’m not here to talk about the decisions over the referees or VAR. Don’t ask me, ask them.”
Guardiola will not give up on a third successive title and hopes his players learn from the experience.
He said: “There are three teams in front of us who have more of a chance to win the Premier League but hopefully we can sustain this mentality and try.
“If in the end it’s not enough we’ll congratulate Liverpool, Leicester or Chelsea.
“How we react is the process we have to learn. I don’t have regrets.”
READ MORE
Liverpool stretch lead in title race with win over Manchester City


| Kosmos Virtual 3D Universe |
|
Reverse
Autopilot
Share
|
|
Copyright © 2013 John Judnich |
Kosmos allows you to explore a computer-generated 3D universe from your browser.
Click anywhere to navigate, and adjust speed with the big slider bar on the left.
Unfortunately, your web browser reports it does not support 3D graphics (no "WebGL").
Please upgrade to a modern browser to use Kosmos. Mozilla Firefox seems to work the best.
Some browsers and operating systems (particularly Microsoft Windows and Google Chrome) have serious compatibility issues with complex WebGL apps.
Currently only Firefox seems to work consistently across platforms. Even then, we were forced to disable features for Kosmos to function at all on Windows (specifically, not all planets in the Kosmos universe will be unique on Windows).
The URL below to links directly to what you see now. Simply copy and paste into your preferred networking/messaging app.


Hacker News Update
This tool will allow you to view all Hacker News posts since a prior time with some filter options.


--- layout: archive title: Zulip Chat Archive permalink: /stream/113489-new-members/topic/Error.20message.20in.20VS.20Code.html ---
In tactic mode if there is an error, it lists the current tactic state with n goals, and then the error, followed by the tactic state again. Is there a setting to make it show the error first? Currently I have to scroll down to see the error every time I change something.
Some might say that if you have to scroll down then you have too much in your tactic state :-)
{% endraw %}Last updated: Apr 24 2020 at 19:02 UTC


Feature ui.grid.validate allows validating cells after they are changed. To enable, you must include the
ui.grid.validate
module and you must include the ui-grid-validate
directive on your grid element.
This feature depends on ui.grid.edit.
Documentation for the validation feature is provided in the api documentation, in particular:
Validation is based on validation functions defined at service level (thus valid through all the application).
Some custom validators come with the feature and are:
required
: to ensure that a field is not empty.minLength
: to ensure that the value inserted is at least X characters long.maxLength
: to ensure that the value inserted is at most X characters long.To define a new validator you should use the setValidator method.
To add a validator to a column you just need to add a validators
property to its colDef
object, containing a property for each validator you want to add. The name of the property
will set the validator and the value of the property will be treated as an argument by the validator function.
When a field does not pass validation it gets a invalid
class so you can customize it via css.
The feature adds 2 templates to ui-grid:
cellTitleValidator
wich adds the error message to the title attribute of the cell.cellTooltipValidator
wich depends on ui-bootstrap to add a tooltip.In case you have an external service providing validators, you can add a function calling said service by setting an external validator factory function via setExternalFactoryFunction.
Please be advised that external validators should accept the same parameters (or at least an ordered subset) as
our validators do (newValue
, oldValue
, rowEntity
, colDef
);


I graduated from California State University, East Bay with a Bachelors of Science in Computer Science with an emphasis on Software Engineering in 2018. The emphasis on Software Engineering required that I take 3 extra classes. These classes were: Software Engineering 1, Software Engineering 2, and Software Testing.
Software Engineering 1 focused on working in a group of about 5 people creating a project from start to finish. We had to come up with our own idea. Pick any language that we wanted and then create the project. My group decided to use JavaFX to create a fulfillment system. You can learn more about it at Fulfillment System. We wrote up a document paper, specs paper, and UMLs for the project. The class followed the waterfall approach but we coded everything in the agile approach.
Software Engineering 2 focused on different design patterns. All of the assignments were done in Java. I learned factory, adaptor, iterator, compound, observer, command, and template patterns.
Software Testing focused on using Python to test different programs. I tested the schools web-site by using Selenium. I wrote unit test to test code that was given to me that had errors in it.


--- menu: - id: home url: / - id: archive url: /content/archive.html - id: talk url: /talk/index.html - id: resume url: /content/resume.html - id: about url: /content/about.html ---


Methods¶
Summary¶
method |
class parent |
truncated documentation |
|---|---|---|
BaseEstimator |
Removes any non pickable attribute. |
|
BaseLearningOnnx |
Overwrites getstate to get rid of InferenceSession. |
|
OrtDataLoader |
Removes any non pickable attribute. |
|
OrtGradientForwardBackwardOptimizer |
Removes any non pickable attribute. |
|
OrtGradientForwardBackward |
Removes any non pickable attribute. |
|
BaseEstimator |
||
BaseLearningOnnx |
||
OrtDataLoader |
||
OrtGradientOptimizer |
||
OrtGradientForwardBackwardOptimizer |
||
OrtGradientForwardBackward |
||
OrtGradientForwardBackwardFunction |
||
AbsoluteLearningLoss |
||
BaseLearningLoss |
||
ElasticLearningLoss |
||
NegLogLearningLoss |
||
SquareLearningLoss |
||
BaseLearningPenalty |
||
ElasticLearningPenalty |
||
NoLearningPenalty |
||
BaseLearningRate |
||
LearningRateSGD |
||
LearningRateSGDNesterov |
||
OrtDataLoader |
Returns the number of observations. |
|
BaseEstimator |
Usual. |
|
BaseLearningOnnx |
Usual |
|
OrtDataLoader |
usual |
|
OrtGradientForwardBackward |
usual |
|
BaseLearningOnnx |
||
BaseLearningRate |
||
|
LearningRateSGD |
|
|
LearningRateSGDNesterov |
|
BaseEstimator |
Restores any non pickable attribute. |
|
BaseLearningOnnx |
Overwrites getstate to get rid of InferenceSession. |
|
OrtDataLoader |
Restores any non pickable attribute. |
|
OrtGradientForwardBackwardOptimizer |
Restores any non pickable attribute. |
|
OrtGradientForwardBackward |
Restores any non pickable attribute. |
|
BaseLearningOnnx |
Binds C_OrtValue to the structure used by InferenceSession to run inference. |
|
OrtGradientOptimizer |
Binds C_OrtValue to the structure used by InferenceSession to run inference. |
|
BaseLearningOnnx |
Binds C_OrtValue to the structure used by InferenceSession to run inference. |
|
|
AbsoluteLearningLoss |
|
BaseLearningLoss |
||
|
ElasticLearningLoss |
|
|
NegLogLearningLoss |
|
|
SquareLearningLoss |
|
BaseLearningPenalty |
||
|
ElasticLearningPenalty |
|
|
NoLearningPenalty |
|
BaseLearningRate |
||
|
LearningRateSGD |
|
|
LearningRateSGDNesterov |
|
OrtGradientForwardBackward |
Creates forward and backward ONNX graph. The new class has the following attributes: |
|
OrtGradientOptimizer |
Creates an instance of TrainingSession. |
|
OrtGradientForwardBackwardOptimizer |
||
OrtGradientOptimizer |
||
OrtGradientForwardBackwardOptimizer |
||
OrtGradientForwardBackwardOptimizer |
||
BaseEstimator |
Returns the trained onnx graph, the initial graph modified by replacing the initializers with the trained … |
|
OrtGradientForwardBackward |
||
OrtGradientOptimizer |
||
OrtGradientForwardBackwardOptimizer |
||
OrtDataLoader |
||
OrtGradientForwardBackwardFunction |
Implements backward function. The function returns an OrtValueVector. |
|
BaseLearningOnnx |
This class updates the weights. It assumes it can do operator on OrtValue. This can be done through ONNX … |
|
OrtGradientForwardBackwardOptimizer |
Creates ONNX graph and InferenceSession related to any operations applying on OrtValue. |
|
AbsoluteLearningLoss |
||
ElasticLearningLoss |
||
NegLogLearningLoss |
||
SquareLearningLoss |
||
ElasticLearningPenalty |
||
NoLearningPenalty |
||
LearningRateSGD |
||
LearningRateSGDNesterov |
||
|
AbsoluteLearningLoss |
Assuming the loss function was created. This one takes the onnx graph and generate the onnx graph for the … |
BaseLearningLoss |
Assuming the loss function was created. This one takes the onnx graph and generate the onnx graph for the … |
|
|
ElasticLearningLoss |
Assuming the loss function was created. This one takes the onnx graph and generate the onnx graph for the … |
|
NegLogLearningLoss |
Assuming the loss function was created. This one takes the onnx graph and generate the onnx graph for the … |
|
SquareLearningLoss |
Assuming the loss function was created. This one takes the onnx graph and generate the onnx graph for the … |
BaseLearningOnnx |
Clears binding and empty cache. |
|
OrtGradientOptimizer |
Trains the model. |
|
OrtGradientForwardBackwardOptimizer |
Trains the model. |
|
OrtGradientForwardBackwardFunction |
Implements forward function. |
|
OrtGradientForwardBackwardOptimizer |
Returns the trained weights and the inputs. |
|
OrtGradientForwardBackward |
Returns an initializer as numpy arrays. |
|
BaseEstimator |
Returns the list of parameters. Parameter deep is unused. |
|
OrtGradientOptimizer |
Returns the trained weights. |
|
OrtGradientForwardBackwardOptimizer |
Returns the trained weights. |
|
BaseEstimator |
Returns the trained onnx graph, the initial graph modified by replacing the initializers with the trained … |
|
OrtGradientOptimizer |
Returns the trained onnx graph, the initial graph modified by replacing the initializers with the trained … |
|
OrtGradientForwardBackwardOptimizer |
Returns the trained onnx graph, the initial graph modified by replacing the initializers with the trained … |
|
BaseLearningRate |
Initializes the learning rate at the beginning of the training. |
|
LearningRateSGD |
Updates the learning rate at the end of an iteration. |
|
LearningRateSGDNesterov |
Updates the learning rate at the end of an iteration. |
|
OrtDataLoader |
Iterates over the datasets by drawing batch_size consecutive observations. Modifies a bind structure. |
|
OrtDataLoader |
Iterates over the datasets by drawing batch_size consecutive observations. This iterator is slow as it … |
|
OrtDataLoader |
Iterates over the datasets by drawing batch_size consecutive observations. This iterator is slow as it … |
|
BaseLearningRate |
Loops over learning rate values, n to be precise. |
|
|
LearningRateSGD |
Loops over learning rate values, n to be precise. |
|
LearningRateSGDNesterov |
Loops over learning rate values, n to be precise. |
|
AbsoluteLearningLoss |
Returns the loss and the gradient as OrtValue. |
BaseLearningLoss |
Returns the loss and the gradient as OrtValue. |
|
|
ElasticLearningLoss |
Returns the loss and the gradient as OrtValue. |
|
NegLogLearningLoss |
Returns the loss and the gradient as OrtValue. |
|
SquareLearningLoss |
Returns the loss and the gradient as OrtValue. |
|
AbsoluteLearningLoss |
Returns the weighted loss (or score) for every observation as OrtValue. |
BaseLearningLoss |
Returns the weighted loss (or score) for every observation as OrtValue. |
|
|
ElasticLearningLoss |
Returns the weighted loss (or score) for every observation as OrtValue. |
|
NegLogLearningLoss |
Returns the weighted loss (or score) for every observation as OrtValue. |
|
SquareLearningLoss |
Returns the weighted loss (or score) for every observation as OrtValue. |
OrtGradientForwardBackwardOptimizer |
Returns the losses associated to every observation. |
|
OrtGradientForwardBackward |
Creates an instance of class self.cls_type_. It implements methods forward and backward. |
|
BaseLearningPenalty |
Returns the received loss. Updates the loss inplace. |
|
ElasticLearningPenalty |
Computes the penalty associated to every weights and adds them up to the loss. |
|
NoLearningPenalty |
Returns the received loss. Updates the loss inplace. |
|
OrtGradientForwardBackwardFunction |
Saves inputs furing forward steps. The list inputs is copied (simple copy, no deep copy). |
|
BaseOnnxClass |
Saves all ONNX files stored in this class. |
|
OrtGradientForwardBackwardOptimizer |
Return the whole score associated. |
|
BaseEstimator |
Returns the list of parameters. Parameter deep is unused. |
|
OrtGradientOptimizer |
Changes the trained weights. |
|
OrtGradientForwardBackwardOptimizer |
Changes the trained weights. |
|
BaseLearningRate |
Updates the learning rate at the end of an iteration. |
|
LearningRateSGD |
Updates the learning rate at the end of an iteration. |
|
LearningRateSGDNesterov |
Updates the learning rate at the end of an iteration. |
|
BaseLearningPenalty |
Returns the received loss. Updates the weight inplace. |
|
ElasticLearningPenalty |
||
NoLearningPenalty |
Returns the received loss. Updates the weight inplace. |
|
BaseLearningRate |
Updates weights based on the algorithm this class is setting up. |
|
LearningRateSGD |
||
LearningRateSGDNesterov |


Python Basic Syntax
The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.
First Python Program
Let us execute programs in different modes of programming.
Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings up the following prompt −
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Type the following text at the Python prompt and press the Enter −
>>> print "Hello, Python!"
If you are running new version of Python, then you would need to use print statement with parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this produces the following result −
Hello, Python!
Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.
Let us write a simple Python program in a script. Python files have extension .py. Type the following source code in a test.py file −
print "Hello, Python!"
We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows −
$ python test.py
This produces the following result −
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py file −
#!/usr/bin/python
print "Hello, Python!"
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows −
$ chmod +x test.py # This is to make file executable
$./test.py
This produces the following result −
Hello, Python!
Python Loops
In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a loop statement −
Python programming language provides following types of loops to handle looping requirements.
| Sr.No. | Loop Type & Description |
|---|---|
| 1 | while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body. |
| 2 | for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. |
| 3 | nested loops
You can use one or more loop inside any another while, for or do..while loop. |
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements. Click the following links to check their detail.
Let us go through the loop control statements briefly
| Sr.No. | Control Statement & Description |
|---|---|
| 1 | break statement
Terminates the loop statement and transfers execution to the statement immediately following the loop. |
| 2 | continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. |
| 3 | pass statement
The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. |
Python Numbers
Number data types store numeric values. They are immutable data types, means that changing the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b
Python supports four different numerical types −
int (signed integers) − They are often called just integers or ints, are positive or negative whole numbers with no decimal point.
long (long integers ) − Also called longs, they are integers of unlimited size, written like integers and followed by an uppercase or lowercase L.
float (floating point real values) − Also called floats, they represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming.
Examples
Here are some examples of numbers
| int | long | float | complex |
|---|---|---|---|
| 10 | 51924361L | 0.0 | 3.14j |
| 100 | -0x19323L | 15.20 | 45.j |
| -786 | 0122L | -21.9 | 9.322e-36j |
| 080 | 0xDEFABCECBDAECBFBAEL | 32.3+e18 | .876j |
| -0490 |<PHONE_NUMBER>43L | -90. | -.6545+0J |
| -0x260 | -052318172735L | -32.54e100 | 3e+26J |
| 0x69 | -4721885298529L | 70.2-E12 | 4.53e-7j |
Python allows you to use a lowercase L with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.
A complex number consists of an ordered pair of real floating point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number.
Number Type Conversion
Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.
Type int(x) to convert x to a plain integer.
Type long(x) to convert x to a long integer.
Type float(x) to convert x to a floating-point number.
Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions
Mathematical Functions
Python includes following functions that perform mathematical calculations.
| Sr.No. | Function & Returns ( description ) |
|---|---|
| 1 | abs(x)
The absolute value of x: the (positive) distance between x and zero. |
| 2 | ceil(x)
The ceiling of x: the smallest integer not less than x |
| 3 | cmp(x, y)
-1 if x < y, 0 if x == y, or 1 if x > y |
| 4 | exp(x)
The exponential of x: ex |
| 5 | fabs(x)
The absolute value of x. |
| 6 | floor(x)
The floor of x: the largest integer not greater than x |
| 7 | log(x)
The natural logarithm of x, for x> 0 |
| 8 | log10(x)
The base-10 logarithm of x for x> 0. |
| 9 | max(x1, x2,...)
The largest of its arguments: the value closest to positive infinity |
| 10 | min(x1, x2,...)
The smallest of its arguments: the value closest to negative infinity |
| 11 | modf(x)
The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float. |
| 12 | pow(x, y)
The value of x**y. |
| 13 | round(x [,n])
x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0. |
| 14 | sqrt(x)
The square root of x for x > 0 |
Random Number Functions
Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions that are commonly used.
| Sr.No. | Function & Description |
|---|---|
| 1 | choice(seq)
A random item from a list, tuple, or string. |
| 2 | randrange ([start,] stop [,step])
A randomly selected element from range(start, stop, step) |
| 3 | random()
A random float r, such that 0 is less than or equal to r and r is less than 1 |
| 4 | seed([x])
Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None. |
| 5 | shuffle(lst)
Randomizes the items of a list in place. Returns None. |
| 6 | uniform(x, y)
A random float r, such that x is less than or equal to r and r is less than y |
Trigonometric Functions
Python includes following functions that perform trigonometric calculations.
| Sr.No. | Function & Description |
|---|---|
| 1 | acos(x)
Return the arc cosine of x, in radians. |
| 2 | asin(x)
Return the arc sine of x, in radians. |
| 3 | atan(x)
Return the arc tangent of x, in radians. |
| 4 | atan2(y, x)
Return atan(y / x), in radians. |
| 5 | cos(x)
Return the cosine of x radians. |
| 6 | hypot(x, y)
Return the Euclidean norm, sqrt(x*x + y*y). |
| 7 | sin(x)
Return the sine of x radians. |
| 8 | tan(x)
Return the tangent of x radians. |
| 9 | degrees(x)
Converts angle x from radians to degrees. |
| 10 | radians(x)
Converts angle x from degrees to radians. |
Mathematical Constants
The module also defines two mathematical constants −
| Sr.No. | Constants & Description |
|---|---|
| 1 | pi The mathematical constant pi. |
| 2 | e The mathematical constant e. |
Python Strings
Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"
Accessing Values in Strings
Python does not support a character type; these are treated as strings of length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −
#!/usr/bin/python
var1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
When the above code is executed, it produces the following result −
var1[0]: H
var2[1:5]: ytho
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example −
#!/usr/bin/python
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'
When the above code is executed, it produces the following result −
Updated String :- Hello Python
Escape Characters
Following table is a list of escape or non-printable characters that can be represented with backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
| Backslash notation | Hexadecimal character | Description |
|---|---|---|
| \a | 0x07 | Bell or alert |
| \b | 0x08 | Backspace |
| \cx | Control-x | |
| \C-x | Control-x | |
| \e | 0x1b | Escape |
| \f | 0x0c | Formfeed |
| \M-\C-x | Meta-Control-x | |
| \n | 0x0a | Newline |
| \nnn | Octal notation, where n is in the range 0.7 | |
| \r | 0x0d | Carriage return |
| \s | 0x20 | Space |
| \t | 0x09 | Tab |
| \v | 0x0b | Vertical tab |
| \x | Character x | |
| \xnn | Hexadecimal notation, where n is in the range 0.9, a.f, or A.F |
String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
| Operator | Description | Example |
|---|---|---|
| + | Concatenation - Adds values on either side of the operator | a + b will give HelloPython |
| * | Repetition - Creates new strings, concatenating multiple copies of the same string | a*2 will give -HelloHello |
| [] | Slice - Gives the character from the given index | a[1] will give e |
| [ : ] | Range Slice - Gives the characters from the given range | a[1:4] will give ell |
| in | Membership - Returns true if a character exists in the given string | H in a will give 1 |
| not in | Membership - Returns true if a character does not exist in the given string | M not in a will give 1 |
| r/R | Raw String - Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter "r," which precedes the quotation marks. The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark. | print r'\n' prints \n and print R'\n'prints \n |
| % | Format - Performs String formatting | See at next section |
String Formatting Operator
One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family. Following is a simple example −
#!/usr/bin/python
print "My name is %s and weight is %d kg!" % ('Zara', 21)
When the above code is executed, it produces the following result −
My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can be used along with % −
| Format Symbol | Conversion |
|---|---|
| %c | character |
| %s | string conversion via str() prior to formatting |
| %i | signed decimal integer |
| %d | signed decimal integer |
| %u | unsigned decimal integer |
| %o | octal integer |
| %x | hexadecimal integer (lowercase letters) |
| %X | hexadecimal integer (UPPERcase letters) |
| %e | exponential notation (with lowercase 'e') |
| %E | exponential notation (with UPPERcase 'E') |
| %f | floating point real number |
| %g | the shorter of %f and %e |
| %G | the shorter of %f and %E |
Other supported symbols and functionality are listed in the following table −
| Symbol | Functionality |
|---|---|
| * | argument specifies width or precision |
| - | left justification |
| + | display the sign |
| <sp> | leave a blank space before a positive number |
| # | add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used. |
| 0 | pad from left with zeros (instead of spaces) |
| % | '%%' leaves you with a single literal '%' |
| (var) | mapping variable (dictionary arguments) |
| m.n. | m is the minimum total width and n is the number of digits to display after the decimal point (if appl.) |
Triple Quotes
Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double quotes.
#!/usr/bin/python
para_str = """this is a long string that is made up of
several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [ \n ], or just a NEWLINE within
the variable assignment will also show up.
"""
print para_str
When the above code is executed, it produces the following result. Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the "up." and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\n) −
this is a long string that is made up of
several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.
Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it −
#!/usr/bin/python
print 'C:\\nowhere'
When the above code is executed, it produces the following result −
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression' as follows −
#!/usr/bin/python
print r'C:\\nowhere'
When the above code is executed, it produces the following result −
C:\\nowhere
Unicode String
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit Unicode. This allows for a more varied set of characters, including special characters from most languages in the world. I'll restrict my treatment of Unicode strings to the following −
#!/usr/bin/python
print u'Hello, world!'
When the above code is executed, it produces the following result −
Hello, world!
As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.
Built-in String Methods
Python includes the following built-in methods to manipulate strings −
| Sr.No. | Methods with Description |
|---|---|
| 1 | capitalize()
Capitalizes first letter of string |
| 2 | center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width columns. |
| 3 | count(str, beg= 0,end=len(string))
Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given. |
| 4 | decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. |
| 5 | encode(encoding='UTF-8',errors='strict')
Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'. |
| 6 | endswith(suffix, beg=0, end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise. |
| 7 | expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided. |
| 8 | find(str, beg=0 end=len(string))
Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise. |
| 9 | index(str, beg=0, end=len(string))
Same as find(), but raises an exception if str not found. |
| 10 | isalnum()
Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise. |
| 11 | isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false otherwise. |
| 12 | isdigit()
Returns true if string contains only digits and false otherwise. |
| 13 | islower()
Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise. |
| 14 | isnumeric()
Returns true if a unicode string contains only numeric characters and false otherwise. |
| 15 | isspace()
Returns true if string contains only whitespace characters and false otherwise. |
| 16 | istitle()
Returns true if string is properly "titlecased" and false otherwise. |
| 17 | isupper()
Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise. |
| 18 | join(seq)
Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string. |
| 19 | len(string)
Returns the length of the string |
| 20 | ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of width columns. |
| 21 | lower()
Converts all uppercase letters in string to lowercase. |
| 22 | lstrip()
Removes all leading whitespace in string. |
| 23 | maketrans()
Returns a translation table to be used in translate function. |
| 24 | max(str)
Returns the max alphabetical character from the string str. |
| 25 | min(str)
Returns the min alphabetical character from the string str. |
| 26 | replace(old, new [, max])
Replaces all occurrences of old in string with new or at most max occurrences if max given. |
| 27 | rfind(str, beg=0,end=len(string))
Same as find(), but search backwards in string. |
| 28 | rindex( str, beg=0, end=len(string))
Same as index(), but search backwards in string. |
| 29 | rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of width columns. |
| 30 | rstrip()
Removes all trailing whitespace of string. |
| 31 | split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given. |
| 32 | splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed. |
| 33 | startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise. |
| 34 | strip([chars])
Performs both lstrip() and rstrip() on string. |
| 35 | swapcase()
Inverts case for all letters in string. |
| 36 | title()
Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase. |
| 37 | translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the del string. |
| 38 | upper()
Converts lowercase letters in string to uppercase. |
| 39 | zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero). |
| 40 | isdecimal()
Returns true if a unicode string contains only decimal characters and false otherwise. |
Python Functions
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a function in Python.
Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.
Example
The following function takes a string as input parameter and prints it on standard screen.
def printme( str ):
"This prints a passed string into this function"
print str
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function −
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
When the above code is executed, it produces the following result −
I'm first call to user defined function!
Again second call to the same function
Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example −
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
hangeme( mylist );
print "Values outside the function: ", mylist
The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Function Arguments
You can call a function by using the following types of formal arguments −
- Required arguments
- Keyword arguments
- Default arguments
- Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows −
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme()
When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways −
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme( str = "My string")
When the above code is executed, it produces the following result −
My string
The following example gives more clear picture. Note that the order of parameters does not matter.
#!/usr/bin/python
# Function definition is here
def printinfo( name, age )
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed −
#!/usr/bin/python
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Name: miki
Age 35
Variable-length arguments
You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example −
#!/usr/bin/python
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −
Output is:
10
Output is:
70
60
50
The Anonymous Functions
These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an expression
Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
#!/usr/bin/python
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result −
Value of total : 30
Value of total : 40
The return Statement
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
All the above examples are not returning any value. You can return a value from a function as follows −
#!/usr/bin/python
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;
# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total
When the above code is executed, it produces the following result −
Inside the function : 30
Outside the function : 30
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python −
- Global variables
- Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example −
#!/usr/bin/python
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
When the above code is executed, it produces the following result −
Inside the function local total : 30
Outside the function global total : 0


ISBN Search
ISBN-13:<PHONE_NUMBER>143
ISBN-10:<PHONE_NUMBER>
Author: David Chisnall
Edition: 1
Binding: Paperback
Publisher: Addison-Wesley Professional
Published: May 2012
List Price: $34.99
$17.99
+3.99 shipping
Ready to ship
Notes
$23.91
$24.86
$25.63
+3.50 shipping
Ships 2-3 days
$26.55
+4.96 shipping
Ships 3+ Days
$29.14
+3.97 shipping
$29.74
$31.11
$35.16
+3.95 shipping
$33.99
+5.99 shipping
$13.00
$17.95
+4.49 shipping
$22.22
$26.52
$49.65
Free shipping
$49.19
$24.99


You can go further.
{{end}}{{if eq .Lang "zh-CN"}} No starting costs, no monthly fees, no kidding. Our cut is a low fixed percentage of incoming revenues. {{else}} No starting costs, no monthly fees, no kidding. Our cut is a low fixed percentage of incoming revenues. {{end}}
{{if eq .Lang "zh-CN"}} With Pivotshare, your video streams instantaneously to the desktop, iOS, and Android using bleeding-edge tech to reduce buffering and maximize speed. {{else}} With Pivotshare, your video streams instantaneously to the desktop, iOS, and Android using bleeding-edge tech to reduce buffering and maximize speed. {{end}}
{{if eq .Lang "zh-CN"}} Infrastructure, support, and payments are our job. All you need to do is add your content, choose your prices, and spread the word. {{else}} Infrastructure, support, and payments are our job. All you need to do is add your content, choose your prices, and spread the word. {{end}}


[gecode-users] Gecode/J: Propagation
Mikael Zayenz Lagerkvist
zayenz at gmail.com
Mon Nov 5 04:56:53 CET 2007
On 11/5/07, Malcolm Ryan <malcolmr at cse.unsw.edu.au> wrote:
> When does propagation occur? Does it happen as constraints are
> created, only only when it is specifically requested? If it's the
> latter (and I hope it is) then how do I request it (in Gecode/J)?
Propagation is delayed.
See method status():
http://www.gecode.org/gecodej/doc/group__TaskSearch.html#g915af1a9b39dc9886e46e0a4981d288f
Cheers,
Mikael
--
Mikael Zayenz Lagerkvist, http://www.ict.kth.se/~zayenz/
More information about the gecode-users
mailing list


Add Doctor To Hospital
Doctor ID
First Name
Last Name
Gender :
Male
Female
Other
Date of Birth
Contact
E-mail
Address
Submit


To view this page ensure that Adobe Flash Player version 11.8.0 or greater is installed.
July. 2013
Connect Gamepad and choose dropbox
« Back


ModuleRef
public struct ModuleRef : ModuleProtocol
The ModuleRef
type acts as a lightweight Swift reference to an underlying GModule
instance.
It exposes methods that can operate on this data type through ModuleProtocol
conformance.
Use ModuleRef
only as an unowned
reference to an existing GModule
instance.
The GModule
struct is an opaque data structure to represent a
dynamically-loaded module.
It should only be accessed via the following functions.
-
Untyped pointer to the underlying
GModule
instance. For type-safe access, use the generated, typed pointer_ptr
property instead.Declaration
Swift
public let ptr: UnsafeMutableRawPointer
-
Designated initialiser from the underlying
C
data typeDeclaration
Swift
init(_ p: UnsafeMutablePointer<GModule>)
-
Reference intialiser for a related type that implements
ModuleProtocol
Declaration
Swift
init<T>(_ other: T) where T : ModuleProtocol
-
Unsafe typed initialiser. Do not use unless you know the underlying data type the pointer points to conforms to
ModuleProtocol
.Declaration
Swift
init<T>(cPointer: UnsafeMutablePointer<T>)
-
Unsafe typed initialiser. Do not use unless you know the underlying data type the pointer points to conforms to
ModuleProtocol
.Declaration
Swift
init<T>(constPointer: UnsafePointer<T>)
-
Unsafe untyped initialiser. Do not use unless you know the underlying data type the pointer points to conforms to
ModuleProtocol
.Declaration
Swift
init(raw: UnsafeRawPointer)
-
Unsafe untyped initialiser. Do not use unless you know the underlying data type the pointer points to conforms to
ModuleProtocol
.Declaration
Swift
init(raw: UnsafeMutableRawPointer)
-
Unsafe untyped initialiser. Do not use unless you know the underlying data type the pointer points to conforms to
ModuleProtocol
.Declaration
Swift
init(opaquePointer: OpaquePointer)
-
Opens a module. If the module has already been opened,
its reference count is incremented.
First of all
g_module_open()
tries to openfile_name
as a module. If that fails andfile_name
has the “.la”-suffix (and is a libtool archive) it tries to open the corresponding module. If that fails and it doesn’t have the proper module suffix for the platform (G_MODULE_SUFFIX
), this suffix will be appended and the corresponding module will be opened. If that fails andfile_name
doesn’t have the “.la”-suffix, this suffix is appended andg_module_open()
tries to open the corresponding module. If eventually that fails as well,nil
is returned.Declaration
Swift
static func open(fileName file_name: UnsafePointer<gchar>, flags: ModuleFlags) -> ModuleRef!


Use this section to configure which of the Security Schemes are needed in order to invoke operations in the API. You can add multiple security requirements, resulting in consumers being allowed to provided any one of them. Each security requirement consists of one or more Security Scheme and (in the case of certain security types like OAuth) a list of the scopes the consumer must have.
Note: security requirements can also be declared at the Operation level, which will override the settings configured here.
Use this section to configure which of the Security Schemes are needed in order to invoke this specific operation. You can add multiple security requirements, resulting in consumers being allowed to provided any one of them. Each security requirement consists of one or more Security Scheme and (in the case of certain security types like OAuth) a list of the scopes the consumer must have.
Note: setting a Security Requirement for this operation will only apply to this operation and will override any security requirements configured globally.


About Us
Our Story
Hawa Kader Gaye Dia, our founder and executive director, was first made aware of the significant plight of talibé children in 2010 when her family was on their first pilgrimage to Mecca. Her family’s guide was Ibrahim Cisse’s son who was a student at the time. Several years later in 2015 a news headline caught Hawa’s eye that called her to action: “Big Fire Where Talibés Sleep”. Nine children, ages 6-10, had lost their lives that day.
Hawa knew immediately that she could not stand by and watch another Senegalese child be hurt. She was called to act upon what she has always believed is her life’s mission: to reach out and make a real difference in the lives of these poor children. She strives to give the talibé children a healthy start to life, giving them the opportunity to learn, and protecting them from harm.
Our Team
HAWA KADER GAYE DIA: FOUNDER AND EXECUTIVE DIRECTOR
Hawa grew up in Senegal, West Africa, and moved to the USA in 1991 where she attended the University of the District of Columbia and earned her Bachelor’s Degree in Business Management. Hawa also completed advanced degree work in Education, Psychology and School Directorship. Her decades of experience as a teacher sparked a powerful and passionate vision to provide a better life for less fortunate children in Senegal, especially those born with Sickle Cell Anemia. She founded Mathurin Children’s Foundation to educate the world about the challenges these children face and to provide resources that can make a profound difference in their lives. The foundation is named for Hawa’s beloved cousin Mathurin who died of Sickle Cell Anemia at the age of five.
SHIVANI CANCIENNE: DIRECTOR OF OPERATIONS AND DEVELOPMENT
Shivani was born and raised in Northern California and she earned her bachelor’s degree in Education at Chaminade University in Honolulu. Her joy and love for teaching children has spanned over forty years and is still going strong. A skilled administrator, Shivani served as human resources manager for an international nonprofit. Shivani is also trained in mediation and conflict resolution with an emphasis on mindfulness. She dreamed of one day being part of an organization that helps children in need in Africa. After meeting Hawa and learning about her mission and foundation she now has the opportunity to see her dream come true.
HYEJIN LEE – SECRETARY
Hyejin moved to the USA from Seoul, South Korea in 1994 and earned her bachelor’s degree in Education at the University of the Nations in Kona, HI. Her decades of teaching experience and her love for children drive her passion for charitable work. Hyejin is committed to make the world a better place by helping disadvantaged children improve their lives. She is currently Director of Growing Light Montessori School in Oakland, California. She is very grateful for the opportunity to work with wonderful colleagues who share a common vision of health, education and opportunity for the children of Senegal.
REBECCA SCALF – BOARD MEMBER
Rebecca is the daughter and granddaughter of teachers. After graduating with a BA in Film Studies, she joined the family trade, teaching children ages 4 through 12 since 1994. She has volunteered as an Exhibit Guide at Chabot Space and Science Center, and currently directs a volunteer-run summer day camp for the Community Camps of the Girl Scouts of Northern California and serves as Program Support Manager with the Girl Scouts of Oakland. For Rebecca, crafting is the best way to relax and creatively unwind; to help others enjoy their creativity she has taught classes in knitting, crochet and the batik art of decorating Ukrainian eggs. She lives in Oakland with her husband and two cats.


Bio
Gregor Johann Mendel (20 July 1822 – 6 January 1884) was a scientist, Augustinian friar and abbot of St. Thomas' Abbey in Brno, Margraviate of Moravia. Mendel was born in a German-speaking family in the Silesian part of the Austrian Empire (today's Czech Republic) and gained posthumous recognition as the founder of the modern science of genetics. Though farmers had known for millennia that crossbreeding of animals and plants could favor certain desirable traits, Mendel's pea plant experiments conducted between 1856 and 1863 established many of the rules of heredity, now referred to as the laws of Mendelian inheritance.
Mendel worked with seven characteristics of pea plants: plant height, pod shape and color, seed shape and color, and flower position and color. Taking seed color as an example, Mendel showed that when a true-breeding yellow pea and a true-breeding green pea were cross-bred their offspring always produced yellow seeds. However, in the next generation, the green peas reappeared at a ratio of 1 green to 3 yellow. To explain this phenomenon, Mendel coined the terms “recessive” and “dominant” in reference to certain traits. (In the preceding example, the green trait, which seems to have vanished in the first filial generation, is recessive and the yellow is dominant.) He published his work in 1866, demonstrating the actions of invisible “factors”—now called genes—in predictably determining the traits of an organism.
The profound significance of Mendel's work was not recognized until the turn of the 20th century (more than three decades later) with the rediscovery of his laws. Erich von Tschermak, Hugo de Vries, Carl Correns, and William Jasper Spillman independently verified several of Mendel's experimental findings, ushering in the modern age of genetics.
Life and Career
Mendel was born into a German-speaking family in Hynčice (Heinzendorf bei Odrau in German), at the Moravian-Silesian border, Austrian Empire (now a part of the Czech Republic). He was the son of Anton and Rosine (Schwirtlich) Mendel, and had one older sister, Veronika, and one younger, Theresia. They lived and worked on a farm which had been owned by the Mendel family for at least 130 years. During his childhood, Mendel worked as a gardener and studied beekeeping. Later, as a young man, he attended gymnasium in Opava (called Troppau in German). He had to take four months off during his gymnasium studies due to illness. From 1840 to 1843, he studied practical and theoretical philosophy and physics at the Philosophical Institute of the University of Olomouc, taking another year off because of illness. He also struggled financially to pay for his studies, and Theresia gave him her dowry. Later he helped support her three sons, two of whom became doctors.
He became a friar in part because it enabled him to obtain an education without having to pay for it himself. As the son of a struggling farmer, the monastic life, in his words, spared him the "perpetual anxiety about a means of livelihood." He was given the name Gregor when he joined the Augustinian friars.
Experiments on Plant Hybridization
After initial experiments with pea plants, Mendel settled on studying seven traits that seemed to be inherited independently of other traits:
- Seed shape
- Seed coat tint
- Flower color
- Pod shape
- Unripe pod color
- Flower location
- Plant height
He first focused on seed shape, which was either angular or round. Between 1856 and 1863 Mendel cultivated and tested some 28,000 plants, the majority of which were pea plants (Pisum sativum). This study showed that, when true-breeding different varieties were crossed to each other (e.g., tall plants fertilized by short plants), one in four pea plants had purebred recessive traits, two out of four were hybrids, and one out of four were purebred dominant. His experiments led him to make two generalizations, the Law of Segregation and the Law of Independent Assortment, which later came to be known as Mendel's Laws of Inheritance.