text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91
values | source stringclasses 1
value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
04 June 2012 10:36 [Source: ICIS news]
SINAGPORE (ICIS)--?xml:namespace>
“The inventories are up to 30 days and it is too high, so we have to shut down to reduce our inventories,” the company source said.
The main product of the line is pre-oriented yarn (POY) whose prices have been soft for the past several months incurring losses to the company, the source said but did not give any other details.
The company has to shut down the plant also because of the restrictions on electricity by the government during high demand summer season, the source added.
The plant is operating at full capacity and the company plans to run it 100% after completing maintenance turnaround, | http://www.icis.com/Articles/2012/06/04/9566521/chinas-lianda-chemical-fiber-plans-polyester-line-shutdown-in.html | CC-MAIN-2015-06 | refinedweb | 119 | 56.59 |
Problems with @Inject annotationRene Lenno Nov 17, 2011 5:13 AM
Hi,
I'm trying to use Errai in my GWT project. I'm a total newbie, so my question may be trivial but I really can't figure it out:
I have a GWT Project that is designed according to the MVP GWT example:
I'm trying to replace the server-client communication bei Errai. The problem I have is that the Incetion only seems to work. On the @EntryPoint:
@EntryPoint
public class App {
@Inject
private Event<UserCustomRequest> userCustomRequest;
@PostConstruct
public void onModuleLoad() {
new AppController(this).go(RootPanel.get());
}
public void response(@Observes UserCustomResponse event) {
Window.alert("response");
}
[...]
}
This works fine, but if i try to use the @Inject annotation for my requests or responeses in other classes than the @EntryPoint, the injection seems to fail (in this case, userCustomRequest is null). Also the response method isn't called in any other class than the @EntryPoint class:
public class AnyPresenter implements Presenter {
@Inject
private Event<UserCustomRequest> userCustomRequest;
public void response(@Observes UserCustomResponse event) {
Window.alert("response");
}
[...]
}
Thanks for the help!
1. Re: Problems with @Inject annotationDominik Obermaier Nov 17, 2011 6:43 AM (in response to Rene Lenno)
Do you Inject your AnyPresenter when using it? It is important, that the container is responsible for managing the Presenter. Dependendy Injection will not work if you do e.g. "new AnyPresenter()".
2. Re: Problems with @Inject annotationChristian Sadilek Nov 17, 2011 10:54 AM (in response to Rene Lenno)
For classses other than the EntryPoint (like your AnyPresenter) you need an @ApplicationScoped annotation, and like Dominik mentioned above, you also need an injection point to use them.
3. Re: Problems with @Inject annotationRene Lenno Nov 18, 2011 2:52 PM (in response to Rene Lenno)
Thanks for the advice. I will fix that next week.
Cheers
4. Re: Problems with @Inject annotationDavid Hahn Feb 22, 2012 11:24 AM (in response to Rene Lenno)
Hi,
did you solved the problem already?
I tried the above mentioned solution (injecting the presenter and use @ApplicationScoped for it) without success
Could you also provide some proper snippets? | https://community.jboss.org/thread/174973?tstart=0 | CC-MAIN-2015-48 | refinedweb | 354 | 50.57 |
Problem with getOptimalNewCameraMatrix
I want to calibrate a car video recorder and use it for 3D reconstruction with Structure from Motion (SfM). The original size of the pictures I have took with this camera is 1920x1080. Basically, I have been using the source code from the OpenCV tutorial for the calibration.
But there are some problems and I would really appreciate any help.
So, as usual (at least in the above source code), here is the pipeline:
- Find the chessboard corner with findChessboardCorners
- Get its subpixel value with cornerSubPix
- Draw it for visualisation with drawhessboardCorners
- Then, we calibrate the camera with a call to calibrateCamera
- Call the getOptimalNewCameraMatrix and the undistort function to undistort the image
In my case, since the image is too big (1920x1080), I have resized it to 640x320 and used it for the calibration (during SfM, I will also use this size of image, so, I don't think it would be any problem). And also, I have used a 9x6 chessboard corners for the calibration.
Here, the problem arose. After a call to the
getOptimalNewCameraMatrix, the distortion come out totally wrong. Even the returned ROI is
[0,0,0,0]. Below is the original image and its undistorted version:
You can see the image in the undistorted image is at the bottom left.
But, if I didn't call the
getOptimalNewCameraMatrix and just straight undistort it, I got a quite good image.
So, I have two questions.
- Why is this? I have tried with another dataset taken with the same camera, and also with my iPhone 6 Plus, but the results are same as above.
- For SfM, I guess the call to getOptimalNewCameraMatrix is important? Because if not, the undistorted image would be zoomed and blurred, making the keypoint detection harder (in my case, I will be using the optical flow)? I have tested the code with the opencv sample pictures and the results are just fine.
Below is my source code:
(more)(more)
from sys import argv import numpy as np import imutils # To use the imutils.resize function. # Resizing while preserving the image's ratio. # In this case, resizing 1920x1080 into 640x360. import cv2 import glob # termination criteria criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = np.zeros((9*6,3), np.float32) objp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2) # Arrays to store object points and image points from all the images. objpoints = [] # 3d point in real world space imgpoints = [] # 2d points in image plane. images = glob.glob(argv[1] + '*.jpg') width = 640 for fname in images: img = cv2.imread(fname) if width: img = imutils.resize(img, width=width) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # Find the chess board corners ret, corners = cv2.findChessboardCorners(gray, (9,6),None) # If found, add object points, image points (after refining them) if ret == True: objpoints.append(objp) corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria) imgpoints.append ...
Can you show the section of code where you call the function? I just tested with the calibration I'm currently using, and it works fine. It's probably a parameter problem, and for that we need to see what you're doing.
Hmm, I don't see anything wrong. I will point out that you should only need to call getOptimalNewCameraMatrix once though. It should be the same for all the images since they have same distortion and camera matrix.
Yeah, I can take a look.
Google Drive, megaupload, an imgur gallery, whatever.
Ok, My C++ version works fine. I'm fixing a problem with Python right now, so I'll get back to you on that.
Hmm, your python code is running just fine on my machine. What version of OpenCV are you using?
I'm using Python3, but yeah. No problems at all. I just copied your code and added a few print statements. It doesn't look like there's been any changes to the code, so I don't know why you wouldn't get the same results.
It's definitely because the roi is all zeros, but why is it all zeros? Are you getting all zeros in the distortion matrix as well?
And I've got
Which makes me wonder what the difference is.
So I tried just overwriting the dist matrix with the one you have, and it works fine. Your distortion matrix seems correct, and it puts out good results from getOptimalNewCameraMatrix.
Yep. Not a clue. But when using your values from calibrateCamera, getOptimalNCM works just fine.
Ah, wait what? Why is part of my calibration.cpp commented out? That may have something to do with it. | https://answers.opencv.org/question/102485/problem-with-getoptimalnewcameramatrix/ | CC-MAIN-2021-21 | refinedweb | 791 | 67.86 |
Name: Selenium for python 2.7
File size: 817mb
Language: English
Rating: 5/10
Download
8 May Example 2: Selenium WebDriver is often used as a basis for testing web applications. Here is a simple example uisng Python's standard. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium This documentation explains Selenium 2 WebDriver API. Note. This is not an official documentation. If you would like to contribute to this documentation, you can fork this project in Github and send pull requests.
from selenium import webdriver from turtlebaybiathlon.com import Keys driver = turtlebaybiathlon.comx() turtlebaybiathlon.com("turtlebaybiathlon.com") assert. The current supported Python versions are Python and Python Python 3 is not yet supported. Selenium server is a Java program. Java Runtime. Python 's EOL or sunset date was moved to In other words, during , Python will no longer maintain Python While maintenance by core Python.
Drop support for Python , , Now only supporting Python Currently only supporting a selenium version < as this version breaks using a custom . how to install selenium python webdriver, installing Python and Selenium, Python selenium The current supported Python versions are , , and 20 Nov For this, go the following URL, download the latest Python (I am using x) and install it: turtlebaybiathlon.com Install PIP: If you. This blog details the steps to installing Selenium for use with Python. I don't understand what he means by "use pip command below to install. 2 Jul This is a quick introduction to Selenium WebDriver in Python on Ubuntu/Debian systems. WebDriver (part of Selenium 2) is a library for.
29 Jun OSx Sierra comes with Python already installed. import unittest from selenium import webdriver from turtlebaybiathlon.com 26 Oct The current supported Python versions are Python and Python Python 3 is not yet supported. Selenium server is a Java program. Python bindings for the Selenium WebDriver for automating web browser interaction. Conda · Files · Labels · Badges. License: Apache ; Home. Python # Selenium. # turtlebaybiathlon.com install selenium. # Firefox. #. # To Run: # python turtlebaybiathlon.com #. # Please email [email protected] with any.
More: | http://turtlebaybiathlon.com/entertainment/selenium-for-python-27.php | CC-MAIN-2018-47 | refinedweb | 346 | 51.04 |
The Silverlight Tools Beta 1 for Visual Studio 2008 includes support for creating applications in Silverlight version 2 Beta 1. The Silverlight Designer Preview in Visual Studio 2008 has features that are a subset of the features in the WPF Designer.
The following table lists the features that are supported in the Silverlight Designer Preview for Silverlight 2 Beta 1 projects.
Feature
Notes
Full XAML editing is supported.
IntelliSense and XAML formatting is the same as in the WPF Designer's XAML editor, except that Silverlight 2 Beta 1 types are targeted instead of WPF types.
Design view displays a read-only WYSIWYG visual preview.
Allows the developer to preview work before running it. Design view supports zoom.
Split view with Design view and XAML view is supported.
Silverlight 2 Beta 1 controls and corresponding icons are displayed in the Toolbox.
Silverlight 2 Beta 1 controls are displayed alphabetically in a tab on the Toolbox.
The Toolbox with drag-and-drop support for XAML view is supported.
Useful for adding Silverlight 2 Beta 1 controls from non-default namespaces. When a control is added, a reference and the namespace are added automatically.
The Document Outline window and tag navigator are available when editing XAML.
Navigation features for interacting with the code are supported.
Auto-update between XAML view and other WPF Designer components is supported.
Errors are reported in the Error List window.
XAML with errors causes the Last Known Good view to be displayed until valid XAML is entered.
The following table lists the features that are not supported in the Silverlight Designer Preview for Silverlight 2 Beta 1 projects.
Modifications in Design view are not supported.
Selecting controls, moving controls, adding items from the Toolbox, and other Design view features are not supported.
The Properties window is not supported.
Globalization features are not supported.
Automatic resource reloading is not supported.
Changes to resources that are contained in other files require a rebuild before they are visible in the loaded XAML. | http://silverlight.net/Quickstarts/Start/18660837-4a10-462b-bf6e-723b36748ec3.aspx | crawl-001 | refinedweb | 332 | 58.79 |
I have seconds since Jan 1 1970 00:00 as an int64 in nanoseconds and I'm trying to convert it into month/day/year/day of week.
It's easy to do this iteratively, I have that working but I want to do it formulaically. I'm looking for the actual math.
New answer for old question:
Rationale for this new answer: The existing answers either do not show the algorithms for the conversion from nanoseconds to year/month/day (e.g. they use libraries with the source hidden), or they use iteration in the algorithms they do show.
This answer has no iteration whatsoever.
The algorithms are here, and explained in excruciating detail. They are also unit tested for correctness over a span of +/- a million years (way more than you need).
The algorithms don't count leap seconds. If you need that, it can be done, but requires a table lookup, and that table grows with time.
The date algorithms deal only with units of days, and not nanoseconds. To convert days to nanoseconds, multiply by
86400*1000000000 (taking care to ensure you're using 64 bit arithmetic). To convert nanoseconds to days, divide by the same amount. Or better yet, use the C++11
<chrono> library.
There are three date algorithms from this paper that are needed to answer this question.
1.
days_from_civil:
//; }
2.
civil_from_days:
// Returns year/month/day triple in civil calendar // Preconditions: z is number of days since 1970-01-01 and is in the range: // [numeric_limits<Int>::min(), numeric_limits<Int>::max()-719468]. template <class Int> constexpr std::tuple<Int, unsigned, unsigned> civil_from_days(Int z) noexcept { static_assert(std::numeric_limits<unsigned>::digits >= 18, "This algorithm has not been ported to a 16 bit unsigned integer"); static_assert(std::numeric_limits<Int>::digits >= 20, "This algorithm has not been ported to a 16 bit signed integer"); z += 719468; const Int era = (z >= 0 ? z : z - 146096) / 146097; const unsigned doe = static_cast<unsigned>(z - era * 146097); // [0, 146096] const unsigned yoe = (doe - doe/1460 + doe/36524 - doe/146096) / 365; // [0, 399] const Int y = static_cast<Int>(yoe) + era * 400; const unsigned doy = doe - (365*yoe + yoe/4 - yoe/100); // [0, 365] const unsigned mp = (5*doy + 2)/153; // [0, 11] const unsigned d = doy - (153*mp+2)/5 + 1; // [1, 31] const unsigned m = mp + (mp < 10 ? 3 : -9); // [1, 12] return std::tuple<Int, unsigned, unsigned>(y + (m <= 2), m, d); }
3.
weekday_from_days:
// Returns day of week in civil calendar [0, 6] -> [Sun, Sat] // Preconditions: z is number of days since 1970-01-01 and is in the range: // [numeric_limits<Int>::min(), numeric_limits<Int>::max()-4]. template <class Int> constexpr unsigned weekday_from_days(Int z) noexcept { return static_cast<unsigned>(z >= -4 ? (z+4) % 7 : (z+5) % 7 + 6); }
These algorithms are written for C++14. If you have C++11, remove the
constexpr. If you have C++98/03, remove the
constexpr, the
noexcept, and the
static_asserts.
Note the lack of iteration in any of these three algorithms.
They can be used like this:
#include <iostream> int main() { int64_t z = days_from_civil(2015LL, 8, 22); int64_t ns = z*86400*1000000000; std::cout << ns << '\n'; const char* weekdays[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; unsigned wd = weekday_from_days(z); int64_t y; unsigned m, d; std::tie(y, m, d) = civil_from_days(ns/86400/1000000000); std::cout << y << '-' << m << '-' << d << ' ' << weekdays[wd] << '\n'; }
which outputs:
1440201600000000000 2015-8-22 Sat
The algorithms are in the public domain. Use them however you want. The date algorithms paper has several more useful date algorithms if needed (e.g.
weekday_difference is both remarkably simple and remarkably useful).
These algorithms are wrapped up in an open source, cross platform, type-safe date library if needed.
If timezone or leap second support is needed, there exists a timezone library built on top of the date library.
Update: Different local zones in same app
See how to convert among different time zones.
Update: Are there any pitfalls to ignoring leap seconds when doing date calculations in this manner?
This is a good question from the comments below.
Answer: There are some pitfalls. And there are some benefits. It is good to know what they both are.
Almost every source of time from an OS is based on Unix Time. Unix Time is a count of time since 1970-01-01 excluding leap seconds. This includes functions like the C
time(nullptr) and the C++
std::chrono::system_clock::now(), as well as the POSIX
gettimeofday and
clock_gettime. This is not a fact specified by the standard (except it is specified by POSIX), but it is the de facto standard.
So if your source of seconds (nanoseconds, whatever) neglects leap seconds, it is exactly correct to ignore leap seconds when converting to field types such as
{year, month, day, hours, minutes, seconds, nanoseconds}. In fact to take leap seconds into account in such a context would actually introduce errors.
So it is good to know your source of time, and especially to know if it also neglects leap seconds as Unix Time does.
If your source of time does not neglect leap seconds, you can still get the correct answer down to the second. You just need to know the set of leap seconds that have been inserted. Here is the current list.
For example if you get a count of seconds since 1970-01-01 00:00:00 UTC which includes leap seconds and you know that this represents "now" (which is currently 2016-09-26), the current number of leap seconds inserted between now and 1970-01-01 is 26. So you could subtract 26 from your count, and then follow these algorithms, getting the exact result.
This library can automate leap-second-aware computations for you. For example to get the number of seconds between 2016-09-26 00:00:00 UTC and 1970-01-01 00:00:00 UTC including leap seconds, you could do this:
#include "chrono_io.h" #include "tz.h" #include <iostream> int main() { using namespace date; auto now = to_utc_time(sys_days{2016_y/sep/26}); auto then = to_utc_time(sys_days{1970_y/jan/1}); std::cout << now - then << '\n'; }
which outputs:
1474848026s
Neglecting leap seconds (Unix Time) looks like:
#include "chrono_io.h" #include "date.h" #include <iostream> int main() { using namespace date; using namespace std::chrono_literals; auto now = sys_days{2016_y/sep/26} + 0s; auto then = sys_days{1970_y/jan/1}; std::cout << now - then << '\n'; }
which outputs:
1474848000s
For a difference of
26s.
This upcoming New Years (2017-01-01) we will insert the 27th leap second.
Between 1958-01-01 and 1970-01-01 10 "leap seconds" were inserted, but in units smaller than a second, and not just at the end of Dec or Jun. Documentation on exactly how much time was inserted and exactly when is sketchy, and I have not been able to track down a reliable source.
Atomic time keeping services began experimentally in 1955, and the first atomic-based international time standard TAI has an epoch of 1958-01-01 00:00:00 GMT (what is now UTC). Prior to that the best we had was quartz-based clocks which were not accurate enough to worry about leap seconds. | https://codedump.io/share/AqNRbBAzZ7Cw/1/math-to-convert-seconds-since-1970-into-date-and-vice-versa | CC-MAIN-2017-13 | refinedweb | 1,196 | 62.07 |
Answered by:
Double Linked List and Pointer in C
Hi all,
I am getting confused by pointer in C. I have dlnode_t and dlist_t as struct to implement double linked list.
typedef struct dlnode dlnode_t; struct dlnode { void *data; /* A pointer to a generic satellite data payload */ dlnode_t *next; /* A pointer to the next item in the list */ dlnode_t *prev; /* A pointer to the previous item in the list */ }; typedef struct { dlnode_t *head; /* A pointer to the head node of the list */ dlnode_t *foot; /* A pointer to the foot node of the list */ int list_len; /* Total number of items in the list */ int size; /* Size of the list in bytes */ } dlist_t;
int * alloc_data(int val) { int *rv = safe_malloc(sizeof (int)); *rv = val; return (rv); }
int main(void) { dlist_t *list = NULL; int *num = NULL, *rv = NULL; dlnode_t *tnode = NULL; list = make_empty_list(); list = insert_in_order(list, alloc_data(5), sizeof (int), cmp_int); printf("%d\n",list->list_len); printf("%d\n",list->list_len); list = insert_in_order(list, alloc_data(2), sizeof (int), cmp_int); list = insert_in_order(list, alloc_data(10), sizeof (int), cmp_int); ... }
void * safe_malloc(size_t size) { void * arrays = malloc(size * sizeof (int)); if (arrays == NULL) { fprintf(stderr, "Memory allocation failed. The program will be terminated.\n"); exit(EXIT_FAILURE); } return arrays; }
int cmp_int(const void *a, const void *b) { int a_int=(int*)a; int b_int=(int*)b; if(a==NULL || b==NULL) { fprintf(stderr,"Either the value of a or b is NULL."); exit(EXIT_FAILURE); } if(a_int>b_int) return BIGGER; else if(a_int<b_int) return SMALLER; return EQUAL; }
dlist_t * make_empty_list(void) { dlist_t *double_list_pointer = NULL; dlist_t double_list; double_list.foot = NULL; double_list.head = NULL; double_list.list_len = 0; double_list.size = 0; double_list_pointer = &double_list; return double_list_pointer; }
dlist_t * insert_in_order(dlist_t *list, void *value, size_t size, int (*cmp_fptr)(const void *, const void *)) { dlnode_t *current_dlnode = list->head; dlnode_t *new_dlnode = safe_malloc(sizeof(dlnode_t));; dlnode_t *previous_dlnode=NULL; int compare_result = 0; while (current_dlnode!=NULL) { compare_result = cmp_fptr(current_dlnode->data, value); if(compare_result!=SMALLER) continue; previous_dlnode=current_dlnode; current_dlnode=current_dlnode->next; } new_dlnode->data = value; new_dlnode->next = current_dlnode; new_dlnode->prev = previous_dlnode; list->list_len=list->list_len+1; list->size=list->size+sizeof(new_dlnode); if(previous_dlnode==NULL) { current_dlnode=new_dlnode; return list; } previous_dlnode->next=new_dlnode; if(new_dlnode->next==NULL) { list->foot=new_dlnode; } return list; }
The first time, after putting an integer into the list, the insert_in_order function will return the list as pointer. list->head still have the same memory address as before. But, the value of list->foot; list->list_len; and list->size are changed. Notice the printf inside the main function, that is where changes occured.
As a result, the second time, when the list being passed into the insert_in_order function, the value of them changed.
Example: Suppose the list->list_len should be 1, but it turns out that it gives me a garbage value.
I don't get it, why all the values, except for head, are changed after the list being returned.
Sorry, if my english is bad.
Question
Answers
All replies
There are numerous problems with your code. The following are just the obvious ones at first glance:
There is no declaration (prototype or definition) in scope when alloc_data calls safe_malloc. The compiler must assume safe_malloc returns int which is obviously false and should lead to a required diagnostic.
The same problem exists when main calls make_empty_list.
make_empty_list returns the address of an automatic object. The object will cease to exist as soon as make_empty_list returns. It is illegal for main to attempt to use that object or make any use of the returned value.
The same missing prototype problem exists when main calls insert_in_order. Furthermore, cmp_int is undefined at this point. The compiler has no idea what value to pass but must assume the value is an int. This should result in a required diagnostic at the point where insert_in_order is defined.
On each call to insert_in_order, previous_dlnode is set to NULL. On the first call, list->head is also NULL (courtesy of make_empty_list) and that value is assigned to current_dlnode. The while loop is skipped, values are stored in *new_dlnode, list->list_len and list->size are updated, and list->head is NOT updated. previous_dlnode is still NULL so you return WITHOUT EVER UPDATING list->head. On the second call, this process is repeated. list->head is NEVER updated!
You could save a lot of typing (and the possibility of typing errors) if you replace lines like list->list_len=list->list_len+1; with list->list_len += 1; (and in this case the more idiomatic list->list_len++;).
Why in main do you print list->len twice in succession? | http://social.msdn.microsoft.com/Forums/vstudio/en-US/57451cd2-6db2-4262-bbff-0985dedcdfc7/double-linked-list-and-pointer-in-c?forum=vcgeneral | CC-MAIN-2014-35 | refinedweb | 746 | 54.63 |
In this article I will go over some of my thoughts on TypeScript. It will not be an in depth article, and I will try to keep it as short as possible. Let's start with the pros 🎉
Pros
1. Errors: You are able to detect errors during compile-time. This will give quick feedback and it makes refactoring much easier. It is also helpful when scaling the project.
2. IntelliSense: There is often good support of IntelliSense. This includes autocompletion and autoimports. I also really like, that I am able to get quick info.
Source: Visual Studio Code
3. Adopting: When you are working on existing JavaScript projects, it is really amazing, that you are able to gradually adopt TypeScript. TypeScript is based on JavaScript, so in practice you could just write plain old JavaScript in a
.ts file.
"TypeScript is a typed superset of JavaScript that compiles to plain JavaScript." - typescriptlang.org
4. Patterns: I really like, that TypeScript from the start is guiding the user of TypeScript to use structure. When you are writing plain JavaScript, it can easily become spaghetti code. We as developers want to follow some form of patterns and structure. This can be achieved from the start using
class,
interface,
namespace and
module, amongst other things.
class Car { // Fields // Constructor // Properties // Functions }
5. Ability to understand: I have talked with people both from frontend and backend. A bunch of people from backend hated JavaScript, but none of them hated TypeScript. I guess it is easier to understand when you are used to work with type heavy languages like Java or C#.
6. Jobs: TypeScript is gaining more and more popularity and more companies are using the language. This gives more job opportunities surrounding TypeScript.
Cons
1. Time: You often need a build environment, and it will therefore take more time upfront.
2. Errors: The error messages can sometimes be misleading, but you should never only just trust the IDE or editor anyway.
3. Library support: Not all JavaScript libraries supports TypeScript, but most of them do.
4. Learning: Like everything, it takes time to learn. We are only human, and I would not say, that the learning curve is that high, if you already got the basics of programming in place.
Note for con #3: The way I wrote this was misleading. Check out this article. It explains my point 😊
Discussion (2)
Can you elaborate on con 3?
All JavaScript is valid TypeScript.
And the
@typesrepo as a lot of typings for libraries that don't ship with typing themselves.
You can use the libraries in TypeScript without hassle nearly all times, as the TypeScript is transpiled back to JavaScript anyway.
Normally you are consuming a third party library, not injecting your code into it. I feel like I'm missing part of the explanation of your con?
Thank you for pointing this out 😊 I have updated the article with a comment at the bottom. | https://practicaldev-herokuapp-com.global.ssl.fastly.net/steffenpedersen/typescript-6-pros-and-4-cons-biased-1l9n | CC-MAIN-2021-10 | refinedweb | 492 | 75 |
slight lean to yes (let's move to svn). I also agree with
Steve's main point; both cvs and svn have a centralized model which isn't
ideal for us. But, svn has much better support for repository
restructuring and if we're about to embark on large scale restructures of
the repository it probably makes sense to seriously consider switching.
There is a conversion path (cvs2svn) from cvs to svn that should preserve
history. We've got 5+ years of development in this repository, a
moderately big repository with a number of branches & tags, and I know we
have a couple of partially corrupted RCS files sitting there (it confuses
statcvs for example), so I suspect we will lose a few bits and pieces.
Because of this, and because we have multiple cvs modules, we're not going
to be able to use the almost fully automated SF migration service.
SF is more restrictive on the commit hooks that can be run on svn as
opposed to cvs. Many of our old developerworks commit hooks couldn't be
made to work on sourceforge due to different server topology, so I believe
the only thing we are currently losing that we would lose is the update of
the _timestamp file. However, as I understand svn, we probably don't care
about this since svn has a model of global versioning of the entire
repository on each commit.
My suggestion is that we continue this discussion and see what the general
feeling among core team members is. If it's positive, then we can do some
evaluation of how well cvs2svn is going to work on our repository. I'll
volunteer to do this as I'm extremely picky about revision control and
project history :) If it looks like the conversion is going to be viable,
then we can discuss more if necessary, bring up the proposal on the
researchers list, etc.
I'd expect this to be a somewhat disruptive/drawn out process. The svn
import on the SF side may take several days (according to the site docs).
I'd also expect it would take a few more days to work out kinks in nightly
regression scripts, machine configurations, etc. So, a downtime (no
commits) of a week or so seems likely. So, as a timeline, continue
discussion on this list, If it's generally positive I'll do some
experiments locally on using cvs2svn and report within the next week, and
after we get 2.4.5 out the door (hopefully by end of June), we could make
a switch (if that is the final decision).
- | https://sourceforge.net/p/jikesrvm/mailman/message/7402134/ | CC-MAIN-2017-30 | refinedweb | 439 | 56.18 |
08 May 2012 05:53 [Source: ICIS news]
(adds background with recasts throughout)
?xml:namespace>
SINGAPORE
At least 10 people were killed, while more than 140 were injured from the incident that occurred at a toluene vessel inside BST Elastomers' plant at around 15:20
BST Elastomers’ 55,000 tonne/year butadiene rubber (BR) unit and its 75,000 tonne/year synthetic butadiene rubber (SBR) plant sustained “severe damage” from the weekend incident and are expected to be down for months, the company said in a letter to customers dated 8 May.
“There was an explosion and fire at the BR unit on May 5th 2012 and subsequently damaged the SBR facility,” the company said in the letter.
BST Elastomers expects the BR unit to be shut for six months, while its SBR plant will likely be off line for two months, the company said in the letter.
BST, on the other hand, expects the shutdown of its plants, including a 140,000 tonne/year butadiene (BD) unit and a 55,000 tonne/year methyl tertiary butyl ether (MTBE) unit, to last at least a month, a company source said.
Operations were also halted at the company’s 55,000 tonne/year of butane liquefied petroleum gas (LPG) unit, a 40,000 tonne/year of C4 raffinate (isobutylene) unit and a 35,000 tonne/year butene-1 unit, the source | http://www.icis.com/Articles/2012/05/08/9557118/thai-bst-declares-fm-in-map-ta-phut-br-sbr-plants-damaged.html | CC-MAIN-2014-52 | refinedweb | 230 | 52.67 |
String.Trim Method
Namespace: SystemNamespace: System
Assembly: mscorlib (in mscorlib.dll)
The Trim method removes from the current string all leading and trailing white-space characters. Each leading and trailing trim operation stops when a non-white-space character is encountered. For example, if the current string is " abc xyz ", the Trim method returns "abc xyz".,() method to remove any extra white space from strings entered by the user before concatenating them.
using System; public class Example { public static void Main() { Console.Write("Enter your first name: "); string firstName = Console.ReadLine(); Console.Write("Enter your middle name or initial: "); string middleName = Console.ReadLine(); Console.Write("Enter your last name: "); string lastName = Console.ReadLine(); Console.WriteLine(); Console.WriteLine("You entered '{0}', '{1}', and '{2}'.", firstName, middleName, lastName); string name = ((firstName.Trim() + " " + middleName.Trim()).Trim() + " " + lastName.Trim()).Trim(); Console.WriteLine("The result is " + name + "."); } } // The following is possible output from this example: // Enter your first name: John // Enter your middle name or initial: // Enter your last name: Doe // // You entered ' John ', '', and ' Doe'. // The result is John Do. | http://technet.microsoft.com/en-us/library/t97s7bs3.aspx | CC-MAIN-2014-52 | refinedweb | 176 | 51.95 |
Specio - Type constraints and coercions for Perl
version 0.11
package MyApp::Type::Library; use Specio::Declare; use Specio::Library::Builtins; declare( 'PositiveInt', parent => t('Int'), inline => sub { $_[0]->parent()->inline_check( $_[1] ) . ' && ( ' . $_[1] . ' > 0'; }, ); # or ... declare( 'PositiveInt', parent => t('Int'), where => sub { $_[0] > 0 }, ); declare( 'ArrayRefOfPositiveInt', parent => t( 'ArrayRef', of => t('PositiveInt'), ), ); coerce( 'ArrayRefOfPositiveInt', from => t('PositiveInt'), using => sub { [ $_[0] ] }, ); any_can_type( 'Duck', methods => [ 'duck_walk', 'quack' ], ); object_isa_type('MyApp::Person');
WARNING: This thing is very alpha.
The
Specio distribution provides classes for representing type constraints and coercion, along with syntax sugar for declaring them.
Note that this is not a proper type system for Perl. Nothing in this distribution will magically make the Perl interpreter start checking a value's type on assignment to a variable. In fact, there's no built-in way to apply a type to a variable at all.
Instead, you can explicitly check a value against a type, and optionally coerce values to that type.
My long-term goal is to replace Moose's built-in types and MooseX::Types with this module. I will also make sure that Specio types can be used with Moo in a sane fashion.
At it's core, a type is simply a constraint. A constraint is code that checks a value and returns true or false. Most constraints are represented by Specio::Constraint::Simple objects. However, there are other type constraint classes for specialized kinds of constraints.
Types can be named or anonymous, and each type can have a parent type. A type's constraint is optional because it can be used to create a named subtype of some existing type without adding additional constraints.
Constraints can be expressed either in terms of a simple subroutine reference or in terms of an inline generator subroutine reference. The former is easier to write but the latter is preferred because it allow for better optimization.
A type can also have an optional message generator subroutine reference. You can use this to provide a more intelligent error message when a value does not pass the constraint, though the default message should suffice for most cases.
Finally, you can associate a set of coercions with a type. A coercion is a subroutine reference (or inline generator, like constraints), that takes a value of one type and turns it into a value that matches the type the coercion belongs to.
This distribution ships with a set of builtin types representing the types provided by the Perl interpreter itself. They are arranged in a hierarchy as follows:
Item Bool Maybe (of `a) Undef Defined Value Str Num Int ClassName Ref ScalarRef (of `a) ArrayRef (of `a) HashRef (of `a) CodeRef RegexpRef GlobRef FileHandle Object
The
Item type accepts anything and everything.
The
Bool type only accepts
undef,
0, or
1.
The
Undef type only accepts
undef.
The
Defined type accepts anything except
undef.
The
Num and
Int types are stricter about numbers than Perl is. Specifically, they do not allow any sort of space in the number, nor do they accept "Nan", "Inf", or "Infinity".
The
ClassName type constraint checks that the name is valid and that the class is loaded.
The
FileHandle type accepts either a glob, a scalar filehandle, or anything that isa IO::Handle.
All types accept overloaded objects that support the required operation. See below for details.
Perl's overloading is horribly broken and doesn't make much sense at all.
However, unlike Moose, all type constraints allow overloaded objects where they make sense.
For types where overloading makes sense, we explicitly check that the object provides the type overloading we expect. We do not simply try to use the object as the type and question and hope it works. This means that these checks effectively ignore the
fallback setting for the overloaded object. In other words, an object that overloads stringification will not pass the
Bool type check unless it also overloads boolification.
Most types do not check that the overloaded method actually returns something that matches the constraint. This may change in the future.
The
Bool type accepts an object that provides
bool overloading.
The
Str type accepts an object that provides string (
q{""}) overloading.
The
Num type accepts an object that provides numeric
'0+'} overloading. The
Int type does as well, but it will check that the overloading returns an actual integer.
The
ClassName type will accept an object with string overloading that returns a class name.
To make this all more confusing, the
Value type will never accept an object, even though some of its subtypes will.
The various reference types all accept objects which provide the appropriate overloading. The
FileHandle type accepts an object which overloads globification as long as the returned glob is an open filehandle.
Any type followed by a type parameter
of `a in the hierarchy above can be parameterized. The parameter is itself a type, so you can say you want an "ArrayRef of Int", or even an "ArrayRef of HashRef of ScalarRef of ClassName".
When they are parameterized, the
ScalarRef and
ArrayRef types check that the value(s) they refer to match the type parameter. For the
HashRef type, the parameter applies to the values (keys are never checked).
The
Maybe type is a special parameterized type. It allows for either
undef or a value. All by itself, it is meaningless, since it is equivalent to "Maybe of Item", which is equivalent to Item. When parameterized, it accepts either an
undef or the type of its parameter.
This is useful for optional attributes or parameters. However, you're probably better off making your code simply not pass the parameter at all This usually makes for a simpler API.
Types are local to each package where they are used. When you "import" types from some other library, you are actually making a copy of that type.
This means that a type named "Foo" in one package may not be the same as "Foo" in another package. This has potential for confusion, but it also avoids the magic action at a distance pollution that comes with a global type naming system.
The registry is managed internally by the Specio distribution's modules, and is not exposed to your code. To access a type, you always call
t('TypeName').
This returns the named type or dies if no such type exists.
Because types are always copied on import, it's safe to create coercions on any type. Your coercion from
Str to
Int will not be seen by any other package, unless that package explicitly imports your
Int type.
When you import types, you import every type defined in the package you import from. However, you can overwrite an imported type with your own type definition. You cannot define the same type twice internally.
By default, all types created inside a package are invisible to other packages. If you want to create a type library, you need to inherit from Specio::Exporter package:
package MyApp::Type::Library; use parent 'Specio::Exporter'; use Specio::Declare; use Specio::Library::Builtins; declare( 'Foo', parent => t('Str'), where => sub { $_[0] =~ /foo/i }, );
Now the MyApp::Type::Library package will export a single type named
Foo. It does not re-export the types provided by Specio::Library::Builtins.
If you want to make your library re-export some other libraries types, you can ask for this explicitly:
package MyApp::Type::Library; use parent 'Specio::Exporter'; use Specio::Declare; use Specio::Library::Builtins -reexport; declare( 'Foo, ... );
Now MyApp::Types::Library exports any types it defines, as well as all the types defined in Specio::Library::Builtins.
Use the Specio::Declare module to declare types. It exports a set of helpers for declaring types. See that module's documentation for more details on these helpers.
This needs some changes in Moose core. Stay tuned.
Using Specio with Moo is easy. You can pass Specio constraint objects as
isa parameters for attributes. For coercions, simply call
$type->coercion_sub().
package Foo; use Specio::Declare; use Specio::Library::Builtins; use Moo; my $str_type = t('Str'); has string => ( is => 'ro', isa => $str_type, ); my $ucstr = declare( 'UCStr', parent => t('Str'), where => sub { $_[0] =~ /^[A-Z]+$/ }, ); coerce( $ucstr, from => t('Str'), using => sub { return uc $_[0] }, ); has ucstr => ( is => 'ro', isa => $ucstr, coerce => $ucstr->coercion_sub(), );
The subs returned by Specio use Sub::Quote internally and are suitable for inlining.
See Specio::Constraint::Simple for the API that all constraint objects share.
This module aims to supplant both Moose's built-in type system (see Moose::Util::TypeConstraints aka MUTC) and MooseX::Types, which attempts to patch some of the holes in the Moose built-in type design.
Here are some of the salient differences:
Unlike Moose and MooseX::Types, type names are always local to the current package. There is no possibility of name collision between different modules, so you can safely use short types names.
Unlike MooseX::Types, types are strings, so there is no possibility of colliding with existing class or subroutine names.
Types are always retrieved using the
t() subroutine. If you pass an unknown name to this subroutine it dies. This is different from Moose and MooseX::Types, which assume that unknown names are class names.
The
$type->validate_or_die() method throws a Specio::Exception object on failure, not a string.
With Moose and MooseX::Types, you use the same subroutine,
subtype(), to declare both named and anonymous types. With Specio, you use
declare() for named types and
anon() for anonymous types.
Moose and MooseX::Types have
class_type and
duck_type. The former type requires an object, while the latter accepts a class name or object.
With Specio, the distinction between accepting an object versus object or class is explicit. There are six declaration helpers,
object_can_type,
object_does_type,
object_isa_type,
any_can_type,
any_does_type, and
any_isa_type.
Perl's overloading is quite broken but ignoring it makes Moose's type system frustrating to use in many cases.
Moose and MooseX::Types types can be defined with a subroutine reference as the constraint, an inline generator subroutine, or both. This is purely for backwards compatibility, and it makes the internals more complicated than they need to be.
With Specio, a constraint can have either a subroutine reference or an inline generator, not both.
I simply never got around to implementing this in Moose.
Moose has some bizarre (and mostly) undocumented features relating to coercions and parameterizable types. This is a misfeature.
This distro was originally called "Type", but that's an awfully generic top level namespace. Specio is Latin for for "look at" and "spec" is the root for the word "species". It's short, relatively easy to type, and not used by any other distro.
Eventually I'd like to see this distro replace Moose's internal type system, which would also make MooseX::Types obsolete. This almost certainly means rewriting this distro to not use Moose itself (or any modules which use Moose, like Throwable).
Please report any bugs or feature requests to
bug-type) 2014 by Dave Rolsky.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible) | http://search.cpan.org/~drolsky/Specio/lib/Specio.pm | CC-MAIN-2014-52 | refinedweb | 1,850 | 64.41 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
multiple invoice layout
I would like to have multiple layouts on the invoice. Under the print button you get 'invoices' I would like to see more choices of custom made layout invoices.
Something like [PRINT] - invoice std - invoice special - invoice foreign Where the names are also custom depending on the layout.
We use the delivery address as a location reference so this should be printed on the invoice in some cases.
Is this possible ? If so how do I do this ?
PS. I have tried the OpenOffice template editor module but this ruined my openerp-print-invoice.
Note: Make sure you have administration privileges and in user Access Rights you have Technical Features checked.
You need the following:
- A new/modified/existing RML invoice template that should be saved in addons/account/report or anywhere you like.
- a new Report Action
- and an Action Binding for it.
Report Action
- Go to Settings->Technical->Actions->Reports and search for invoice
- click the More drop down list and select Duplicate to create a new identical entry, all you have to change is the Name and the Report File location
Action Binding
- Go to Settings->Technical->Actions->Action Bindings
- Again look up invoice
- Duplicate it the same way you did for the report, but in Action (change only) write the name of the new report you just created earlier.
You are done, you will now have 2 options in the invoice Print drop down list.
You can have as many reports as you like and this works for all other types of reports, not just invoices.
PS: Make sure that the
Action Binding for the new
Report has the
Qualifier set to
client_print_multi
Update: You need a report python file to define the report service, this is an example for a secondary invoice report:
import time from openerp.report import report_sxw class account_invoice_secondary(report_sxw.rml_parse): def __init__(self, cr, uid, name, context=None): super(account_invoice_secondary, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'time': time, }) report_sxw.report_sxw( 'report.account.invoice.secondary', 'account.invoice', 'account/report/account_invoice_secondary_report.rml', parser = account_invoice_secondary )
Make sure to configure your report to have the service name account.invoice.secondary
name your file account_invoice_secondary_report.py and put it in account/report/ and lastly, import it in accounts/report/__init__.py
Restart your server and it should work.
Hi, just wondering how you sorted it out. I followed step by step the whole procedure, and still the same first rml report is used, whatever the line i am using in the Print drop down list.
Did you change the
Report File field in your new report? Because it should be different from the default one.
Yes, this was the first field value changed. Does it work on your side with two different Report files ?
Nope, this is a Linux one
Hello. Looking now to the script from the module, i seems the module is able to process only one single entry (the first one) within the Settings - Technical/Actions/Reports record set. Hence, it cannot work the way i was expecting. And the only way i can imagine now is to manage the Security tab so that i make sure that a User can "see" only one entry within the set, and so should the expected behavior be ensured.
Did you make sure that the corresponding Action Binding has the
Qualifier set to
client_print_multi ?
Yes, i did. As i am not able to illustrate the module script which keep the only first occurrence for processing, there is nothing much i can provide, else than a suspicion on the script from the module. Thanks.
I have followed your instructions to the letter, but I still have only one option under my dropdown. I am using Windows, does this work differently for this OS?
It should work for Windows, please make sure that the
Action Binding for the new
Report has the
Qualifier set to
client_print_multi
Well I tried numerous times but haven't got it set up yet. :(
To recapitulate, there are two things which I am not entirely certain of; based on your description. For "Action Bindings" you say "look up Invoice"; do you mean the binding "Invoice" (account.analytic.account) or "account.invoice" (account.invoice)? [I already tried both, but want to be sure now]
Also for the "Action (change only)" field, I am not sure if I did it right. I made a new record with: Name = account_print_invoice_FR.rml, Type of action = ir.actions.report.xml. Do I need to select an existing record, which one?
I already had the qualifier set to client_print_multi, as you recommended higher up in the thread.
UPDATE: I can't edit the above comment, but I figured I should use "ir.actions.act_window" as type for the action instead of what I specified earlier. I also guess I should use "Invoice" (account.analytic.account), rather than "account.invoice"; because otherwise it will result in view errors on the invoices. HOWEVER: it still doesn't work. :/ I can't figure out what I'm doing wrong, as I've done it over 10 times by now - and am convinced my settings appear to be configured correctly.
I tried this solution and It worked perfect for me!
Many, Many thanks for your answer Karim!
If anybody want to know my exact steps please let me know.
With Kind regards,
Michael Bos
Ps. I made a brand new incoming shipment document, with print options and all.
thanks it works for me have the very same problem as 62552; both print the same form; I am using v7 for Windows and just cant figure out WHY!
same problem with 62552, 57672, I'm using ubuntu 12.04 , openerp v7. Anyone know how to solve this?
This is really nice solution but i got a problem (Report has not been downloaded Detail: URL seems to be an unsupported one) when i try to modify new report through openoffice (modify existing report).
Michael Bos let us know how do yo do it?
I am sorry for my late reaction. I am not nearby a real computer untill the weekend. I will then post this as a solution. Thank you!
Hello Thanks it's work for me , but the problem in traslation i can not translate my second invoice which directory is same as invoice directory
hi all,
we spent a lot of time figuring out how to make multiple layouts working. finally we did it and we wan't to share our experiences with you.
for a detailed documentation about creating multiple sale order layouts have a look at the following link. this documentation may also be used to create other additional layouts/reports.
10 seconds later: when trying to post this answer I received: "Could not post, because your karma is insufficient to publish links"
therefore: please go to -> Support -> Knowledge database -> OpenERP - FAQ -> OpenERP7 - Multiple sale order, invoice layouts, reports
we used a lot of images for documentation purposes. therefore we're not able to do a simple copy/paste to this forum.
direct link to the documentation article at oneStep2:
kind regards, sandra oneStep2
Thank's Sandra. I follow your steps but when I duplicate the action binding I can't see the action (change only) previusly created. I don't have Quotation / Order / Other_layout because It isn't an action it's an action report. Thanks in advance
Hi, yes, it is an action, but it can be selected if you have previously created this new report...did you follow step by step our documentation?
Hello Thanks it's work for me , but the problem in traslation i can not translate my second invoice which directory is same as invoice directory
I created a step by step guide with screenshots on how to do this using Odoo v8. I struggled with this for a long time (being new to Odoo myself) and I hope this guide will help save others the same frustration I went through.
Here's the guide to Create Multiple Invoice Templates in Odoo v8:
link is dead
Still working here, Pascal: Is there an error you're getting?
Friends i too faced the same problem and got a solution.
We can create a duplicate invoice from the existing one. check this link :
Thank you and Enjoy can confirm this bug is lasting for months ... The two reports print the same thing, when they're created as explained by Karim
prueba modificando los ficheros: __init__.py y account_print_invoice_new.py
Hello Thanks it's work for me , but the problem in traslation i can not translate my second invoice which directory is same as invoice directory
I have noticed that when you use the default invoices, it will be translated into the language of the language you have defined the user. I have not checked what will happen if you have a customer/company in language A and the invoice address is with someone in language B.
I expect that it will use the language depending on whom you send the various reports/orders.
In order for the documents to be translated, you have to load / import the appropriate language.
Settings -> Load a Translation.
After this, you can specify another language on the user, so the system might try to translate (using strings in the database, don't expect magic) the standard documents.
If you have customized documents and/or modified text, you have to add those strings to the database as well. I have not done that yet, so I cannot give you any answers/hints regarding this issue.
This is really a nice tutorial but I got problem (Report has not been downloaded Detail: URL seems to be an unsupported one) when I tried to modify new report through openoffice(modify existing report). I just copy purchase_requisition.rml file and paste somewhere else and rename this file comparative_statement.rml and again paste this file in report folder of purchase requisition and follow the procedure that you have mentioned above, now I am able to see two option under print button both are working but my question is how to modify new report comparative statement?
Hello Thanks it's work for me , but the problem in traslation i can not translate my second invoice which directory is same as invoice directory
It is not that much complex to define multiple invoices for the invoice, you might not have seen module that already support printing of multiple invoices with configuration. of course if your own custom format installed it will detect and print up on the configuration
May be it is not direct solution but it gives you best example to keep and print invoices in multiple layouts.
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/multiple-invoice-layout-8237 | CC-MAIN-2018-47 | refinedweb | 1,842 | 62.88 |
Creating an Application in Kivy: Part 2
This article continues the tutorial we started in Part 1. In the first part, we set up a Kivy project and developed a very basic Kivy application. We also discussed version control to aid in project management. In this part, we’ll be designing an actual user interface for a Jabber client and begin to implement it in the KV language.
Make sure you have completed part 1, or if you want to skip the preliminaries, you can clone the end_part_one tag of the Orkiv git repository and start from there. It’s probably a good idea to name a new branch for your working changes so your master branch doesn’t diverge from my upstream repository. Remember to activate the virtualenv you created in Part 1 (or create one if you’re starting from the git clone.)
git clone git checkout end_part_one git checkout -b working_changes source venv/bin/activate
Table Of Contents
Here are links to other parts of the tutorial. I’m sorry for the navigation faux pas; blogs are not the best interface for multi-part articles.
- Part 1: Introduction to Kivy
- Part 2: Creating a form
- Part 3: Interacting with widgets and the user
- Part 4: Code and Interface Improvements
- Part 5: Rendering a Buddy List
- Part 6: ListView Interaction
- Part 7: Receiving messages and interface fixes
- Part 8: Width based layout
- Part 9: Deploying your Kivy application
Interface Design
In general, before developing a user interface, it is a good idea to know what you want it to look like. I see this project having three main views. When the user first opens the application, they’ll see an Account Details screen to provide their jabber server and login credentials. We won’t bother with saving these details since this tutorial series is focused on Kivy interface development, not persistence. Once they have logged in, the other two views are a Buddy List and the individual Chat Window.
I would like to develop the app to show the buddy list and chat windows side by side if the screen is large enough (eg: a laptop screen or large tablet in horizontal orientation), but only one window at a time on small screens. It is very important to evaluate screen size when developing cross platform applications; it is generally not desirable or feasible to render the same view on large monitors and small phones. We’ll look at this feature in later tutorials, but knowing that we want to plan for it now will affect how we implement our design.
All of these windows are pretty simple. In this second part, we will focus on the account details screen. It will be a simple form with labels on the left and fields for entering the various details on the right. The fields covered will include server, username, and password. Below these fields will be a Login button. Normally I’d sketch the interface on a piece of paper, but since this looks like every other Jabber client on the market, I don’t think it’s necessary.
The Account Details Form Widget
In Kivy, virtually every object that gets displayed on the screen is a widget. Just a few examples include:
- The label we rendered in the first tutorial
- The text input fields and buttons we’ll render in this tutorial
- Layout classes that contain other widgets and decide where they should be displayed
- Complicated tree views such as file pickers
- Movie and photo renderers
- Tabbed boxes that display different widgets depending on the selected tab
It is easy to make custom widgets, and to access all widgets, whether custom or otherwise, from KV language files. We’ll be creating a new widget to contain our entire Account Details form. Start by adding a new import and class to
__main__.py:
from kivy.uix.boxlayout import BoxLayout class AccountDetailsForm(BoxLayout): pass
Running the code with this addition won’t change anything in the output, since the newly created widget hasn’t been added to the root window. However, there are a few things we need to discuss before we change the KV language file to use this widget. You might be asking yourself why we created a new widget instead of adding a
BoxLayout widget (whatever that is!) directly to the root of the KV language file
orkiv.kv. While it would have been trivial to do this, it would have made putting a new widget (such as the Buddy List) on the root screen more difficult. Further, when it comes time to attach events to the Login button, we can make it a method of this new class, where it makes the most sense.
The
BoxLayout is a very simple widget that simply takes the available space and places all the child widgets in it from left to right or top to bottom. By default, each widget gets an equal amount of space, but it’s also possible to make certain widgets have specific sizes or percentages of space or to expand to fill available area.
BoxLayout is one of several kinds of layouts available in Kivy. A layout is simply a container widget that holds other widgets and knows how to position those child widgets in a specific pattern. We’ll be seeing a
GridLayout shortly. You can read about other Kivy layouts in the Kivy API Reference.
Let’s edit
orkiv.kv to render this new widget as the child form instead of the label we used before. We’ll also add a couple labels to the
AccountDetailsForm class so you can see the relationship between root widgets and classes in the KV Language:
AccountDetailsForm: <AccountDetailsForm>: Label: text: 'Hello World' Label: text: 'Another World'
There’s a couple things going on here. The root widget of the
Orkiv app is defined as a
AccountDetailsForm. This is followed by a colon in case we wanted to add other child widgets to the object, but in this case, it’s just followed by a blank line. Then we define the structure of the child widgets of the
AccountDetailsForm class itself. We know it’s a class and not a root widget because the class name is surrounded in angle brackets (< and >). Further, one app can only have one root widget. We just defined that root to be pointing at a single
AccountDetailsForm. However, note that a class can be styled once and added in more than one place. Just as our
AccountDetailsForm has two labels, it would be possible (though silly, from an interface perspective) to create a container widget that contains two
AccountDetailsForms. The point is, an
AccountDetailsForm, once its layout has been defined, can be used just like any of the built-in widgets supplied with Kivy.
If you run
python orkiv now, it will render the two labels side by side, each taking a full half the window. Note that there are actually three widgets being rendered; first, the
AccountDetailsForm (which is a
BoxLayout by inheritance) is rendered to fill the whole screen, and then it lays out the two labels as child widgets.
However, that’s not the AccountDetailsForm we were looking for! Let’s create our first nontrivial Kivy Language class. Replace the
class in your
orkiv.kv with the following:
<AccountDetailsForm>: orientation: "vertical" GridLayout: cols: 2 Label: text: "Server" TextInput: Label: text: "Username" TextInput: Label: text: "Password" TextInput: password: True Button: text: "Login"
It’s time to discuss just how the Kivy language lays things out. In my mind, it uses a box model similar to HTML, except instead of ugly HTML tags, indentation is used to specify what widgets go inside other widgets. Also, unlike HTML, style information is included in the
.kv file instead of an external
.css file. Though it’s not a hard and fast rule, style information (called properties in Kivy) typically begins with a lowercase letter, while child widgets start with a capital.
Look at the first level of indentation under the
<AccountDetailsForm> declaration. There are three items;
orientation,
GridLayout, and
Button. The former counts as “style information”. Remember that the
AccountDetailsForm class extends BoxLayout. One of the attributes on BoxLayout is “orientation”; we are telling BoxLayout here that we want a vertical layout.
This vertical box layout then contains two widgets, a
GridLayout and a
Button. The GridLayout spaces all it’s children equally. We just have to tell it that there are 2 columns (the
cols property) and then start adding our objects, which are displayed from left to right and wrap to the next row in the grid after every two widgets. We add
Labels and
TextInputs. Each label has a
text property that we set using a further level of indent. The
TextInput objects don’t require any extra properties except the password.
Later, we’ll have to give these objects some identifiers so we can refer to them in code. For this initial prototyping stage, we can start with the bare minimum. If we render the above example, we end up with a recognizable, but rather ugly form:
Restricting sizes
Let’s try to make the form a little less ugly:
<AccountDetailsForm>: orientation: "vertical" height: "200dp" size_hint_y: None GridLayout: cols: 2 row_default_height: "40dp" row_force_default: True spacing: "10dp" padding: "10dp" Label: text: "Server" TextInput: Label: text: "Username" TextInput: Label: text: "Password" TextInput: password: True Button: size_hint_y: None height: "40dp" text: "Login"
All we’ve done here is add some styling information to make the layout a little more friendly. This can be complicated as we want the app to look good on a variety of devices at a variety of resolutions and screen sizes. The main thing is to ensure all the widgets have a known height. As you might guess, this can be accomplished by adding a
height property to each of the widgets. However, doing this alone will not work because
BoxLayout likes to think of itself as in charge of deciding what size a widget should be. Without any styling, heights in a vertical
BoxLayout are calculated as the number of widgets divided by the available screen space. However, it’s possible to tell
BoxLayout to make certain widgets take a higher percentage of available space by giving it a
size_hint_y attribute, which should be a float and defaults to 1.0. Unfortunately, for textboxes and buttons, percentages don’t really make a lot of sense, since we have no idea what size the window or screen of a particular advice is going to be, but we do know we want them to be about the same height on each screen.
So in addition to setting the
height attribute, we also have to set
size_hint_y to
None for those widgets to prevent
BoxLayout from ignoring the
height property and laying things out by percentages instead.
You’ll also note that we are specifying the heights using strings that end in the suffix “dp”. It’s possible to provide integer values here, which would be interpreted as the number of pixels high the button is. However, due to the massive variance in screen resolutions on modern devices, it’s not really feasible to use pixels as a measurement. A login button that is 40 pixels high and looks good on a desktop monitor would look very small, indeed, on a “retina” display tablet.
Therefore, Kivy provides us with the concept of “display pixels”; hence the “dp” in the strings. Display pixels should be about the same size on every device; on a standard desktop monitor they generally map to a single pixel, but on higher density displays, they will be multiplied by a scaling factor. There are other metric properties such as
cm or
in that you can use, but I generally find it most convenient to think in display pixels.
Note also that instead of supplying heights for each of the
Label and
TextInput widgets inside the grid layout, we cheated and used the
row_default_height attribute so all rows have the same height. For this to work, you also have to set
row_force_default to True.
Finally we added
spacing and
padding properties to the
GridLayout to add a 10dp space between child widgets and a “frame” around the whole
GridLayout as well. If we run this example, it looks like this:
There’s one more thing I’d like to do before ending this part of the tutorial. As you can see above, the form is showing up at the bottom of the window, no matter what size the window is. That might look a bit bizarre on a tablet or even phone screen. It would be better if the entire form was anchored to the top of the window.
As an exercise, take a few moments to experiment (remember to use a different git branch!) and see if you can figure out how to move the form to the top by yourself. The next paragraph contains some hints if you get stuck, and the working code is linked after that. (I’m not about to tell you not to cheat, since it really depends what your personal goals are in reading this tutorial.)
There are probably multiple ways to do this, and I’m not even certain my solution is the best one. But I suggest making the
AccountDetailsForm into an AnchorLayout and anchor a child
BoxLayout to the top of the form. Note that you’ll have to change both files to make this happen.
If you’re still confused, have a look at the full changeset at the changeset on github.
That’s it for part 2 of this tutorial, which focused on laying out widgets in the KV Language. In part 3, we’ll figure out how to log into an XMPP library and render a buddy list. Note that I don’t actually know how to do this, so we’ll have to figure it out together!!
[...] Arch Linux Community on Gittip Creating an Application In Kivy: Part 2 [...]
Kivy looks awesome. Only thing it is missing is native themes. I think that is a blocker for people trying to write apps for any platform. QT really shines there, QT apps look like Mac apps on a Mac and KDE apps on KDE and Gtk apps on Gnome. Yes, QT is not perfect when it comes to native styling but it’s close. I think Kivy could really become a great challenger to traditional (Gtk/QT) toolkits if it supported native styling in some way.
I’m not overly familiar with QT, but I did find PyQT to be “less pythonic” than I would like. I’ve always considered GUI toolkits to be a necessary evil, and none of them were ideal. However, Kivy is truly a joy to work with from a developer perspective. I’m amazed how often I write code and run it to find that it “just works” without having to reference the documentation.
The default Kivy theme fits in with the android platform, though it isn’t a pixel for pixel native representation. On other devices it doesn’t fit in at all! However, Kivy does support advanced low-level theming (see), and I think this mechanism is still being improved. I would not be surprised to see native themes in Kivy’s future.
Just wanted to say that I’m still loving this tutorial and *really* appreciate that you’re building a non-trivial app w/ a .kv file, can’t wait for the next part!
I’m glad you’re enjoying it! I’m also enjoying writing it.
I’m planning to release the parts on a one per week(ish) schedule.
Took up your call to experiment.
A StackLayout also works to move the widgets up:
from kivy.uix.stacklayout import StackLayout
class MainForm(StackLayout):
pass
class AccountDetailsForm(BoxLayout):
pass
…
MainForm:
:
orientation: “lr-tb”
AccountDetailsForm:
orientation: “vertical”
…
[...] « Creating an Application In Kivy: Part 2 [...]
[...] article continues a series on creating a Kivy application. At the end of Part 2, we had a basic form for entering Jabber login details. In this part, we’ll hook up the login [...]
[...] Part 2: A basic KV Language interface [...]
[...] Part 2: A basic KV Language interface [...]
[...] Part 2: A basic KV Language interface [...]
[...] Part 2: A basic KV Language interface [...]
[...] Part 2: A basic KV Language interface [...] | http://archlinux.me/dusty/2013/06/19/creating-an-application-in-kivy-part-2/ | CC-MAIN-2014-42 | refinedweb | 2,728 | 60.85 |
Ticket #1486 (closed bug: fixed)
utcToLocalTime converting in the wrong direction on Windows
Description (last modified by igloo) (diff)
I found a strange UTC to Local Time conversion bug on the Windows version of GHC 6.6.1.
Code to reproduce it:
import Monad import Data.Time import Locale main = do t <- (liftM2 utcToLocalTime) getCurrentTimeZone getCurrentTime let s = formatTime defaultTimeLocale "%r" t putStrLn s z <- (liftM timeZoneName) getCurrentTimeZone putStrLn z
Running this program around 04:35 PM I get the following results
On Linux (a recent Ubuntu with GHC 6.6.1 compiled from source)
04:35:48 PM EDT
On Windows (GHC 6.6.1 from installer) I get
12:36:04 AM Eastern Daylight Time
Looks like the Windows version is counting in the wrong direction. I made some tests in GHCi on both machines an get this:
On Windows:
Prelude> :m Monad Data.Time Locale Prelude Locale Data.Time Monad> z <- getCurrentTimeZone Eastern Daylight Time Prelude Locale Data.Time Monad> timeZoneMinutes z 240
On Linux: (same commands)
Prelude Locale Data.Time Monad> timeZoneMinutes z -240
Cheers,
Olivier.
Attachments
Change History
Note: See TracTickets for help on using tickets. | http://hackage.haskell.org/trac/ghc/ticket/1486 | CC-MAIN-2013-20 | refinedweb | 191 | 55.34 |
Is there a way to specify the GPU to use when using a DataLoader with pin_memory = True?
I’ve tried using
torch.cuda.set_device(device)
and
with torch.cuda.device(gpu_id):
#DataLoader
but nvidia-smi shows that the GPU used is always the first available.
I think I could use:
CUDA_VISIBLE_DEVICES=x
to make the target GPU be the only one available in the notebook but I’d rather not.
Is there a way to specify the GPU to use when using a DataLoader with pin_memory = True?
afaik, pinned memory is not specific to any GPU. It just puts data in the locked page in host CPU memory. The destination is specified by .cuda(device)
I thought that too but I’ve noticed that when I pin it, some stuff get loaded on the GPU according to nvidia-smi.
I’ve tried changing the device before pinning it as in:
import torch
x_tensor = torch.FloatTensor(1)
with torch.cuda.device(2):
x_tensor.pin_memory()
and I got this:
I don’t know the inner working of pinning memory but this led me to believe some preparations take place on the GPU as well (setting the device before starting a DataLoader doesn’t seem to affect it).
If I set the .cuda(device) on model/inputs they get sent to the correct GPU but that memory usage from pinning persists until I finish so I decided to ask on here for some opinions
I played with different sized tensors, the allocated memory is always constant. It is very likely that some context is created when you do so. So don’t worry too much about it.
What pytorch version are you using? Pinning to specific GPU was merged recently before that context was always initialized on device 0.
It is not such a small deal, on an 8 GPU system 7 unnecessary contexts can be created, each taking ~ 400 MB, together taking ~ 3 GB of memory. | https://discuss.pytorch.org/t/pin-memory-to-specific-gpu-in-dataloader/11908 | CC-MAIN-2022-21 | refinedweb | 324 | 64.71 |
Closed Bug 560580 Opened 11 years ago Closed 10 years ago
pref sync cleanup
Categories
(Firefox :: Sync, defect)
Tracking
()
2.0
People
(Reporter: mconnor, Assigned: philikon)
References
Details
(Whiteboard: [qa-])
Attachments
(1 file, 3 obsolete files)
from bug 548385: * don't sync pref type (Preferences.js solves this for us) * make storage just prefs[prefname] = value and have a simpler data format (this would be a storage version bump, but that's not especially terrible for prefs) * need to solve whether we sync prefs if the local client doesn't have that pref enabled for sync (if we do, we should enable that pref for sync in future, so it's bidirectional) * Using Preferences.js would make this code much more compact: _prefs: new Preferences(); _getAllPrefs: function () { let values = {}; let toSync = this._syncPrefs; for (let i = 0; i < toSync.length; i++) { if (!this._prefs.get(WEAVE_SYNC_PREFS + toSync[i]), false) continue; let val = this._prefs.get(toSync[i], ""); if (val) values[toSync[i]] = val; } return values; }, _setAllPrefs: function(values) { for (let pref in values) { if (!this._prefs.get(WEAVE_SYNC_PREFS + toSync[i]), false) continue; try { this._prefs.set(pref, values[pref]); catch(e) { this._log.trace("Failed to set pref: " + pref + " Reason: " + e); } } }
Since we're bumping the global storageVersion to 4 in Sync 1.6, we have an opportunity to redo the prefs engine and bump its storageVersion to 2: * do not sync the pref type (bug 558890) * handle some error scenarios more gracefully (bug 579347) * use AppInfo.ID as the GUID so that each Mozilla app uses its own namespace (bug 598968) * never ever do disk I/O (bug 609395) The latter ones are the motivator here since we want them for Firefox + Fennec 4.
Assignee: nobody → philipp
In this patch: * We no longer sync the pref type (bug 558890), all hail Preference.js! * Use AppInfo.ID as the GUID so that each Mozilla app uses its own namespace (bug 598968). This and the previous change are an incompatible change to the prefs storage format, so engine.version was upped from 1 to 2. * We never ever do disk I/O (bug 609395) akin to the tabs engine. Unlike the tabs engine, we store the dirty state (tracker.modified) in a preference so it's persisted across sessions. * We now also sync the prefs that determine which prefs are to be synced (yo dawg!). That means when you switch off persona sync on one machine it'll propagate to all machines. Predictability FTW! * Also, the way we determine whether a pref should be included in the record is now much saner. * The tracker score increment now actually is what the comment said (25 points). Changing the prefs that determine which prefs are to be synced ups the score by 100.
Requesting blocking2.0 for beta8 as we want to land this at the same time as simplified crypto (bug 603489)
blocking2.0: --- → ?
Ensure we test PrefEngine.getChangedIDs(). No code change, just moar tests.
Attachment #491353 - Attachment is obsolete: true
Attachment #491370 - Flags: review?(mconnor)
Comment on attachment 491370 [details] [diff] [review] v1.1 >diff --git a/services/sync/modules/engines/prefs.js b/services/sync/modules/engines/prefs.js >+ if (aData.slice(0, WEAVE_SYNC_PREFS.length) == WEAVE_SYNC_PREFS) You do this in a few places. Do this instead (faster/easier to read) if (aData.indexOf(WEAVE_SYNC_PREFS) == 0) Otherwise, way to slip this in under the wire...
Attachment #491370 - Flags: review?(mconnor) → review+
(In reply to comment #6) > >+ if (aData.slice(0, WEAVE_SYNC_PREFS.length) == WEAVE_SYNC_PREFS) > > You do this in a few places. Do this instead (faster/easier to read) > > if (aData.indexOf(WEAVE_SYNC_PREFS) == 0) Ah right, forgot that indexOf() can also take a substring. If only strings had startswith()/endswith() methods...
Addressed mconnor's review comment. This is ready for landing in fx-sync, but should be coordinated with landing of bug 603489
Attachment #491370 - Attachment is obsolete: true
Fix + test for a small bug that prevented services.sync.prefs.sync.* preferences from being applied.
Attachment #492243 - Attachment is obsolete: true
Status: NEW → RESOLVED
Closed: 10 years ago
Resolution: --- → FIXED
Whiteboard: [qa-]
Belated blocking+.
blocking2.0: ? → beta8+
Component: Firefox Sync: Backend → Sync
Product: Cloud Services → Firefox | https://bugzilla.mozilla.org/show_bug.cgi?id=560580 | CC-MAIN-2020-45 | refinedweb | 693 | 66.44 |
Unformatted text preview: Notes on Diffy Qs
Differential Equations for Engineers by Jiˇ í Lebl
r
July 16, 2010 2 A
Typeset in LTEX. Copyright c 2008–2010 Jiˇí Lebl
r This work is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0
United States License. To view a copy of this license, visit
licenses/by-nc-sa/3.0/us/ or send a letter to Creative Commons, 171 Second Street, Suite
300, San Francisco, California, 94105, USA.
You can use, print, duplicate, share these notes as much as you want. You can base your own notes
on these and reuse parts if you keep the license the same. If you plan to use these commercially (sell
them for more than just duplicating cost), then you need to contact me and we will work something
out. If you are printing a course pack for your students, then it is fine if the duplication service is
charging a fee for printing and selling the printed copy. I consider that duplicating cost.
During the writing of these notes, the author was in part supported by NSF grant DMS-0900885.
See for more information (including contact information). Contents
Introduction
0.1 Notes about these notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
0.2 Introduction to differential equations . . . . . . . . . . . . . . . . . . . . . . . . .
1 2 3 First order ODEs
1.1 Integrals as solutions . . . . . . . . . . .
1.2 Slope fields . . . . . . . . . . . . . . . .
1.3 Separable equations . . . . . . . . . . . .
1.4 Linear equations and the integrating factor
1.5 Substitution . . . . . . . . . . . . . . . .
1.6 Autonomous equations . . . . . . . . . .
1.7 Numerical methods: Euler’s method . . . .
.
.
.
.
.
. .
.
.
.
.
.
. Higher order linear ODEs
2.1 Second order linear ODEs . . . . . . . . . .
2.2 Constant coefficient second order linear ODEs
2.3 Higher order linear ODEs . . . . . . . . . . .
2.4 Mechanical vibrations . . . . . . . . . . . . .
2.5 Nonhomogeneous equations . . . . . . . . .
2.6 Forced oscillations and resonance . . . . . . .
.
.
.
.
.
. .
.
.
.
.
. Systems of ODEs
3.1 Introduction to systems of ODEs . . . . . . . .
3.2 Matrices and linear systems . . . . . . . . . . .
3.3 Linear systems of ODEs . . . . . . . . . . . .
3.4 Eigenvalue method . . . . . . . . . . . . . . .
3.5 Two dimensional systems and their vector fields
3.6 Second order systems and applications . . . . .
3.7 Multiple eigenvalues . . . . . . . . . . . . . .
3.8 Matrix exponentials . . . . . . . . . . . . . . .
3.9 Nonhomogeneous systems . . . . . . . . . . .
3 .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
. .
.
.
.
.
. .
.
.
.
.
.
.
.
. 5
5
7 .
.
.
.
.
.
. 13
13
18
22
27
32
36
41 .
.
.
.
.
. 47
47
51
57
62
70
76 .
.
.
.
.
.
.
.
. 83
83
87
95
99
105
110
119
124
131 4
4 CONTENTS and the Laplacian . . . . . .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. .
.
.
.
.
.
.
.
. 143
143
151
160
168
175
181
191
198
204 5 Eigenvalue problems
211
5.1 Sturm-Liouville problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
5.2 Application of eigenfunction series . . . . . . . . . . . . . . . . . . . . . . . . . . 219
5.3 Steady periodic solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 6 The Laplace transform
229
6.1 The Laplace transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
6.2 Transforms of derivatives and ODEs . . . . . . . . . . . . . . . . . . . . . . . . . 236
6.3 Convolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 Further Reading 247 Index 249 Introduction
0.1 Notes about these notes This book originated from my class notes for teaching Math 286, differential equations, at the
University of Illinois at Urbana-Champaign in fall 2008 and spring 2009. It is a first course on
differential equations for engineers. The standard book for the course is Edwards and Penney,
Differential Equations and Boundary Value Problems [EP], fourth edition. The structure of these
present notes, therefore, reflects the structure of [EP], at least as far as the material that is covered in
the course. Many examples and applications are taken more or less from this book, though they also
appear in many other sources, of course. Other books I have used as sources of information and
inspiration are E.L. Ince’s classic (and inexpensive) Ordinary Differential Equations [I], and also
my undergraduate textbooks, Stanley Farlow’s Differential Equations and Their Applications [F],
which is now available from Dover, and Berg and McGregor’s Elementary Partial Differential
Equations [BM]. See the Further Reading chapter at the end of the book.
I taught the course with the IODE software (). IODE
is a free software package that is used either with Matlab (proprietary) or Octave (free software).
Projects and labs from the IODE website are referenced throughout the notes. They need not be
used for this course, but I think it is better to use them. The graphs in the notes were made with
the Genius software (see). I have used Genius in class to
show essentially these and similar graphs.
These notes are available from. Check there for any
A
possible updates or errata. The LTEX source is also available from the same site for possible
modification and customization.
I would like to acknowledge Rick Laugesen. I have used his handwritten class notes the first
time I taught the course. My organization of these present notes, and the choice of material covered,
is heavily influenced by his class notes. Many examples and computations are taken from his
notes., and
probably others I have forgotten. Finally I would like to acknowledge NSF grant DMS-0900885.
The organization of these notes to some degree requires that they be done in order. Hence, later
5 6 INTRODUCTION chapters can be dropped. The dependence of the material covered is roughly given in the following
diagram:
Introduction
Chapter 1
Chapter 2
w ' Chapter 6 Chapter 3
w Chapter 4
Chapter 5
There are some references in chapters 4 and 5 to material from chapter 3 (some linear algebra),
but these references are not absolutely essential and can be skimmed over, so chapter 3 can safely be
dropped, while still covering chapters 4 and 5. The notes are done for two types of courses. Either
at 4 hours a week for a semester (Math 286 at UIUC):
Introduction, chapter 1 (plus the two IODE labs), chapter 2, chapter 3, chapter 4, chapter 5 (or 6).
Or a shorter version (Math 285 at UIUC) of the course at 3 hours a week for a semester:
Introduction, chapter 1 (plus the two IODE labs), chapter 2, chapter 4, (maybe chapter 5 or 6).
IODE need not be used for either version. If IODE is not used, some additional material may
need to be covered instead.
The lengths of the chapter on Laplace transform ( chapter 6) and the chapter on Sturm-Liouville
( chapter 5) are approximately the same and are interchangable. Laplace transform is not normally
covered at UIUC 285/286. I think it is essential that any notes on differential equations at least
mention the Laplace transform. 0.2. INTRODUCTION TO DIFFERENTIAL EQUATIONS 0.2 7 Introduction to differential equations Note: more than 1 lecture, §1.1 in [EP] 0.2.1 Differential equations The laws of physics are generally written down as differential equations. Therefore, all of science
and engineering use differential equations to some degree. Understanding differential equations is
essential to understanding almost anything you will study in your science and engineering classes.
You can think of mathematics as the language of science, and differential equations are one of
the most important parts of this language as far as science and engineering are concerned. As
an analogy, suppose that all your classes from now on were given in Swahili. Then it would be
important to first learn Swahili, otherwise you will have a very tough time getting a good grade in
your other classes.
You have already seen many differential equations without perhaps knowing about it. And
you have even solved simple differential equations when you were taking calculus. Let us see an
example you may not have seen:
dx
+ x = 2 cos t.
(1)
dt
Here x is the dependent variable and t is the independent variable. Equation (1) is a basic example
of a differential equation. In fact it is an example of a first order differential equation, since it
involves only the first derivative of the dependent variable. This equation arises from Newton’s law
of cooling where the ambient temperature oscillates with time. 0.2.2 Solutions of differential equations Solving the differential equation means finding x in terms of t. That is, we want to find a function
of t, which we will call x, such that when we plug x, t, and dx into (1), the equation holds. It is the
dt
same idea as it would be for a normal (algebraic) equation of just x and t. We claim that
x = x(t) = cos t + sin t
is a solution. How do we check? We simply plug x into equation (1)! First we need to compute
We find that dx = − sin t + cos t. Now let us compute the left hand side of (1).
dt dx
.
dt dx
+ x = (− sin t + cos t) + (cos t + sin t) = 2 cos t.
dt
Yay! We got precisely the right hand side. But there is more! We claim x = cos t + sin t + e−t is also
a solution. Let us try,
dx
= − sin t + cos t − e−t .
dt 8 INTRODUCTION Again plugging into the left hand side of (1)
dx
+ x = (− sin t + cos t − e−t ) + (cos t + sin t + e−t ) = 2 cos t.
dt
And it works yet again!
So there can be many different solutions. In fact, for this equation all solutions can be written in
the form
x = cos t + sin t + Ce−t
for some constant C . See Figure 1 for the graph of a few of these solutions. We will see how we
can find these solutions a few lectures from now.
It turns out that solving differential equations
can be quite hard. There is no general method
that solves any given differential equation. We
will generally focus on how to get exact formulas
for solutions of certain differential equations, but
we will also spend a little bit of time on getting
approximate solutions.
For most of the course we will look at ordinary differential equations or ODEs, by which we
mean that there is only one independent variable
and derivatives are only with respect to this one
variable. If there are several independent variables, we will get partial differential equations or
PDEs. We will briefly see these near the end of
Figure 1: Few solutions of dx + x = 2 cos t.
dt
the course.
Even for ODEs, which are very well understood, it is not a simple question of turning a crank to get answers. It is important to know when
it is easy to find solutions and how to do so. Even if you leave much of the actual calculations
to computers in real life, you need to understand what they are doing. For example, it is often
necessary to simplify or transform your equations into something that a computer can actually.
0 1 2 3 4 5 3 3 2 2 1 1 0 0 -1 -1 0 0.2.3 1 2 3 4 5 Differential equations in practice So how do we use differential equations in science and engineering? First, we have some real
world problem that we wish to understand. We make some simplifying assumptions and create a 0.2. INTRODUCTION TO DIFFERENTIAL EQUATIONS 9 mathematical model. That is, we translate the real world situation into a set of differential equations.
Then we apply mathematics to get some sort of a mathematical solution. There is still something
left to do. We have to interpret the results. We have to figure out what the mathematical solution
says about the real world problem we started with.
Learning how to formulate the mathematical
Real world problem
model and how to interpret the results is what
your physics and engineering classes do. In this
abstract
interpret
course we will focus mostly on the mathematical
analysis. Sometimes we will work with simple real
solve
Mathematical
Mathematical
world examples, so that we have some intuition
model
solution
and motivation about what we are doing.
Let us look at an example of this process. One of the most basic differential equations is the
standard exponential growth model. Let P denote the population of some bacteria on a Petri dish.
Let us suppose that there is enough food and enough space. Then the rate of growth of bacteria will
be proportional to the population. I.e. a large population grows quicker. Let t denote time (say in
seconds). Our model will be
dP
= kP,
dt
for some positive constant k > 0.
Example 0.2.1: Suppose there are 100 bacteria at time 0 and 200 bacteria at time 10s. How many
bacteria will there be 1 minute from time 0 (in 60 seconds)?
First we have to solve the equation. We claim that a solution is given by
P(t) = Cekt ,
where C is a constant. Let us try.
dP
= Ckekt = kP.
dt
And it really is a solution.
OK, so what now? We do not know C and we do not know k. But we know something. We
know that P(0) = 100, and we also know that P(10) = 200. Let us plug these conditions in and see
what happens.
100 = P(0) = Cek0 = C,
200 = P(10) = 100 ek10 .
Therefore, 2 = e10k or ln 2
10 = k ≈ 0.069. So we know that
P(t) = 100 e(ln 2)t/10 ≈ 100 e0.069t . At one minute, t = 60, the population is P(60) = 6400. See Figure 2 on the next page. 10 INTRODUCTION Let us talk about the interpretation of the results. Does this mean that there must be exactly
6400 bacteria on the plate at 60s? No! We have made assumptions that might not be exactly true.
But if our assumptions are reasonable, then there will be approximately 6400 bacteria. Also note
that in real life P is a discrete quantity, not a real number. However, our model has no problem
saying that for example at 61 seconds, P(61) ≈ 6859.35.
Normally, the k in P = kP will be known, and
you will want to solve the equation for different
initial conditions. What does that mean? Suppose
k = 1 for simplicity. Now suppose we want to
solve the equation dP = P subject to P(0) = 1000
dt
(the initial condition). Then the solution turns out
to be (exercise)
P(t) = 1000 et . 0 10 20 30 40 50 60 6000 6000 5000 5000 4000 4000 3000 3000 2000 2000 We will call P(t) = Cet the general solution,
as every solution of the equation can be written
in this form for some constant C . Then you will
need an initial condition to find out what C is to
find the particular solution we are looking for. Figure 2: Bacteria growth in the first 60 secGenerally, when we say “particular solution,” we onds.
just mean some solution.
1000 1000 0 0 0 10 20 30 40 50 60 Let us get to what we will call the four fundamental equations. These,
dy
= ky,
dx
for some constant k > 0. Here y is the dependent and x the independent variable. The general
solution for this equation is
y( x) = Cekx .
We have already seen that this is a solution above with different variable names.
dy
= −ky,
dx
for some constant k > 0. The general solution for this equation is
y( x) = Ce−kx . 0.2. INTRODUCTION TO DIFFERENTIAL EQUATIONS 11 Exercise 0.2.1: Check that the y given is really a solution to the equation.
Next, take the second order differential equation
d2 y
= −k2 y,
dx2
for some constant k > 0. The general solution for this equation is
y( x) = C1 cos(kx) + C2 sin(kx).
Note that because we have a second order differential equation, we have two constants in our general
solution.
Exercise 0.2.2: Check that the y given is really a solution to the equation.
And finally, take the second order differential equation
d2 y
= k2 y,
2
dx
for some constant k > 0. The general solution for this equation is
y( x) = C1 ekx + C2 e−kx ,
or
y( x) = D1 cosh(kx) + D2 sinh(kx).
For those that do not know, cosh and sinh are defined by
e x + e− x
,
2
e x − e− x
sinh x =
.
2 cosh x = These functions are sometimes easier to work with than exponentials. They have some nice familiar
d
properties such as cosh 0 = 1, sinh 0 = 0, and dx cosh x = sinh x (no that is not a typo) and
d
sinh x = cosh x.
dx
Exercise 0.2.3: Check that both forms of the y given are really solutions to the equation.
An interesting note about cosh: The graph of cosh is the exact shape a hanging chain will make
and it is called a catenary. Contrary to popular belief this is not a parabola. If you invert the graph
of cosh it is also the ideal arch for supporting its own weight. For example, the gateway arch in
Saint Louis is an inverted graph of cosh (if it were just a parabola it might fall down). This formula
is actually inscribed inside the arch:
y = −127.7 ft · cosh( x/127.7 ft) + 757.7 ft. 12 INTRODUCTION 0.2.4 Exercises Exercise 0.2.4: Show that x = e4t is a solution to x − 12 x + 48 x − 64 x = 0.
Exercise 0.2.5: Show that x = et is not a solution to x − 12 x + 48 x − 64 x = 0.
Exercise 0.2.6: Is y = sin t a solution to dy 2
dt = 1 − y2 ? Justify. Exercise 0.2.7: Let y + 2y − 8y = 0. Now try a solution of the form y = erx for some (unknown)
constant r. Is this a solution for some r? If so, find all such r.
Exercise 0.2.8: Verify that x = Ce−2t is a solution to x = −2 x. Find C to solve for the initial
condition x(0) = 100.
Exercise 0.2.9: Verify that x = C1 e−t + C2 e2t is a solution to x − x − 2 x = 0. Find C1 and C2 to
solve for the initial conditions x(0) = 10 and x (0) = 0.
Exercise 0.2.10: Using properties of derivatives of functions that you know try to find a solution to
( x )2 + x2 = 4.
Exercise 0.2.11: Solve:
a) dA
= −10A, A(0) = 5.
dt b) dH
= 3H, H (0) = 1.
dx c) dy
= 4y, y(0) = 0, y (0) = 1.
dx d) dx
= −9 x, x(0) = 1, x (0) = 0.
dy Chapter 1
First order ODEs
1.1 Integrals as solutions Note: 1 lecture (or less), §1.2 in [EP]
A first order ODE is an equation of the form
dy
= f ( x, y),
dx
or just
y = f ( x, y).
In general, there is no simple formula or procedure one can follow to find solutions. In the next few
lectures we will look at special cases where solutions are not difficult to obtain. In this section, let
us assume that f is a function of x alone, that is, the equation is
y = f ( x). (1.1) We could just integrate (antidifferentiate) both sides with respect to x.
y ( x) dx = f ( x) dx + C, that is
y( x) = f ( x) dx + C. This y( x) is actually the general solution. So to solve (1.1), we find some antiderivative of f ( x) and
then we add an arbitrary constant to get the general solution.
Now is a good time to discuss a point about calculus notation and terminology. Calculus
textbooks muddy the waters by talking about integral as primarily the so-called indefinite integral.
13 14 CHAPTER 1. FIRST ORDER ODES The indefinite integral is really the antiderivative (in fact the whole one-parameter family of
antiderivatives). There really exists only one integral and that is the definite integral. The only
reason for the indefinite integral notation is that we can always write an antiderivative as a (definite)
integral. That is, by the fundamental theorem of calculus we can always write f ( x) dx + C as
x f (t) dt + C.
x0 Hence the terminology to integrate when we may really mean to antidifferentiate. Integration is
just one way to compute the antiderivative (and it is a way that always works, see the following
examples). Integration is defined as the area under the graph, it only happens to also compute
antiderivatives. For sake of consistency, we will keep using the indefinite integral notation when we
want an antiderivative, and you should always think of the definite integral.
Example 1.1.1: Find the general solution of y = 3 x2 .
Elementary calculus tells us that the general solution must be y = x3 + C . Let us check: y = 3 x2 .
We have gotten precisely our equation back.
Normally, we also have an initial condition such as y( x0 ) = y0 for some two numbers x0 and y0
( x0 is usually 0, but not always). We can then write the solution as a definite integral in a nice way.
Suppose our problem is y = f ( x), y( x0 ) = y0 . Then the solution is
x y( x ) = f ( s) ds + y0 . (1.2) x0 Let us check! We compute y = f ( x) (by fundamental theorem of calculus) and by Jupiter, y is a
x0
solution. Is it the one satisfying the initial condition? Well, y( x0 ) = x f ( x) dx + y0 = y0 . It is!
0
Do note that the definite integral and the indefinite integral (antidifferentiation) are completely
different beasts. The definite integral always evaluates to a number. Therefore, (1.2) is a formula
we can plug into the calculator or a computer, and it will be happy to calculate specific values for us.
We will easily be able to plot the solution and work with it just like with any other function. It is not
so crucial to always find a closed form for the antiderivative.
Example 1.1.2: Solve 2 y = e− x , y(0) = 1. By the preceding discussion, the solution must be
x y( x) = 2 e− s ds + 1.
0 Here is a good way to make fun of your friends taking second semester calculus. Tell them to find
the closed form solution. Ha ha ha (bad math joke). It is not possible (in closed form). There is
absolutely nothing wrong with writing the solution as a definite integral. This particular integral is
in fact very important in statistics. 1.1. INTEGRALS AS SOLUTIONS 15 Using this method, we can also solve equations of the form
y = f (y).
Let us write the equation in Leibniz notation.
dy
= f (y).
dx
Now we use the inverse function theorem from calculus to switch the roles of x and y to obtain
dx
1
=
.
dy
1
dy + C.
f (y) x(y) =
Finally, we try to solve for y. Example 1.1.3: Previously, we guessed y = ky (for some k > 0) has solution Cekx . We can actually
do it now. First we note that y = 0 is a solution. Henceforth, we assume y 0. We write
1
dx
=.
dy ky
We integrate to obtain
1
ln |y| + D,
k
where D is an arbitrary constant. Now we solve for y (actually for |y|).
x(y) = x = |y| = ekx−kD = e−kD ekx .
If we replace e−kD with an arbitrary constant C we can get rid of the absolute value bars (we can
do this as D was arbitrary). In this way, we also incorporate the solution y = 0. We get the same
general solution as we guessed before, y = Cekx .
Example 1.1.4: Find the general solution of y = y2 .
First we note that y = 0 is a solution. We can now assume that y
dx
1
= 2.
dy y 0. Write 16 CHAPTER 1. FIRST ORDER ODES We integrate to get
−1
+ C.
y
We solve for y = C1 x . So the general solution is
−
x= 1
or
y = 0.
C−x
Note the singularities of the solution. If for example C = 1, then the solution “blows up” as we
approach x = 1. Generally, it is hard to tell from just looking at the equation itself how the solution
is going to behave. The equation y = y2 is very nice and defined everywhere, but the solution is
only defined on some interval (−∞, C ) or (C, ∞).
y= Classical problems leading to differential equations solvable by integration are problems dealing
with velocity, acceleration and distance. You have surely seen these problems before in your
calculus class.
Example 1.1.5: Suppose a car drives at a speed et/2 meters per second, where t is time in seconds.
How far did the car get in 2 seconds (starting at t = 0)? How far in 10 seconds?
Let x denote the distance the car traveled. The equation is
x = et/2 .
We can just integrate this equation to get that
x(t) = 2et/2 + C.
We still need to figure out C . We know that when t = 0, then x = 0. That is, x(0) = 0. So
0 = x(0) = 2e0/2 + C = 2 + C.
Thus C = −2 and x(t) = et/2 − 2. Now we just plug in to get where the car is at 2 and at 10 seconds. We obtain
x(2) = 2e2/2 − 2 ≈ 3.44 meters, x(10) = 2e10/2 − 2 ≈ 294 meters. Example 1.1.6: Suppose that the car accelerates at a rate of t2 m/s2 . At time t = 0 the car is at the 1
meter mark and is traveling at 10 m/s. Where is the car at time t = 10.
Well this is actually a second order problem. If x is the distance traveled, then x is the velocity,
and x is the acceleration. The equation with initial conditions is
x = t2 , x(0) = 1, x (0) = 10. Well, what if we call x = v, and then we have the problem
v = t2 , v(0) = 10. Once we solve for v, we can then integrate and find x.
Exercise 1.1.1: Solve for v and then solve for x. Then find x(10) to answer the question. 1.1. INTEGRALS AS SOLUTIONS 1.1.1 17 Exercises Exercise 1.1.2: Solve dy
dx = x2 + x for y(1) = 3. Exercise 1.1.3: Solve dy
dx = sin(5 x) for y(0) = 2. Exercise 1.1.4: Solve dy
dx = 1
x 2 −1 for y(0) = 0. Exercise 1.1.5: Solve y = y3 for y(0) = 1.
Exercise 1.1.6 (challenging): Solve y = (y − 1)(y + 1) for y(0) = 3.
Exercise 1.1.7: Solve dy
dx = 1
y +1 for y(0) = 0. Exercise 1.1.8: Solve y = sin x for y(0) = 0.
Exercise 1.1.9: A spaceship is traveling at the speed 2t2 + 1 km/s (t is time in seconds). It is pointing
directly away from earth and at time t = 0 it is 1000 kilometers from earth. How far from earth is it
at one minute from time t = 0?
Exercise 1.1.10: Solve
integral. dx
dt = sin(t2 ) + t, x(0) = 20. It is OK to leave your answer as a definite 18 CHAPTER 1. FIRST ORDER ODES 1.2 Slope fields Note: 1 lecture, §1.3 in [EP]
At this point it may be good to first try the Lab I and/or Project I from the IODE website:.
As we said, the general first order equation we are studying looks like
y = f ( x, y).
In general, we cannot simply solve these kinds of equations explicitly. It would be good if we could
at least figure out the shape and behavior of the solutions, or if we could even find approximate
solutions for any equation. 1.2.1 Slope fields.
-3 -2 -1 0 1 2 3 -3 -2 -1 0 1 2 3 3 3 3 3 2 2 2 2 1 1 1 1 0 0 0 0 -1 -1 -1 -1 -2 -2 -2 -2 -3 -3 -3
-3 -2 -1 0 1 2 Figure 1.1: Slope field of y = xy. 3 -3
-3 -2 -1 0 1 2 3 Figure 1.2: Slope field of y = xy with a graph
of solutions satisfying y(0) = 0.2, y(0) = 0, and
y(0) = −0.2. We call this picture the slope field of the equation. If we are given a specific initial condition
y( x0 ) = y0 , we can look at the location ( x0 , y0 ) and follow the slopes. See Figure 1.2.
By looking at the slope field different 1.2. SLOPE FIELDS 19 behavior. On the other hand, plotting a few solutions of the equation y = −y, we see that no matter
what y(0) is, all solutions tend to zero as x tends to infinity. See Figure 1.3.
-3 -2 -1 0 1 2 3 3 3 2 2 1 1 0 0 -1 -1 -2 -2 -3 -3
-3 -2 -1 0 1 2 3 Figure 1.3: Slope field of y = −y with a graph of a few solutions. 1.2.2 Existence and uniqueness We wish to ask two fundamental questions about the problem
y = f ( x, y), y( x0 ) = y0 . :
1
y= ,
x y(0) = 0. Integrate to find the general solution y = ln | x| + C . Note that the solution does not exist at x = 0.
See Figure 1.4 on the next page. 20 CHAPTER 1. FIRST ORDER ODES -3 -2 -1 0 1 2 3 -3 -2 -1 0 1 2 3 3 3 3 3 2 2 2 2 1 1 1 1 0 0 0 0 -1 -1 -1 -1 -2 -2 -2 -2 -3 -3 -3
-3 -2 -1 0 1 2 3 Figure 1.4: Slope field of y = 1/x. -3
-3 -2 -1 0 1 2 3 Figure 1.5: Slope field of y = 2 |y| with two
solutions satisfying y(0) = 0. Example 1.2.2: Solve:
y = 2 |y|, y(0) = 0. See Figure 1.5. Note that y = 0 is a solution. But also the function x2 if x ≥ 0, y( x) = 2
− x if x < 0.
It is actually hard to tell from the slope field that the solution will not be unique. Is there any
hope? Of course there is. It turns out that the following theorem is true. It is known as Picard’s
theorem∗ .
Theorem 1.2.1 (Picard’s theorem on existence and uniqueness). If f ( x, y) is continuous (as a
f
function of two variables) and ∂ y exists and is continuous near some ( x0 , y0 ), then a solution to
∂
y = f ( x, y), y( x0 ) = y0 , exists (at least for some small interval of x’s) and is unique.
Note that the problems y = 1/x, y(0) = 0 and y = 2 |y|, y(0) = 0 do not satisfy the hypothesis
of the theorem. Even if we can use the theorem, we ought to be careful about this existence business.
It is quite possible that the solution only exists for a short while.
Example 1.2.3: For some constant A, solve:
y = y2 ,
∗ y(0) = A. Named after the French mathematician Charles Émile Picard (1856 – 1941) 1.2. SLOPE FIELDS 21 We know how to solve this equation. First assume that A 0, so y is not equal to zero at least
for some x near 0. So x = 1/y2 , so x = −1/y + C , so y = C1 x . If y(0) = A, then C = 1/A so
−
y= 1
.
1/A − x If A = 0, then y = 0 is a solution.
For example, when A = 1 the solution “blows up” at x = 1. Hence, the solution does not exist
for all x even if the equation is nice everywhere. The equation y = y2 certainly looks nice.
For the most of this course we will be interested in equations where existence and uniqueness
holds, and in fact holds “globally” unlike for the equation y = y2 . 1.2.3 Exercises Exercise 1.2.1: Sketch direction field for y = e x−y . How do the solutions behave as x grows? Can
you guess a particular solution by looking at the direction field?
Exercise 1.2.2: Sketch direction field for y = x2 .
Exercise 1.2.3: Sketch direction field for y = y2 .
Exercise 1.2.4: Is it possible to solve the equation y = xy
cos x for y(0) = 1? Justify. √
Exercise 1.2.5: Is it possible to solve the equation y = y | x| for y(0) = 0? Is the solution unique?
Justify. 22 1.3 CHAPTER 1. FIRST ORDER ODES Separable equations Note: 1 lecture, §1.4 in [EP]
When a differential equation is of the form y = f ( x), we can just integrate: y = f ( x) dx + C .
Unfortunately this method no longer works for the general form of the equation y = f ( x, y).
Integrating both sides yields
y= f ( x, y) dx + C. Notice
dy
= f ( x)g(y).
dx
Then we rewrite the equation as
dy
= f ( x) dx.
g(y)
Now both sides look like something we can integrate. We obtain
dy
=
g(y) f ( x) dx + C. If we can find closed form expressions for these two integrals, we can, perhaps, solve for y.
Example 1.3.1: Take the equation
y = xy.
First note that y = 0 is a solution, so assume y 0 from now on. Write the equation as dy
=
y x dx + C. We compute the antiderivatives to get
ln |y| = x2
+ C.
2 dy
dx = xy, then 1.3. SEPARABLE EQUATIONS
Or 23
x2 x2 x2 |y| = e 2 +C = e 2 eC = De 2 , where D > 0 is some constant. Because y = 0 is a solution and because of the absolute value we
actually can write:
x2
y = De 2 ,
for any number D (including zero or negative).
We check:
x2
x2
y = Dxe 2 = x De 2 = xy.
Yay!
We should be a little bit more careful with this method. You may be worried that we were
integrating in two different variables. We seemed to be doing a different operation to each side. Let
us work this method out more rigorously.
dy
= f ( x)g(y)
dx
We rewrite the equation as follows. Note that y = y( x) is a function of x and so is dy
!
dx 1 dy
= f ( x)
g(y) dx
We integrate both sides with respect to x.
1 dy
dx =
g(y) dx f ( x) dx + C. We can use the change of variables formula.
1
dy =
g(y) f ( x) dx + C. And we are done. 1.3.2 Implicit solutions It is clear that we might sometimes get stuck even if we can do the integration. For example, take
the separable equation
xy
y= 2
.
y +1
We separate variables
y2 + 1
1
dy = y +
dy = x dx.
y
y 24 CHAPTER 1. FIRST ORDER ODES Now we integrate to get
x2
y2
+ ln |y| =
+ C.
2
2
Or maybe the easier looking expression (where D = 2C ):
y2 + 2 ln |y| = x2 + D.
It is not easy to find the solution explicitly as it is hard to solve for y. We will, therefore, call this
solution an implicit solution. It is easy to check that implicit solutions still satisfy the differential
equation. In this case, we differentiate to get
y 2y + 2
= 2 x.
y It is simple to see that the differential equation holds. If you want to compute values for y you
might have to be tricky. For example, you can graph x as a function of y, and then flip your paper.
Computers are also good at some of these tricks, but you have to be careful.
We note above that the equation also has a solution y = 0. In this case, it turns out that the
general solution is y2 + 2 ln |y| = x2 + C together with y = 0. These outlying solutions such as y = 0
are sometimes called singular solutions. 1.3.3 Examples Example 1.3.2: Solve x2 y = 1 − x2 + y2 − x2 y2 , y(1) = 0.
First factor the right hand side to obtain
x2 y = (1 − x2 )(1 + y2 ).
We separate variables, integrate and solve for y
1 − x2
y
=
,
1 + y2
x2
1
y
= 2 − 1,
2
1+y
x
−1
arctan(y) =
− x + C,
x
−1
y = tan
− x+C .
x
Now solve for the initial condition, 0 = tan(−2 + C ) to get C = 2 (or 2 + π, etc. . . ). The solution we
are seeking is, therefore,
−1
y = tan
−x+2 .
x 1.3. SEPARABLE EQUATIONS 25 Example 1.3.3: Suppose Bob made a cup of coffee, and the water was boiling (100 degrees Celsius)
at time t = 0 minutes. Suppose Bob likes to drink his coffee at 70 degrees. Let the ambient (room)
temperature be 26 degrees. Furthermore, suppose Bob measured the temperature of the coffee at 1
minute and found that it dropped to 95 degrees. When should Bob start drinking?
Let T be the temperature of coffee, let A be the ambient (room) temperature. Then for some k
the temperature of coffee is:
dT
= k ( A − T ).
dt
For our setup A = 26, T (0) = 100, T (1) = 95. We separate variables and integrate (C and D will
denote arbitrary constants)
1 dT
= −k ,
T − A dt
ln(T − A) = −kt + C, (note that T − A > 0)
T − A = D e−kt ,
T = D e−kt + A.
That is, T = 26 + D e−kt . We plug in the first condition 100 = T (0) = 26 + D and hence D = 74.
Now we have T = 26 + 74 e−kt . We plug in 95 = T (1) = 26 + 74 e−k . Solving for k we get
−
k = − ln 957426 ≈ 0.07. Now we solve for the time t that gives us a temperature of 70 degrees. That
ln 70−26 74
is, we solve 70 = 26 + 74e−0.07t to get t = − 0.07 ≈ 7.43 minutes. So Bob can begin to drink the
coffee at about 7 and a half minutes from the time Bob made it. Probably about the amount of time
it took us to calculate how long it would take.
2 Example 1.3.4: Find the general solution to y = − xy (including singular solutions).
3
First note that y = 0 is a solution (a singular solution). So assume that y 0 and write
−3
y = x,
y2
3 x2
=
+ C,
y
2
3
6
y= 2
=2
.
x /2 + C
x + 2C 1.3.4 Exercises Exercise 1.3.1: Solve y = x/y.
Exercise 1.3.2: Solve y = x2 y.
Exercise 1.3.3: Solve dx
= ( x2 − 1) t, for x(0) = 0.
dt 26 CHAPTER 1. FIRST ORDER ODES Exercise 1.3.4: Solve dx
= x sin(t), for x(0) = 1.
dt Exercise 1.3.5: Solve dy
= xy + x + y + 1. Hint: Factor the right hand side.
dx Exercise 1.3.6: Solve xy = y + 2 x2 y, where y(1) = 1.
Exercise 1.3.7: Solve dy y2 + 1
=
, for y(0) = 1.
dx x2 + 1 Exercise 1.3.8: Find an implicit solution for dy x2 + 1
=
, for y(0) = 1.
dx y2 + 1 Exercise 1.3.9: Find explicit solution for y = xe−y , y(0) = 1.
Exercise 1.3.10: Find explicit solution for xy = e−y , for y(1) = 1.
Exercise 1.3.11: Find explicit solution for y = ye− x , y(0) = 1. It is alright to leave a definite
integral in your answer.
2 Exercise 1.3.12: Suppose a cup of coffee is at 100 degrees Celsius at time t = 0, it is at 70 degrees
at t = 10 minutes, and it is at 50 degrees at t = 20 minutes. Compute the ambient temperature. 1.4. LINEAR EQUATIONS AND THE INTEGRATING FACTOR 1.4 27 Linear equations and the integrating factor Note: 1 lecture, §1.5 in [EP]
One of the most important types of equations we will learn how to solve are the so-called linear
equations. In fact, the majority of the course will focus on linear equations. In this lecture we will
focus on the first order linear equation. A first order equation is linear if we can put it into the
following form:
y + p( x)y = f ( x).
(1.3)
The word “linear” here means linear in y. The dependence on x can be more complicated.
Solutions of linear equations have nice properties. For example, the solution exists wherever
p( x) and f ( x) are defined, and has the same regularity (read: it is just as nice). But most importantly
for us right now, there is a method for solving linear first order equations.
First we find a function r( x) such that
r( x)y + r( x) p( x)y = d
r( x)y .
dx Then we can multiply both sides of (1.3) by r( x) to obtain
d
r( x)y = r( x) f ( x).
dx
Now we integrate both sides. The right hand side does not depend on y and the left hand side is
written as a derivative of a function. Afterwards, we can solve for y. The function r( x) is called the
integrating factor and the method is called the integrating factor method.
We are looking for a function r( x) such that if we differentiate it, we get the same function back
multiplied by p( x). That seems like a job for the exponential function! Let
r ( x) = e p( x)dx We compute:
y + p( x)y = f ( x),
e p( x)dx y +e
d
e
dx p( x)dx e p( x)y = e p( x)dx f ( x), y =e p( x)dx f ( x), p( x)dx p( x)dx y=
y = e− e p( x)dx p( x)dx f ( x) dx + C,
e p( x)dx f ( x) dx + C . Of course, to get a closed form formula for y we need to be able to find a closed form formula
for the integrals appearing above. 28 CHAPTER 1. FIRST ORDER ODES Example 1.4.1: Solve
2 y + 2 xy = e x− x , y(0) = −1. First note that p( x) = 2 x and f ( x) = e x− x . The integrating factor is r( x) = e
multiply both sides of the equation by r( x) to get
2 2 2 2 p( x) dx = e x . We
2 2 e x y + 2 xe x y = e x− x e x ,
d x2
e y = ex .
dx
We integrate
2 e x y = e x + C,
2 2 y = e x− x + Ce− x .
Next, we solve for the initial condition −1 = y(0) = 1 + C , so C = −2. The solution is
2 2 y = e x− x − 2e− x .
Note that we do not care which antiderivative we take when computing e
add a constant of integration, but those constants will not matter in the end. p( x)dx . You can always
y + p( x)y = f ( x), y( x0 ) = y0 . Look at the solution and write the integrals as definite integrals.
− y( x) = e x
x0 p( s) ds x t e x0 p( s) ds f (t) dt + y0 . (1.4) x0 You should be careful to properly use dummy variables here. If you now plug such a formula into a
computer or a calculator, it will be happy to give you numerical answers.
Exercise 1.4.2: Check that y( x0 ) = y0 in formula (1.4). 1.4. LINEAR EQUATIONS AND THE INTEGRATING FACTOR 29 Exercise 1.4.3: Write the solution of the following problem as a definite integral, but try to simplify
as far as you can. You will not be able to find the solution in closed form.
2 y + y = ex −x , y(0) = 10. Example 1.4.2: The following is a simple application of linear equations and this type of a problem
is used often in real life. For example, linear equations are used in figuring out the concentration of
chemicals in bodies of water. x denote the kilograms of salt in the tank, let t denote the
time in minutes. Then for a small change ∆t in time, the change in x (denoted ∆ x) is approximately
∆ x ≈ (rate in × concentration in)∆t − (rate out × concentration out)∆t.
Dividing through by ∆t and taking the limit ∆t → 0 we see that
dx
= (rate in × concentration in) − (rate out × concentration out).
dt
In our example, we have
rate in = 5,
concentration in = 0.1,
rate out = 3,
x
x
concentration out =
=
.
volume 60 + (5 − 3)t
Our equation is, therefore,
dx
x
= (5 × 0.1) − 3
.
dt
60 + 2t
Or in the form (1.3)
dx
3
+
x = 0.5.
dt 60 + 2t
Let us solve. The integrating factor is
r(t) = exp 3
3
dt = exp ln(60 + 2t) = (60 + 2t)3/2 .
60 + 2t
2 30 CHAPTER 1. FIRST ORDER ODES
We multiply both sides of the equation to get
(60 + 2t)3/2 dx
3
+ (60 + 2t)3/2
x = 0.5(60 + 2t)3/2 ,
dt
60 + 2t
d
(60 + 2t)3/2 x = 0.5(60 + 2t)3/2 ,
dt
(60 + 2t)3/2 x = 0.5(60 + 2t)3/2 dt + C,
(60 + 2t)3/2
dt + C (60 + 2t)−3/2 ,
2 x = (60 + 2t)−3/2
x = (60 + 2t)−3/2
x= 1
(60 + 2t)5/2 + C (60 + 2t)−3/2 ,
10 60 + 2t
+ C (60 + 2t)−3/2 .
10 We need to find C . We know that at t = 0, x = 10. So
10 = x(0) =
or 60
+ C (60)−3/2 = 6 + C (60)−3/2 ,
10 C = 4(603/2 ) ≈ 1859.03. We are interested in x when the tank is full. So we note that the tank is full when 60 + 2t = 100,
or when t = 20. So
x(20) = 60 + 40
+ C (60 + 40)−3/2 ≈ 10 + 1859.03(100)−3/2 ≈ 11.86.
10 The concentration at the end is approximately 0.1186 kg/liter and we started with 1/6 or 0.167 kg/liter. 1.4.1 Exercises In the exercises, feel free to leave answer as a definite integral if a closed form solution cannot be
found. If you can find a closed form solution, you should give that.
Exercise 1.4.4: Solve y + xy = x.
Exercise 1.4.5: Solve y + 6y = e x .
Exercise 1.4.6: Solve y + 3 x2 y = sin( x) e− x , with y(0) = 1.
3 Exercise 1.4.7: Solve y + cos( x)y = cos( x).
Exercise 1.4.8: Solve 1
x 2 +1 y + xy = 3, with y(0) = 0. 1.4. LINEAR EQUATIONS AND THE INTEGRATING FACTOR 31 seconds) in both lakes. b) When will the concentration in the first lake be below 0.001 kg
per liter. c) When will the concentration in the second lake be maximal.
Exercise 1.4.10: Newton’s law of cooling states that dx = −k( x − A) where x is the temperature,
dt
t is time, A is the ambient temperature, and k > 0 is a constant. Suppose that A = A0 cos(ωt) for
some constants A0 and ω. concentration of
salt is flowing in at 1 liter per minute. The water is mixed well and drained at 1 liter per minute. In
20 minutes there are 15 grams of salt in the tank. What is the concentration of salt in the incoming
brine? 32 1.5 CHAPTER 1. FIRST ORDER ODES Substitution Note: 1 lecture, §1.6 in [EP]
Just like when solving integrals, one method to try is to change variables to end up with a
simpler equation to solve. 1.5.1 Substitution The equation
y = ( x − y + 1)2 .
is neither separable nor linear. What can we do? How about trying to change variables, so that in
the new variables the equation is simpler. We will use another variable v, which we will treat as a
function of x. Let us try
v = x − y + 1.
We need to figure out y in terms of v , v and x. We differentiate (in x) to obtain v = 1 − y . So
y = 1 − v . We plug this into the equation to get
1 − v = v2 .
In other words, v = 1 − v2 . Such an equation we know how to solve.
1
dv = dx.
1 − v2
So
1
v+1
= x + C,
ln
2
v−1
v+1
= e2 x+2C ,
v−1
or v+1 = De2 x for some constant D. Note that v = 1 and v = −1 are also solutions.
v −1
Now we need to “unsubstitute” to obtain
x−y+2
= De2 x ,
x−y
and also the two solutions x − y + 1 = 1 or y = x, and x − y + 1 = −1 or y = x + 2. We solve the first
equation for y.
x − y + 2 = ( x − y)De2 x ,
x − y + 2 = Dxe2 x − yDe2 x ,
−y + yDe2 x = Dxe2 x − x − 2,
y (−1 + De2 x ) = Dxe2 x − x − 2,
y= Dxe2 x − x − 2
.
De2 x − 1 1.5. SUBSTITUTION 33 Note that D = 0 gives y = x + 2, but no value of D gives the solution y = x.
Substitution in differential equations is applied in much the same way that it is applied in
calculus. You guess. Several different substitutions might work. There are some general things to
look for. We summarize a few of these in a table.
When you see Try substituting yy
y2 y
(cos y)y
(sin y)y
y ey y2
y3
sin y
cos y
ey different one. 1.5.2 Bernoulli equations There are some forms of equations where there is a general rule for substitution that always works.
One such example is the so-called Bernoulli equation† .
y + p( x)y = q( x)yn .
This equation looks a lot like a linear equation except for the yn . If n = 0 or n = 1, then the equation
is linear and we can solve it. Otherwise, a change of coordinates v = y1−n transforms the Bernoulli
equation into a linear equation. Note that n need not be an integer.
Example 1.5.1: Solve
xy + y( x + 1) + xy5 = 0, y(1) = 1. First, the equation is Bernoulli ( p( x) = ( x + 1)/ x and q( x) = −1). We substitute
v = y1−5 = y−4 , v = −4y−5 y . In other words, (−1/4) y5 v = y . So
xy + y( x + 1) + xy5 = 0,
− xy5
v + y( x + 1) + xy5 = 0,
4
−x
v + y−4 ( x + 1) + x = 0,
4
−x
v + v( x + 1) + x = 0,
4
† There are several things called Bernoulli equations, this is just one of them. The Bernoullis were a prominent Swiss
family of mathematicians. These particular equations are named for Jacob Bernoulli (1654 – 1705). 34 CHAPTER 1. FIRST ORDER ODES and finally 4( x + 1)
v = 4.
x
Now the equation is linear. We can use the integrating factor method. In particular, we will use
formula (1.4). Let us assume that x > 0 so | x| = x. This assumption is OK, as our initial condition
is x = 1. Let us compute the integrating factor. Here p( s) from formula (1.4) is −4( s+1) .
s
v− x e1 x
p( s) ds = exp
1 − e x
1 p( s) ds e−4 x+4
−4( s + 1)
ds = e−4 x−4 ln( x)+4 = e−4 x+4 x−4 =
,
s
x4 4 x+4 ln( x)−4 =e = e4 x−4 x4 . We now plug in to (1.4)
v( x) = e− x
1 x t e 1 p( s) ds 4 dt + 1 p( s) ds
1
x = e4 x−4 x4 4
1 e−4t+4
dt + 1 .
t4 Note that the integral in this expression is not possible to find in closed form. As we said before, it
is perfectly fine to have a definite integral in our solution. Now “unsubstitute”
x y−4 = e4 x−4 x4 4
1 e − x +1 y=
x4 1.5.3 e−4t+4
dt + 1 ,
t4 x e−4t+4
t4
1 dt + 1 1/4 . Homogeneous equations Another type of equations we can solve by substitution are the so-called homogeneous equations.
Suppose that we can write the differential equation as
y =F y
.
x Here we try the substitutions
v= y
x and therefore y = v + xv . We note that the equation is transformed into
v + xv = F (v) or xv = F (v) − v or v
1
=.
F (v) − v x 1.5. SUBSTITUTION 35 Hence an implicit solution is
1
dv = ln | x| + C.
F (v) − v
Example 1.5.2: Solve
x2 y = y2 + xy, y(1) = 1. We put the equation into the form y = (y/x) + y/x. Now we substitute v = y/x to get the separable
equation
xv = v2 + v − v = v2 ,
2 which has a solution
1
dv = ln | x| + C,
v2
−1
= ln | x| + C,
v
−1
v=
.
ln | x| + C
We unsubstitute
−1
y
=
,
x ln | x| + C
−x
y=
.
ln | x| + C
We want y(1) = 1, so −1
−1
=
.
ln |1| + C
C
Thus C = −1 and the solution we are looking for is
1 = y(1) = y= 1.5.4
−x
.
ln | x| − 1 Exercises Exercise 1.5.1: Solve y + y( x2 − 1) + xy6 = 0, with y(1) = 1.
Exercise 1.5.2: Solve 2yy + 1 = y2 + x, with y(0) = 1.
Exercise 1.5.3: Solve y + xy = y4 , with y(0) = 1.
Exercise 1.5.4: Solve yy + x = x2 + y2 . Exercise 1.5.5: Solve y = ( x + y − 1)2 .
Exercise 1.5.6: Solve y = x2 −y2
,
xy with y(1) = 2. 36 CHAPTER 1. FIRST ORDER ODES 1.6 Autonomous equations Note: 1 lecture, §2.2 in [EP]
Let us consider problems of the form
dx
= f ( x),
dt
where the derivative of solutions depends only on x (the dependent variable). These types of
equations are called autonomous equations. If we think of t as time, the naming comes from the
fact that the equation is independent of time.
Let us come back to the cooling coffee problem. Newton’s law of cooling says that
dx
= −k( x − A),
dt
where x is the temperature, t is time, k is some constant and A is the ambient temperature. See Figure 1.6 for an example with k = 0.3 and A = 5.
Note the solution x = A (in the example x = 5). We call these types of different solutions as t grows. If we change the initial condition a little bit, then as
t → ∞ we get x → A. We call such critical points stable. In this simple example it turns out that all
solutions in fact go to A as t → ∞. If a critical point is not stable we would say it is unstable.
0 5 10 15 20 0 10 10 5 5 10 15 20 5 5.0 2.5 2.5 0.0 0.0 -2.5 -5 7.5 5.0 0 10.0 7.5 0 10.0 -2.5 -5 -10 -10
0 5 10 15 20 Figure 1.6: Slope field and some solutions of
x = −0.3 ( x − 5). -5.0 -5.0
0 5 10 15 20 Figure 1.7: Slope field and some solutions of
x = 0.1 x (5 − x). 1.6. AUTONOMOUS EQUATIONS 37 Let us consider the logistic equation
dx
= kx( M − x),
dt on the facing page for an example. Note two critical points, x = 0 and x = 5.
The critical point at x = 5 is stable. On the other hand the critical point at x = 0 is unstable.
It is not really necessary to find the exact solutions to talk about the long term behavior of the
solutions. For example, from the above we can easily see that 5 if x(0) > 0, lim x(t) = 0
if x(0) = 0, t→∞ DNE or − ∞ if x(0) < 0. Where DNE means “does not exist.” From just looking at the slope field we cannot quite decide
what happens if x(0) < 0. It could be that the solution does not exist for t all the way to ∞. Think
of the equation x = x2 , we have seen that it only exists for some finite period of time. Same can
happen here. In our example equation above it will actually turn out that the solution does not exist
for all time, but to see that we would have to solve the equation. In any case, the solution does go to
−∞,. So draw the x axis, mark all the critical points and then draw
arrows in between. If f ( x) > 0 draw an up arrow and if it is negative draw a down arrow. x=5
x=0 Armed with the phase diagram, it is easy to sketch the solutions approximately.
Exercise 1.6.1: Try sketching a few solutions simply from looking at the phase diagram. Check
with the preceding graphs if you are getting the type of curves. 38 CHAPTER 1. FIRST ORDER ODES
Once we draw the phase diagram, we can easily classify critical points as stable or unstable. unstable stable Since any mathematical model we cook up will only be an approximation to the real world,
unstable points are generally bad news.
Let us think about the logistic equation with harvesting. Logistic equations are commonly used
for modeling population.. k > 0 is some constant depending on how fast humans multiply. Our
equation becomes
dx
= kx( M − x) − h.
dt
Multiply out and solve for critical points
dx
= −kx2 + kMx − h.
dt
Critical points A and B are
kM + (kM )2 − 4hk
kM − (kM )2 − 4hk
B=
.
2k
2k
Exercise 1.6.2: Draw the phase diagram for different possibilities. Note that these possibilities are
A > B, or A = B, or A and B both complex (i.e. no real solutions). Hint: Fix some simple k and M
and then vary h.
A= For example, let M = 8 and k = 0.1. When h = 1, then A and B are distinct and positive.
The graph we will get is given in Figure 1.8 on the next page. As long as the population stays
above B, which is approximately 1.55 million, then the population will not die out. If ever the
population drops below B, humans will die out, and the fast food restaurant serving them will go
out of business.
When h = 1.6, then A = B. There is only one critical point that is unstable. When the population
is above 1.6 million it will tend towards this number. If it ever drops below 1.6 million, humans will
die out on the planet. This scenario is not one that we (as the human fast food proprietor) want to be
in. A small perturbation of the equilibrium state and we are out of business. There is no room for
error. See Figure 1.9 on the facing page
Finally if we are harvesting at 2 million humans per year, the population will always plummet
towards zero, no matter how well stocked the planet starts. See Figure 1.10 on the next page. 1.6. AUTONOMOUS EQUATIONS
0 5 10 39 15 20 0 5 10 15 20 10.0 10.0 10.0 10.0 7.5 7.5 7.5 7.5 5.0 5.0 5.0 5.0 2.5 2.5 2.5 2.5 0.0 0.0 0.0
0 5 10 15 20 Figure 1.8: Slope field and some solutions of
x = 0.1 x (8 − x) − 1.
0 5 0.0
0 5 10 15 20 Figure 1.9: Slope field and some solutions of
x = 0.1 x (8 − x) − 1.6.
10 15 20 10.0 10.0 7.5 7.5 5.0 5.0 2.5 2.5 0.0 0.0
0 5 10 15 20 Figure 1.10: Slope field and some solutions of x = 0.1 x (8 − x) − 2. 1.6.1 Exercises Exercise 1.6.3: Let x = x2 . a) Draw the phase diagram, find the critical points and mark them
stable or unstable. b) Sketch typical solutions of the equation. c) Find lim x(t) for the solution with
t→∞
the initial condition x(0) = −1.
Exercise 1.6.4: Let x = sin x. a) Draw the phase diagram for −4π ≤ x ≤ 4π. On this interval
mark the critical points stable or unstable. b) Sketch typical solutions of the equation. c) Find
limt→∞), find the critical points and mark 40 CHAPTER 1. FIRST ORDER ODES them stable or unstable. b) Sketch typical solutions of the equation. c) Find lim x(t) for the solution
t→∞
with the initial condition x(0) = 0.5.
Exercise 1.6.6: Start with the logistic equation dx = kx( M − x). Suppose that we modify our
dt
harvesting. That is we will only harvest an amount proportional to current population. In other
words we harvest hx per unit of time for some h > 0 (Similar to earlier example with h replaced
with hx). a) Construct the differential equation. b) Show that if kM > h, then the equation is still
logistic. c) What happens when kM < h? 1.7. NUMERICAL METHODS: EULER’S METHOD 1.7 41 Numerical methods: Euler’s method Note: 1 lecture, §2.4 in [EP]
At this point it may be good to first try the Lab II and/or Project II from the IODE website:.
As we said before, unless f ( x, y) is of a special form, it is generally very hard if not impossible
to get a nice formula for the solution of the problem
y = f ( x, y), y( x0 ) = y0 . What if we want to find the value of the solution at some particular x? Or perhaps we want to
produce a graph of the solution to inspect the behavior. In this section we will learn about the basics
of numerical approximation of solutions.
The simplest method for approximating a solution is Euler’s method‡ . It works as follows: We
take x0 and compute the slope k = f ( x0 , y0 ). The slope is the change in y per unit change in x. We
follow the line for an interval of length h on the x axis. Hence if y = y0 at x0 , then we will say that
y1 (the approximate value of y at x1 = x0 + h) will be y1 = y0 + hk. Rinse, repeat! That is, compute
x2 and y2 using x1 and y1 . For an example of the first two steps of the method see Figure 1.11.
-1 0 1 2 3 -1 0 1 2 3 3.0 3.0 3.0 3.0 2.5 2.5 2.5 2.5 2.0 2.0 2.0 2.0 1.5 1.5 1.5 1.5 1.0 1.0 1.0 1.0 0.5 0.5 0.5 0.5 0.0 0.0 0.0
-1 0 1 2 3 0.0
-1 0 1 Figure 1.11: First two steps of Euler’s method with h = 1 for the equation y =
conditions y(0) = 1. 2 y2
3 3 with initial More abstractly, for any i = 1, 2, 3, . . ., we compute
xi+1 = xi + h, yi+1 = yi + h f ( xi , yi ). The line segments we get are an approximate graph of the solution. Generally it is not exactly the
solution. See Figure 1.12 on the next page for the plot of the real solution and the approximation.
‡ Named after the Swiss mathematician Leonhard Paul Euler (1707 – 1783). Do note the correct pronunciation of
the name sounds more like “oiler.” 42 CHAPTER 1. FIRST ORDER ODES
-1 0 1 2 3 3.0 3.0 2.5 2.5 2.0 2.0 1.5 1.5 1.0 1.0 0.5 0.5 0.0 0.0
-1 0 1 2 3 Figure 1.12: Two steps of Euler’s method (step size 1) and the exact solution for the equation y =
with initial conditions y(0) = 1. y2
3 Let us see what happens with the equation y = y2/3, y(0) = 1. Let us try to approximate y(2)
using Euler’s method. In Figures 1.11 and 1.12 we have essentially graphically approximated
y(2) with step size 1. With step size 1 we have y(2) ≈ 1.926. The real answer is 3. So we are
approximately 1.074 off. Let us halve the step size. Computing y4 with h = 0.5, we find that
y(2) ≈ 2.209, so error of about 0.791. Table 1.1 on the facing page gives the values computed for
various parameters.
Exercise 1.7.1: Solve this equation exactly and show that y(2) = 3.
The difference between the actual solution and the approximate solution we will call the error.
We will usually talk about just the size of the error and we do not care much about its sign. The
main point is, that we usually do not know the real solution, so we only have a vague understanding
of the error. If we knew the error exactly . . . what is the point of doing the approximation?
We notice that except for the first few times, every time we halved the interval the error
approximately halved. This halving of the error is a general feature of Euler’s method as it is a first
order method. In the IODE Project II you are asked to implement a second order method. A second
order method reduces the error to approximately one quarter every time we halve the interval.
Note that to get the error to be within 0.1 of the answer we had to already do 64 steps. To get
it to within 0.01 we would have to halve another three or four times, meaning doing 512 to 1024
steps. That is quite a bit to do by hand. The improved Euler method from IODE Project II should
quarter the error every time we halve the interval, so we would have to approximately do half as
many “halvings” to get the same error. This reduction can be a big deal. With 10 halvings (starting
at h = 1) we have 1024 steps, whereas with 5 halvings we only have to do 32 steps, assuming
that the error was comparable to start with. A computer may not care about this difference for a
problem this simple, but suppose each step would take a second to compute (the function may be 1.7. NUMERICAL METHODS: EULER’S METHOD 43 h Approximate y(2) Error Error
Previous error 1
0.5
0.25
0.125
0.0625
0.03125
0.015625
0.0078125 1.92593
2.20861
2.47250
2.68034
2.82040
2.90412
2.95035
2.97472 1.07407
0.79139
0.52751
0.31966
0.17960
0.09588
0.04965
0.02528 0.73681
0.66656
0.60599
0.56184
0.53385
0.51779
0.50913 Table 1.1: Euler’s method approximation of y(2) where of y = y2/3, y(0) = 1.
substantially more difficult to compute than y2/3). Then the difference is 32 seconds versus about
17 minutes. Note: We are not being altogether fair, a second order method would probably double
the time to do each step. Even so, it is 1 minute versus 17 minutes. Next, suppose that we have to
repeat such a calculation for different parameters a thousand times. You get the idea.
Note that we do not know the error! How do we know what is the right step size? Essentially
we keep halving the interval, and if we are lucky, we can estimate the error from a few of these
calculations and the assumption that the error goes down by a factor of one half each time (if we are
using standard Euler).
Exercise 1.7.2: In the table above, suppose you do not know the error. Take the approximate values
of the function in the last two lines, assume that the error goes down by a factor of 2. Can you
estimate the error in the last time from this? Does it (approximately) agree with the table? Now do
it for the first two rows. Does this agree with the table?
Let us talk a little bit more about the example y = y2/3, y(0) = 1. Suppose that instead of the
value y(2) we wish to find y(3). The results of this effort are listed in Table 1.2 on the next page for
successive halvings of h. What is going on here? Well, you should solve the equation exactly and
you will notice that the solution does not exist at x = 3. In fact, the solution goes to infinity when
you approach x = 3.
Another case when things can go bad is if the solution oscillates wildly near some point. Such
an example is given in IODE Project II. In this case, the solution may exist at all points, but even
a better approximation method than Euler would need an insanely small step size to compute the
solution with reasonable precision. And computers might not be able to handle such a small step
size anyway.
In real applications we would not use a simple method such as Euler’s. The simplest method
that would probably be used in a real application is the standard Runge-Kutta method (we will not
describe it here). That is a fourth order method, meaning that if we halve the interval, the error
generally goes down by a factor of 16. 44 CHAPTER 1. FIRST ORDER ODES
h Approximate y(3)
1
0.5
0.25
0.125
0.0625
0.03125
0.015625
0.0078125 3.16232
4.54329
6.86079
10.80321
17.59893
29.46004
50.40121
87.75769 Table 1.2: Attempts to use Euler’s to approximate y(3) where of y = y2/3, y(0) = 1.
Choosing the right method to use and the right step size can be very tricky. There are several
competing factors to consider.
• Computational time: Each step takes computer time. Even if the function f is simple to
compute, we do it many times over. Large step size means faster computation, but perhaps
not the right precision.
• Roundoff errors: Computers only compute with a certain number of significant digits. Errors
introduced by rounding numbers off during our computations become noticeable when the
step size becomes too small relative to the quantities we are working with. So reducing step
size may in fact make errors worse.
• Stability: Certain equations may be numerically unstable. Small errors lead to large errors
down the line. In the worst case the numerical computations might be giving us bogus
numbers that look like a correct answer. Just because the numbers have stabilized after
successive halving, does not mean that we must have the right answer. What may also happen
is that the numbers may never stabilize no matter how many times we halve the interval.
We have seen just the beginnings of the challenges that appear in real applications. Numerical
approximation of solutions to differential equations is an active research area for engineers and
mathematicians. For example, the general purpose method used for the ODE solver in Matlab and
Octave (as of this writing) is a method that appeared in the literature only in the 1980s. 1.7.1 Exercises dx
Exercise 1.7.3: Consider
= (2t − x)2 , x(0) = 2. Use Euler’s method with step size h = 0.5 to
dt
approximate x(1). 1.7. NUMERICAL METHODS: EULER’S METHOD 45 dx
Exercise 1.7.4: Consider
= t − x, x(0) = 1. a) Use Euler’s method with step sizes h =
dt
1, 1/2, 1/4, 1/8 to approximate x(1). b) Solve the equation exactly. c) Describe what happens to the
errors for each h you used. That is, find. 46 CHAPTER 1. FIRST ORDER ODES Chapter 2
Higher order linear ODEs
2.1 Second order linear ODEs Note: less than 1 lecture, first part of §3.1 in [EP]
Let us consider the general second order linear differential equation
A( x)y + B( x)y + C ( x)y = F ( x).
We usually divide through by A( x) to get
y + p( x)y + q( x)y = f ( x), (2.1) where p( x) = B( x)/A( x), q( x) = C ( x)/A( x), and f ( x) = F ( x)/A( x). The word linear means that the equation
contains no powers nor functions of y, y , and y .
In the special case when f ( x) = 0 we have a so-called homogeneous equation
y + p( x)y + q( x)y = 0. (2.2) We have already seen some second order linear homogeneous equations.
y + k2 y = 0
y −k y=0
2 Two solutions are: y1 = cos(kx), Two solutions are: y1 = e ,
kx y2 = sin(kx). y2 = e−kx . If we know two solutions of a linear homogeneous equation, we know a lot more of them.
Theorem 2.1.1 (Superposition). Suppose y1 and y2 are two solutions of the homogeneous equation
(2.2). Then
y( x) = C1 y1 ( x) + C2 y2 ( x),
also solves (2.2) for arbitrary constants C1 and C2 .
47 48 CHAPTER 2. HIGHER ORDER LINEAR ODES That is, we can add solutions together and multiply them by constants to obtain new and different
solutions. We will prove this theorem because the proof is very enlightening and illustrates how
linear equations work.
Proof: Let y = C1 y1 + C2 y2 . Then
y + py + qy = (C1 y1 + C2 y2 ) + p(C1 y1 + C2 y2 ) + q(C1 y1 + C2 y2 )
= C1 y1 + C2 y2 + C1 py1 + C2 py2 + C1 qy1 + C2 qy2
= C1 (y1 + py1 + qy1 ) + C2 (y2 + py2 + qy2 )
= C1 · 0 + C2 · 0 = 0.
The proof becomes even simpler to state if we use the operator notation. An operator is an
object that eats functions and spits out functions (kind of like what a function is, but a function eats
numbers and spits out numbers). Define the operator L by
Ly = y + py + qy.
The differential equation now becomes Ly = 0. The operator (and the equation) L being linear
means that L(C1 y1 + C2 y2 ) = C1 Ly1 + C2 Ly2 . The proof above becomes
Ly = L(C1 y1 + C2 y2 ) = C1 Ly1 + C2 Ly2 = C1 · 0 + C2 · 0 = 0.
Two different solutions to the second equation y − k2 y = 0 are y1 = cosh(kx) and y2 = sinh(kx).
x
−x
x
−x
Let us remind ourselves of the definition, cosh x = e +e and sinh x = e −e . Therefore, these are
2
2
solutions by superposition as they are linear combinations of the two exponential solutions.
The functions sinh and cosh are sometimes more convenient to use than the exponential. Let us
review some of their properties.
cosh 0 = 1
d
cosh x = sinh x
dx
cosh2 x − sinh2 x = 1 sinh 0 = 0
d
sinh x = cosh x
dx Exercise 2.1.1: Derive these properties using the definitions of sinh and cosh in terms of exponentials.
Linear equations have nice and simple answers to the existence and uniqueness question.
Theorem 2.1.2 (Existence and uniqueness). Suppose p, q, f are continuous functions and a, b0 , b1
are constants. The equation
y + p( x)y + q( x)y = f ( x),
has exactly one solution y( x) satisfying the initial conditions
y(a) = b0 , y (a) = b1 . 2.1. SECOND ORDER LINEAR ODES 49 For example, the equation y + k2 y = 0 with y(0) = b0 and y (0) = b1 has the solution
y( x) = b0 cos(kx) + b1
sin(kx).
k The equation y − k2 y = 0 with y(0) = b0 and y (0) = b1 has the solution
y( x) = b0 cosh(kx) + b1
sinh(kx).
k Using cosh and sinh find a solution to the differential equation satisfying the initial conditions.
Question: Suppose we find two different solutions y1 and y2 to the homogeneous equation (2.2).
Can every solution be written (using superposition) in the form y = C1 y1 + C2 y2 ?
Answer is affirmative! Provided that y1 and y2 are different enough in the following sense. We
will say y1 and y2 are linearly independent if one is not a constant multiple of the other.
Theorem 2.1.3. Let p, q, f be continuous functions and take the homogeneous equation (2.2). Let
y1 and y2 be two linearly independent solutions to (2.2). Then every other solution is of the form
y = C1 y1 + C2 y2 .
That is, y = C1 y1 + C2 y2 is the general solution.
For example, we found the solutions y1 = sin x and y2 = cos x for the equation y + y = 0. It is
obvious that sine and cosine are not multiples of each other. If sin x = A cos x for some constant A,
we let x = 0 and this would imply A = 0 = sin x, which is preposterous. So y1 and y2 are linearly
independent. Hence
y = C1 cos x + C2 sin x
is the general solution to y + y = 0.
We will study the solution of nonhomogeneous equations in § 2.5. We will first focus on finding
general solutions to homogeneous equations. 2.1.1 Exercises Exercise 2.1.2: Show that y = e x and y = e2 x are linearly independent.
Exercise 2.1.3: Take y + 5y = 10 x + 5. Find (guess!) a solution. 50 CHAPTER 2. HIGHER ORDER LINEAR ODES Exercise 2.1.4: Prove the superposition principle for nonhomogeneous equations. Suppose that y1
is a solution to Ly1 = f ( x) and y2 is a solution to Ly2 = g( x) (same linear operator L). Show that y
solves Ly = f ( x) + g( x).
Exercise 2.1.5: For the equation x2 y − xy = 0, find two solutions, show that they are linearly
independent and find the general solution. Hint: Try y = xr .
Note that equations of the form ax2 y + bxy + cy = 0 are called Euler’s equations or CauchyEuler equations. They are solved by trying y = xr and solving for r (we can assume that x ≥ 0 for
simplicity).
Exercise 2.1.6: Suppose that (b − a)2 − 4ac > 0. a) Find a formula for the general solution
of ax2 y + bxy + cy = 0. Hint: Try y = xr and find a formula for r. b) What happens when
(b − a)2 − 4ac = 0 or (b − a)2 − 4ac < 0?
We will revisit the case when (b − a)2 − 4ac < 0 later.
Exercise 2.1.7: Same equation as in Exercise 2.1.6. Suppose (b − a)2 − 4ac = 0. Find a formula
for the general solution of ax2 y + bxy + cy = 0. Hint: Try y = xr ln x for the second solution.
If you have one solution to a second order linear homogeneous equation you can find another
one. This is the reduction of order method.
Exercise 2.1.8: Suppose y1 is a solution to y + p( x)y + q( x)y = 0. Show that
y2 ( x) = y1 ( x) e− p( x) dx y1 ( x) 2 dx is also a solution.
If you wish to come up with the formula for reduction of order yourself, start by trying
y2 ( x) = y1 ( x)v( x). Then plug y2 into the equation, use the fact that y1 is a solution, substitute w = v ,
and you have a first order linear equation in w. Solve for w and then for v. When solving for w, make
sure to include a constant of integration. Let us solve some famous equations using the method.
Exercise 2.1.9 (Chebychev’s equation of order 1): Take (1 − x2 )y − xy + y = 0. a) Show that
y = x is a solution. b) Use reduction of order to find a second linearly independent solution. c)
Write down the general solution.
Exercise 2.1.10 (Hermite’s equation of order 2): Take y − 2 xy + 4y = 0. a) Show that y = 1 − 2 x2
is a solution. b) Use reduction of order to find a second linearly independent solution. c) Write
down the general solution. 2.2. CONSTANT COEFFICIENT SECOND ORDER LINEAR ODES 2.2 51 Constant coefficient second order linear ODEs Note: more than 1 lecture, second part of §3.1 in [EP]
Suppose we have the problem
y − 6y + 8y = 0, y(0) = −2, y (0) = 6. This is a second order linear homogeneous equation with constant coefficients. Constant coefficients
means that the functions in front of y , y , and y are constants, not depending on x.
To guess a solution, think of a function that you know stays essentially the same when we
differentiate it, so that we can take the function and its derivatives, add some multiples of these
together, and end up with zero.
Let us try a solution of the form y = erx . Then y = rerx and y = r2 erx . Plug in to get
y − 6y + 8y = 0,
r e − 6rerx + 8erx = 0,
2 rx r2 − 6r + 8 = 0
(r − 2)(r − 4) = 0. (divide through by erx ), Hence, if r = 2 or r = 4, then erx is a solution. So let y1 = e2 x and y2 = e4 x .
Exercise 2.2.1: Check that y1 and y2 are solutions.
The functions e2 x and e4 x are linearly independent. If they were not linearly independent we
could write e4 x = Ce2 x implying that e2 x = C , which is clearly not possible. Hence, we can write
the general solution as
y = C1 e2 x + C2 e4 x .
We need to solve for C1 and C2 . To apply the initial conditions we first find y = 2C1 e2 x + 4C2 e4 x .
We plug in x = 0 and solve.
−2 = y(0) = C1 + C2 ,
6 = y (0) = 2C1 + 4C2 .
Either apply some matrix algebra, or just solve these by high school math. For example, divide the
second equation by 2 to obtain 3 = C1 + 2C2 , and subtract the two equations to get 5 = C2 . Then
C1 = −7 as −2 = C1 + 5. Hence, the solution we are looking for is
y = −7e2 x + 5e4 x .
Let us generalize this example into a method. Suppose that we have an equation
ay + by + cy = 0, (2.3) 52 CHAPTER 2. HIGHER ORDER LINEAR ODES where a, b, c are constants. Try the solution y = erx to obtain
ar2 erx + brerx + cerx = 0,
ar2 + br + c = 0.
The equation ar2 + br + c = 0 is called the characteristic equation of the ODE. Solve for the r by
using the quadratic formula.
√
−b ± b2 − 4ac
.
r1 , r2 =
2a
Therefore, we have er1 x and er2 x as solutions. There is still a difficulty if r1 = r2 , but it is not hard to
overcome.
Theorem 2.2.1. Suppose that r1 and r2 are the roots of the characteristic equation.
(i) If r1 and r2 are distinct and real (when b2 − 4ac > 0), then (2.3) has the general solution
y = C1 er1 x + C2 er2 x .
(ii) If r1 = r2 (happens when b2 − 4ac = 0), then (2.3) has the general solution
y = (C1 + C2 x) er1 x .
For another example of the first case, take the equation y − k2 y = 0. Here the characteristic
equation is r2 − k2 = 0 or (r − k)(r + k) = 0. Consequently, e−kx and ekx are the two linearly
independent solutions.
Example 2.2.1: Find the general solution of
y − 8y + 16y = 0.
The characteristic equation is r2 − 8r + 16 = (r − 4)2 = 0. The equation has a double root
r1 = r2 = 4. The general solution is, therefore,
y = (C1 + C2 x) e4 x = C1 e4 x + C2 xe4 x .
Exercise 2.2.2: Check that e4 x and xe4 x are linearly independent.
That e4 x solves the equation is clear. If xe4 x solves the equation, then we know we are done. Let
us compute y = e4 x + 4 xe4 x and y = 8e4 x + 16 xe4 x . Plug in
y − 8y + 16y = 8e4 x + 16 xe4 x − 8(e4 x + 4 xe4 x ) + 16 xe4 x = 0.
We should note that in practice, doubled root rarely happens. If coefficients are picked truly
randomly we are very unlikely to get a doubled root.
Let us give a short “proof” for why the solution xerx works when the root is doubled. This case
rx
rx
is really a limiting case of when the two roots are distinct and very close. Note that e 2 2 −e11 is a
r −r
solution when the roots are distinct. When r1 goes to r2 in the limit this is like taking derivative of
erx using r as a variable. This limit is xerx , and hence this is a solution in the doubled root case. 2.2. CONSTANT COEFFICIENT SECOND ORDER LINEAR ODES 2.2.1 53 Complex numbers and Euler’s formula It may happen that a polynomial has some complex roots. For example, the equation r2 + define a
multiplication by
def
(a, b) × (c, d) = (ac − bd, ad + bc).
It turns out that with this multiplication rule, all the standard properties of arithmetic hold. Further,
and most importantly (0, 1) × (0, 1) = (−1, 0).
Generally we just write (a, b) as a + ib, and we treat i as if it were an unknown. We can just
do arithmetic with complex numbers just as we would do with polynomials. The property we just
mentioned becomes i2 = −1. So whenever we see i2 , we can replace it by −1. The numbers i and −i
are roots of r2 + 1 = 0.
Note that engineers often use the letter j instead of i for the square root of −1. We will use the
mathematicians’ convention and use i.
Exercise 2.2.3: Make sure you understand (that you can justify) the following identities:
• i2 = −1, i3 = −i, i4 = 1,
• 1
= −i,
i • (3 − 7i)(−2 − 9i) = · · · = −69 − 13i,
• (3 − 2i)(3 + 2i) = 32 − (2i)2 = 32 + 22 = 13,
• 1
3−2i = 1 3+2i
3−2i 3+2i = 3+2i
13 = 3
13 + 2
i.
13 We can also define the exponential ea+ib of a complex number. We can do this by just writing
down the Taylor series and plugging in the complex number. Because most properties of the
exponential can be proved by looking at the Taylor series, we note that many properties still hold
for the complex exponential. For example, e x+y = e x ey . This means that ea+ib = ea eib and hence if
we can compute eib easily, we can compute ea+ib . Here we will use the so-called Euler’s formula.
Theorem 2.2.2 (Euler’s formula).
eiθ = cos θ + i sin θ and e−iθ = cos θ − i sin θ. 54 CHAPTER 2. HIGHER ORDER LINEAR ODES Exercise 2.2.4: Using Euler’s formula, check the identities:
cos θ = eiθ + e−iθ
2 and sin θ = eiθ − e−iθ
.
2i
2 Exercise 2.2.5: Double angle identities: Start with ei(2θ) = eiθ . Use Euler on each side and
deduce:
cos(2θ) = cos2 θ − sin2 θ
and
sin(2θ) = 2 sin θ cos θ.
We also will need some notation. For a complex number a + ib we call a the real part and b the
imaginary part of the number. Often the following notation is used,
Re(a + ib) = a 2.2.2 and Im(a + ib) = b. Complex roots Now suppose that the equation ay + by + cy = 0 has a characteristic equation ar2 + br + c = 0 that
√
2
has complex roots. By quadratic formula the roots are −b± 2b −4ac . These are complex if b2 − 4ac < 0.
a
In this case we can see that the roots are
√
−b
4ac − b2
r1 , r2 =
±i
.
2a
2a
As you can see, you will always get a pair of roots of the form α ± iβ. In this case we can still write
the solution as
y = C1 e(α+iβ) x + C2 e(α−iβ) x .
However, the exponential is now complex valued. We would need to choose C1 and C2 to be
complex numbers to obtain a real-valued solution (which is what we are after). While there is
nothing particularly wrong with this approach, it can make calculations harder and it is generally
preferred to find two real-valued solutions.
Here we can use Euler’s formula. First let
y1 = e(α+iβ) x and y2 = e(α−iβ) x . Then note that
y1 = eα x cos(β x) + ie x sin(β x),
y2 = eα x cos(β x) − ieα x sin(β x).
We note that linear combinations of solutions are also solutions. Hence,
y1 + y2
y3 =
= eα x cos(β x),
2
y1 − y2
y4 =
= eα x sin(β x),
2i
are also solutions. And furthermore they are real-valued. It is not hard to see that they are linearly
independent (not multiples of each other). Therefore, we have the following theorem. 2.2. CONSTANT COEFFICIENT SECOND ORDER LINEAR ODES 55 Theorem 2.2.3. Take the equation
ay + by + cy = 0.
If the characteristic equation has the roots α ± iβ (when b2 − 4ac < 0), then the general solution is
y = C1 eα x cos(β x) + C2 eα x sin(β x).
Example 2.2.2: Find the general solution of y + k2 y = 0, for a constant k > 0.
The characteristic equation is r2 + k2 = 0. Therefore, the roots are r = ±ik and by the theorem
we have the general solution
y = C1 cos(kx) + C2 sin(kx).
Example 2.2.3: Find the solution of y − 6y + 13y = 0, y(0) = 0, y (0) = 10.
The characteristic equation is r2 − 6r + 13 = 0. By completing the square we get (r − 3)2 + 22 = 0
and hence the roots are r = 3 ± 2i. By the theorem we have the general solution
y = C1 e3 x cos(2 x) + C2 e3 x sin(2 x).
To find the solution satisfying the initial conditions, we first plug in zero to get
0 = y(0) = C1 e0 cos 0 + C2 e0 sin 0 = C1 .
Hence C1 = 0 and y = C2 e3 x sin(2 x). We differentiate
y = 3C2 e3 x sin(2 x) + 2C2 e3 x cos(2 x).
We again plug in the initial condition and obtain 10 = y (0) = 2C2 , or C2 = 5. Hence the solution
we are seeking is
y = 5e3 x sin(2 x). 2.2.3 Exercises Exercise 2.2.6: Find the general solution of 2y + 2y − 4y = 0.
Exercise 2.2.7: Find the general solution of y + 9y − 10y = 0.
Exercise 2.2.8: Solve y −. 56 CHAPTER 2. HIGHER ORDER LINEAR ODES Exercise 2.2.12: Find the general solution of y = 0 using the methods of this section.
Exercise 2.2.13: The method of this section applies to equations of other orders than two. We will
see higher orders later. Try to solve the first order equation 2y + 3y = 0 using the methods of this
section.
Exercise 2.2.14: Let us revisit Euler’s equations of Exercise 2.1.6 on page 50. Suppose now that
(b − a)2 − 4ac < 0. Find a formula for the general solution of ax2 y + bxy + cy = 0. Hint: Note
that xr = er ln x . 2.3. HIGHER ORDER LINEAR ODES 2.3 57 Higher order linear ODEs Note: somewhat more than 1 lecture, §3.2 and §3.3 in [EP]
After reading this lecture, it may be good to first try Project III from the IODE website:.
Most equations that appear in applications tend to be second order. Higher order equations do
appear from time to time, but it is a general assumption of modern physics that the world is “second
order.”
The basic results about linear ODEs of higher order are essentially exactly the same as for
second order equations with 2 replaced by n. The important concept of linear independence is
somewhat more complicated when more than two functions are involved.
For higher order constant coefficient ODEs, the methods are also slightly harder, but we will not
dwell on these. You can always use the methods for systems of linear equations from chapter 3 to
solve higher order constant coefficient equations.
So let us start with a general homogeneous linear equation
y(n) + pn−1 ( x)y(n−1) + · · · + p1 ( x)y + p0 ( x)y = 0. (2.4) Theorem 2.3.1 (Superposition). Suppose y1 , y2 , . . . , yn are solutions of the homogeneous equation
(2.4). Then
y( x) = C1 y1 ( x) + C2 y2 ( x) + · · · + Cn yn ( x)
also solves (2.4) for arbitrary constants C1 , . . . , Cn .
We also have the existence and uniqueness theorem for nonhomogeneous linear equations.
Theorem 2.3.2 (Existence and uniqueness). Suppose p0 through pn−1 , and f are continuous functions and a, b0 , b1 , . . . , bn−1 are constants. The equation
y(n) + pn−1 ( x)y(n−1) + · · · + p1 ( x)y + p0 ( x)y = f ( x)
has exactly one solution y( x) satisfying the initial conditions
y(a) = b0 , 2.3.1 y (a) = b1 , ..., y(n−1) (a) = bn−1 . Linear independence When we had two functions y1 and y2 we said they were linearly independent if one was not the
multiple of the other. Same idea holds for n functions. In this case it is easier to state as follows.
The functions y1 , y2 , . . . , yn are linearly independent if
c1 y1 + c2 y2 + · · · + cn yn = 0,
has only the trivial solution c1 = c2 = · · · = cn = 0. If we can write the equation with a nonzero
constant, say c1 0, then we can solve for y1 as a linear combination of the others. If the functions
are not linearly independent, we say they are linearly dependent. 58 CHAPTER 2. HIGHER ORDER LINEAR ODES Example 2.3.1: Show e x , e2 x , e3 x are linearly independent.
Let us give several ways to show this fact. Many textbooks (including [EP] and [F]) introduce
Wronskians, but that is really not necessary here.
Let us write down
c1 e x + c2 e2 x + c3 e3 x = 0.
We use rules of exponentials and write z = e x . Then we have
c1 z + c2 z2 + c3 z3 = 0.
The left hand side is a third degree polynomial in z. It can either be identically zero, or it can have
at most 3 zeros. Therefore, it is identically zero and c1 = c2 = c3 = 0 and the functions are linearly
independent.
Let us try another way. As before we write
c1 e x + c2 e2 x + c3 e3 x = 0.
This equation has to hold for all x. What we could do is divide through by e3 x to get
c1 e−2 x + c2 e− x + c3 = 0.
As the equation is true for all x, let x → ∞. After taking the limit we see that c3 = 0. Hence our
equation becomes
c1 e x + c2 e2 x = 0.
Rinse, repeat!
How about yet another way. We again write
c1 e x + c2 e2 x + c3 e3 x = 0.
We can evaluate the equation and its derivatives at different values of x to obtain equations for c1 ,
c2 , and c3 . Let us first divide by e x for simplicity.
c1 + c2 e x + c3 e2 x = 0.
We set x = 0 to get the equation c1 + c2 + c3 = 0. Now differentiate both sides
c2 e x + 2c3 e2 x = 0.
We set x = 0 to get c2 + 2c3 = 0. We divide by e x again and differentiate to get 4c3 e2 x = 0. It is clear
that c3 is zero. Then c2 must be zero as c2 = −2c3 , and c1 must be zero because c1 + c2 + c3 = 0.
There is no one best way to do it. All of these methods are perfectly valid.
Example 2.3.2: On the other hand, the functions e x , e− x , and cosh x are linearly dependent. Simply
apply definition of the hyperbolic cosine:
cosh x = e x + e− x
.
2 2.3. HIGHER ORDER LINEAR ODES 2.3.2 59 Constant coefficient higher order ODEs When we have a higher order constant coefficient homogeneous linear equation. The song and
dance is exactly the same as it was for second order. We just need to find more solutions. If the
equation is nth order we need to find n linearly independent solutions. It is best seen by example.
Example 2.3.3: Find the general solution to
y − 3y − y + 3y = 0. (2.5) Try: y = erx . We plug in and get
r3 erx − 3r2 erx − rerx + 3erx = 0.
We divide through by erx . Then
r3 − 3r2 − r + 3 = 0.
The trick now is to find the roots. There is a formula for the roots of degree 3 and 4 polynomials
but it is very complicated. There is no formula for higher degree polynomials. That does not mean
that the roots do not exist. There are always n roots for an nth degree polynomial. They might be
repeated and they might be complex. Computers are pretty good at finding roots approximately for
reasonable size polynomials.
Best place to start is to plot the polynomial and check where it is zero. Or you can try plugging
in. Sometimes it is a good idea to just start plugging in numbers r = −2, −1, 0, 1, 2, . . . and see if
you get a hit. There are some signs that you might have missed a root. For example, if you plug in
−2 into our polynomial you get −15. If you plug in 0 you get 3. That means there is a root between
−2 and 0 because the sign changed.
A good strategy at first is to look for roots −1, 1, or 0, these are easy to see. Our polynomial
happens to have two roots r1 = −1 and r2 = 1. There must be 3 roots and the last root is reasonably
easy to find. The constant term in a polynomial is the multiple of the negations of all the roots
because r3 − 3r2 − r + 3 = (r − r1 )(r − r2 )(r − r3 ). In our case we see that
3 = (−r1 )(−r2 )(−r3 ) = (1)(−1)(−r3 ) = r3 .
You should check that r3 = 3 really is a root. Hence we know that e− x , e x and e3 x are solutions
to (2.5). They are linearly independent as can easily be checked, and there are 3 of them, which
happens to be exactly the number we need. Hence the general solution is
y = C1 e− x + C2 e x + C3 e3 x .
Suppose we were given some initial conditions y(0) = 1, y (0) = 2, and y (0) = 3. Then
1 = y(0) = C1 + C2 + C3 ,
2 = y (0) = −C1 + C2 + 3C3 ,
3 = y (0) = C1 + C2 + 9C3 . 60 CHAPTER 2. HIGHER ORDER LINEAR ODES It is possible to find the solution by high school algebra, but it would be a pain. The only sensible
way to solve a system of equations such as this is to use matrix algebra, see § 3.2. For now we note
that the solution is C1 = −1/4, C2 = 1 and C3 = 1/4. The specific solution to the ODE is
−1 − x
1
e + e x + e3 x .
4
4
Next, suppose that we have real roots, but they are repeated. Let us say we have a root r repeated
k times. In the spirit of the second order solution, and for the same reasons, we have the solutions
y= erx , xerx , x2 erx , . . . , xk−1 erx .
We take a linear combination of these solutions to find the general solution.
Example 2.3.4: Solve
y(4) − 3y + 3y − y = 0.
We note that the characteristic equation is
r 4 − 3r 3 + 3r 2 − r = 0.
By inspection we note that r4 − 3r3 + 3r2 − r = r(r − 1)3 . Hence the roots given with multiplicity
are r = 0, 1, 1, 1. Thus the general solution is
y = (C1 + C2 x + C3 x2 ) e x + C4 . from r = 0 terms coming from r = 1 Similarly to the second order case we can handle complex roots. Complex roots always come in
pairs r = α ± iβ. Suppose we have two such complex roots, each repeated k times. The corresponding
solution is
(C0 + C1 x + · · · + Ck−1 xk−1 ) eα x cos(β x) + (D0 + D1 x + · · · + Dk−1 xk−1 ) eα x sin(β x).
where C0 , . . . , Ck−1 , D0 , . . . , Dk−1 are arbitrary constants.
Example 2.3.5: Solve
y(4) − 4y + 8y − 8y + 4y = 0.
The characteristic equation is
r4 − 4r3 + 8r2 − 8r + 4 = 0,
2 (r2 − 2r + 2) = 0,
2 (r − 1)2 + 1 = 0.
Hence the roots are 1 ± i, both with multiplicity 2. Hence the general solution to the ODE is
y = (C1 + C2 x) e x cos x + (C3 + C4 x) e x sin x.
The way we solved the characteristic equation above is really by guessing or by inspection. It is not
so easy in general. We could also have asked a computer or an advanced calculator for the roots. 2.3. HIGHER ORDER LINEAR ODES 2.3.3 61 Exercises Exercise 2.3.1: Find the general solution for y − y + y − y = 0.
Exercise 2.3.2: Find the general solution for y(4) − 5y + 6y = 0.
Exercise 2.3.3: Find the general solution for y + 2y + 2y = 0.
Exercise 2.3.4: Suppose that the characteristic equation for a differential equation is (r − 1)2 (r − 2)2 =
0. a) Find such a differential equation. b) Find its general solution.
Exercise 2.3.5: Suppose that a fourth order equation has a solution y = 2e4 x x cos x. a) Find such
an equation. b) Find the initial conditions that the given solution satisfies.
Exercise 2.3.6: Find the general solution for the equation of Exercise 2.3.5.
Exercise 2.3.7: Let f ( x) = e x − cos x, g( x) = e x + cos x, and h( x) = cos x. Are f ( x), g( x), and h( x)
linearly independent? If so, show it, if not, find a linear combination that works.
Exercise 2.3.8: Let f ( x) = 0, g( x) = cos x, and h( x) = sin x. Are f ( x), g( x), and h( x) linearly
independent? If so, show it, if not, find a linear combination that works.
Exercise 2.3.9: Are x, x2 , and x4 linearly independent? If so, show it, if not, find a linear combination that works.
Exercise 2.3.10: Are e x , xe x , and x2 e x linearly independent? If so, show it, if not, nd a linear
combination that works. 62 CHAPTER 2. HIGHER ORDER LINEAR ODES 2.4 Mechanical vibrations Note: 2 lectures, §3.4 in [EP]
Let us look at some applications of linear second order constant coefficient equations. 2.4.1 Some examples Our first example is a mass on a spring. Suppose we have
a mass m > 0 (in kilograms) connected by a spring with spring
m
constant k > 0 (in newtons per meter) to a fixed wall. There may be
some external force F (t) (in newtons) acting on the mass. Finally,
damping c
there is some friction measured by c ≥ 0 (in newton-seconds per
meter) as the mass slides along the floor ) − cx − kx or
k F (t) mx + cx + kx = F (t).
This is a linear second order constant coefficient ODE. We set up some terminology about this
equation. We say the motion is
(i) forced, if F 0 (if F is not identically zero),
(ii) unforced or free, if F ≡ 0 (if F is identically zero),
(iii) damped, if c > 0, and
(iv) undamped, if c = 0.
This system appears in lots of applications even if it does not at first seem like it. Many real
world scenarios can be simplified to a mass on a spring. For example, a bungee jump setup is
essentially a mass and spring system (you are the mass). It would be good if someone did the math
before you jump off the bridge, right? Let us give 2 other examples. E C
R L Here is an example for electrical engineers. Suppose that 2.4. MECHANICAL VIBRATIONS 63 in coulombs on the capacitor and I (t) be the current in the circuit. The relation between the two is
Q = I . By elementary principles we have that LI + RI + Q/C = E . If we differentiate we get
LI (t) + RI (t) + 1
I (t) = E (t).
C This is an nonhomogeneous second order constant coefficient.
Our next example is going to behave like a mass and spring system
only approximately. Suppose we have a mass m on a pendulum of length L.
We wish to find an equation for the angle θ(t). Let g be the force of gravity.
Elementary physics mandates that the equation is of the form
θ+ L
θ g
sin θ = 0.
L This equation can be derived using Newton’s second law; force equals mass times acceleration.
The acceleration is Lθ and mass is m. So mLθ has to be equal to the tangential component of the
force given by the gravity. This is mg sin θ in the opposite direction. The m curiously cancels from
the equation.
Now we make our approximation. For small θ we have that approximately sin θ ≈ θ. This can
be seen by looking at the graph. In Figure 2.1 we can see that for approximately −0.5 < θ < 0.5 (in
radians) the graphs of sin θ and θ are almost the same.
-1.0 -0.5 0.0 0.5 1.0 1.0 1.0 0.5 0.5 0.0 0.0 -0.5 -0.5 -1.0
-1.0 -1.0
-0.5 0.0 0.5 1.0 Figure 2.1: The graphs of sin θ and θ (in radians). 64 CHAPTER 2. HIGHER ORDER LINEAR ODES Therefore, when the swings are small, θ is always small and we can model the behavior by the
simpler linear equation
g
θ + θ = 0.
L
Note that the errors that we get from the approximation build up so over a very long time, the
behavior might change more substantially. Also we will see that in a mass spring system, the
amplitude is independent of the period, this is not true for a pendulum. But for reasonably short
periods of time and small swings (for example if the length of the pendulum is very large), the
behavior is reasonably close.
In real world problems it is very often necessary to make these types of simplifications. Therefore, it is good to understand both the mathematics and the physics of the situation to see if the
simplification ω0 = √ k/m, then we can write the equation as
x + ω2 x = 0.
0 The general solution to this equation is
x(t) = A cos(ω0 t) + B sin(ω0 t).
By a trigonometric identity, we have that for two different constants C and γ, we have
A cos(ω0 t) + B sin(ω0 t) = C cos(ω0 t − γ).
√
It is not hard to compute that C = A2 + B2 and tan γ = B/A. Therefore, we let C and γ be our
arbitrary constants and write x(t) = C cos(ω0 t − γ).
Exercise 2.4.1: Justify the above identity and verify the equations for C and γ. Hint: Start with
cos(α − β) = cos(α) cos(β) + sin(α) sin(β) and multiply by C. Then think what should α and β be.
While it is generally easier to use the first form with A and B to solve for the initial conditions,
the second form is much more natural. The constants C and γ have very nice interpretation. We
look at the form of the solution
x(t) = C cos(ω0 t − γ). 2.4. MECHANICAL VIBRATIONS 65 We can see that the amplitude is C , ω0 is the (angular) frequency, and γ is the so-called phase shift.
The phase shift just shifts the graph left or right. We call ω0 the natural (angular) frequency. This
entire setup is usually called simple harmonic motion.
Let us pause to explain the word angular before the word frequency. The units of ω0 are radians
per unit time, not cycles per unit time as is the usual measure of frequency. Because we know one
0
cycle is 2π radians, the usual frequency is given by ωπ . It is simply a matter of where we put the
2
constant 2π, and that is a matter of taste.
2
The period of the motion is one over the frequency (in cycles per unit time) and hence ωπ . That
0
is the amount of time it takes to complete one full oscillation.
Example 2.4.1: Suppose that m = 2 kg and k = 8 N m/s. This gives us the initial conditions.
So the equation with initial conditions is
2 x + 8 x = 0,
x(0) = 0.5,
x (0) = 1.
√
√
We can directly compute ω0 = k/m = 4 = 2. Hence the angular frequency is 2. The usual
frequency in Hertz (cycles per second) is 2/2π = 1/π ≈ 0.318.
The general solution is
x(t) = A cos(2t) + B sin(2t).
Letting x(0) = 0.5 means A = 0.5. Then x (t) √ −2(0.5) sin(2t) + 2 B cos(2t). Letting x (0) = 1 we
=
√
get B = 0.5. Therefore, the amplitude is C = A2 + B2 = 0.5 ≈ 0.707. The solution is
x(t) = 0.5 cos(2t) + 0.5 sin(2t).
A plot of x(t) is shown in Figure 2.2 on the following page.
For the free undamped motion, if the solution is of the form
x(t) = A cos(ω0 t) + B sin(ω0 t),
this corresponds to the initial conditions x(0) = A and x (0) = ω0 B.
Therefore, it is easy to figure out A and B first, and compute the amplitude and the phase shift
using A and B. In the example, we have already found C . Let us compute the phase shift. We know
that tan γ = B/A = 1. We take the arctangent of 1 and get approximately 0.785. As you may recall, 66 CHAPTER 2. HIGHER ORDER LINEAR ODES
1.0 0.0 2.5 5.0 7.5 10.0
1.0 0.5 0.5 0.0 0.0 -0.5 -0.5 -1.0
0.0 2.5 5.0 7.5 -1.0
10.0 Figure 2.2: Simple undamped oscillation. we still need to check if this γ is in the right quadrant. Since both A and B are positive, then γ
should be in the first quadrant, and 0.785 radians really is in the first quadrant.
Note: Many calculators and computer software do not only have the atan function for arctangent,
but also what is sometimes called atan2. This function takes two arguments, B and A, and returns
a γ in the correct quadrant for you. 2.4.3 Free damped motion Let us now focus on damped motion. Let us rewrite the equation
mx + cx + kx = 0,
as
x + 2 px + ω2 x = 0,
0
where
ω0 = k
,
m p= c
.
2m The characteristic equation is
r2 + 2 pr + ω2 = 0.
0
Using the quadratic formula we get that the roots are
r = −p ± p2 − ω2 .
0 The form of the solution depends on whether we get complex or real roots. We get real roots if and
only if the following number is nonnegative.
p2 − ω2 =
0 c
2m 2 − k
c2 − 4km
=
.
m
4m2 2.4. MECHANICAL VIBRATIONS 67 The sign of p2 − ω2 is the same as the sign of c2 − 4km. Thus we get real roots if and only if c2 − 4km
0
is nonnegative.
Overdamping
When c2 − 4km > 0, we say the system is overdamped. In this case, there are two distinct real roots r1
and r2 . Notice that both roots are negative. As
is negative.
The solution is
x(t) = C1 er1 t + C2 er2 t . p2 − ω2 is always less than p, then − p ±
0
0 25 50 75 p2 − ω2
0
100 1.5 1.5 Since r1 , r2 are negative, x(t) → 0 as t → ∞.
Thus the mass will tend towards the rest position
as time goes to infinity. For a few sample plots
for different initial conditions, see Figure 2.3.
Do note that no oscillation happens. In fact,
the graph will cross the x axis at most once. To see
why, we try to solve 0 = C1 er1 t + C2 er2 t . Therefore,
C1 er1 t = −C2 er2 t and using laws of exponents we
obtain
−C1
= e(r2 −r1 )t .
Figure 2.3: Overdamped motion for several difC2
ferent initial conditions.
This equation has at most one solution t ≥ 0. For
some initial conditions the graph will never cross the x axis, as is evident from the sample graphs.
1.0 1.0 0.5 0.5 0.0 0.0 0 25 50 75 100 Example 2.4.2: Suppose the mass is released from rest. That is x(0) = x0 and x (0) = 0. Then
x0
x(t) =
r1 er2 t − r2 er1 t .
r1 − r2
It is not hard to see that this satisfies the initial conditions.
Critical damping
When c2 − 4km = 0, we say the system is critically damped. In this case, there is one root of
multiplicity 2 and this root is − p. Therefore, our solution is
x(t) = C1 e− pt + C2 te−
you can only reach in theory. You are always a little bit underdamped or a little bit overdamped. It
is better not to dwell on critical damping. 68 CHAPTER 2. HIGHER ORDER LINEAR ODES Underdamping
When c2 − 4km < 0, we say the system is
underdamped. In this case, the roots are complex. 0 5 10 15 20 25 30 = −p ± p2 − ω2
0
√ −1 ω2 − p2
0 1.0 0.5 0.5 0.0 0.0 -0.5 r = −p ± 1.0 -0.5 = − p ± iω1 ,
where ω1 = ω2 − p2 . Our solution is
0 x(t) = e− pt A cos(ω1 t) + B sin(ω1 t) ,
or
x(t) = Ce− pt cos(ω1 t − γ). -1.0 -1.0
0 5 10 15 20 25 30 Figure 2.4: Underdamped motion with the envelope curves shown. An example plot is given in Figure 2.4. Note that
we still have that x(t) → 0 as t → ∞.
In the figure we also show the envelope curves Ce− pt and −Ce− γ just shifts the graph left or right but within the envelope curves (the envelope
curves do not change if γ changes).
Finally note that the angular pseudo-frequency (we do not call it a frequency since the solution is
not really a periodic function) ω1 becomes lower.
On the other hand when c becomes smaller, ω1 approaches ω0 (ω1 is always smaller than ω0 ),
and the solution looks more and more like the steady periodic motion of the undamped case. The
envelope curves become flatter and flatter as p goes to 0. 2.4.4 Exercises Exercise 2.4.2: Consider a mass and spring system with a mass m = 2, spring constant k = 3, and
damping constant c = 1. a) Set up and find the general solution of the system. b) Is the system
underdamped, overdamped or critically damped? c) If the system is not critically damped, find a c
that makes the system critically damped. 2.4. MECHANICAL VIBRATIONS 69 Exercise 2.4.3: Do Exercise 2.4.2 for m = 3, k = 12, and c = 12.
Exercise 2.4.4: Using the mks units (meters-kilograms-seconds), suppose you have a spring with
spring constant 4 N/m. You want to use it to weight items. Assume no friction. You place the mass
on the spring and put it in motion. a) You count and find that the frequency is 0.8 Hz (cycles per
second). What is the mass? b) Find a formula for the mass m given the frequency ω floor (you wish to find c). You have a spring with spring constant k = 5 N/m. You take the
spring, you attach it to the mass and fix it to a wall. Then you pull on the spring and let the mass go.
You find that the mass oscillates with frequency 1 Hz. What is the friction? 70 2.5 CHAPTER 2. HIGHER ORDER LINEAR ODES Nonhomogeneous equations Note: 2 lectures, §3.5 in [EP] 2.5.1 Solving nonhomogeneous equations We have solved linear constant coefficient homogeneous equations. What about nonhomogeneous
linear ODEs? For example, the equations for forced mechanical vibrations. That is, suppose we
have an equation such as
y + 5y + 6y = 2 x + 1.
(2.6)
We will generally write Ly = 2 x + 1 when the exact form of the operator is not important. We
solve (2.6) in the following manner. We find the general solution yc to the associated homogeneous
equation
y + 5y + 6y = 0.
(2.7)
We call yc the complementary solution. We also find a single particular solution y p to (2.6) in some
way and then
y = yc + y p
is the general solution to (2.6) (we will see why in a moment).
Note that y p can be any solution. Suppose you find a different particular solution y p . Write the
˜
difference as w = y p − y p . Then plug w into the left hand side of the equation to get
˜
w + 5w + 6w = (y p + 5y p + 6y p ) − (˜ p + 5˜ p + 6˜ p ) = (2 x + 1) − (2 x + 1) = 0.
y
y
y
In other words, w is a complementary solution. Using the operator notation the calculation becomes
simpler. As L is a linear operator and so we could just write
Lw = L(y p − y p ) = Ly p − Ly p = (2 x + 1) − (2 x + 1) = 0.
˜
˜
So w = y p − y p is a solution to (2.7). Any two solutions of (2.6) differ by a solution to the
˜
homogeneous equation (2.7). The solution y = yc + y p includes all solutions to (2.6), since yc is the
general solution to the associated homogeneous equation.
Theorem 2.5.1. Let Ly = f ( x) be a linear ODE (not necessarily constant coefficient). Let yc be
the general solution to the associated homogeneous equation Ly = 0 and let y p be any particular
solution to Ly = f ( x). Then the general solution to Ly = f ( x) is
y = yc + y p .
The moral of the story is that we can find the particular solution in any old way. If we find a
different particular solution (by a different method, or simply by guessing), then we still get the
same general solution. The formula may look different, and the constants you will have to choose to
satisfy the initial conditions may be different, but it is the same solution. 2.5. NONHOMOGENEOUS EQUATIONS 2.5.2 71 Undetermined coefficients The trick is to somehow, in a smart way, guess one particular solution to (2.6). Note that 2 x + 1 is a
polynomial, and the left hand side of the equation will be a polynomial if we let y be a polynomial
of the same degree. Let us try
y = Ax + B.
We plug in to obtain
y + 5y + 6y = (Ax + B) + 5(Ax + B) + 6(Ax + B) = 0 + 5A + 6Ax + 6 B = 6Ax + (5A + 6 B).
So 6Ax + (5A + 6 B) = 2 x + 1. Therefore, A = 1/3 and B = −1/9. That means y p =
Solving the complementary problem (Exercise!) we get 1
3 x− 1
9 = 3 x −1
.
9 yc = C1 e−2 x + C2 e−3 x .
Hence the general solution to (2.6) is
y = C1 e−2 x + C2 e−3 x + 3x − 1
.
9 Now suppose we are further given some initial conditions. For example, y(0) = 0 and y (0) = 1/3.
First find y = −2C1 e−2 x − 3C2 e−3 x + 1/3. Then
1
0 = y(0) = C1 + C2 − ,
9 1
1
= y (0) = −2C1 − 3C2 + .
3
3 We solve to get C1 = 1/3 and C2 = −2/9. The particular solution we want is
2
3 x − 1 3e−2 x − 2e−3 x + 3 x − 1
1
=
.
y( x) = e−2 x − e−3 x +
3
9
9
9
Exercise 2.5.1: Check that y really solves the equation (2.6) and the given initial conditions.
Note: A common mistake is to solve for constants using the initial conditions with yc and only
adding the particular solution y p after that. That will not work. You need to first compute y = yc + y p
and only then solve for the constants using the initial conditions.
A right hand side consisting of exponentials, sines, and cosines can be handled similarly. For
example,
y + 2y + 2y = cos(2 x).
Let us simply find some y p . We notice that we may have to also guess sin(2 x) since derivatives of
cosine are sines. We guess
y p = A cos(2 x) + B sin(2 x). 72 CHAPTER 2. HIGHER ORDER LINEAR ODES We plug y p into the equation and we get
−4A cos(2 x) − 4 B sin(2 x) − 4A sin(2 x) + 4 B cos(2 x) + 2A cos(2 x) + 2 B sin(2 x) = cos(2 x).
The left hand side must equal to right hand side. We group terms and we get that −4A + 4 B + 2A = 1
and −4 B − 4A + 2 B = 0. So −2A + 4 B = 1 and 2A + B = 0 and hence A = −1/10 and B = 1/5. So
y p = A cos(2 x) + B sin(2 x) = − cos(2 x) + 2 sin(2 x)
.
10 Similarly, if the right hand side contains exponentials we guess exponentials. For example, if
the equation is (where L is a linear constant coefficient operator)
Ly = e3 x ,
we will guess y = Ae3 x . We note also that using the product rule for differentiation gives us a way to
combine these guesses. If we can guess a form for y such that Ly has all the terms needed to for the
right hand side, that is a good place to start. For example,
Ly = (1 + 3 x2 ) e− x cos(π x).
We will guess
y = (A + Bx + Cx2 ) e− x cos(π x) + (D + Ex + F x2 ) e− x sin(π x).
We will plug in and then hopefully get equations that we can solve for A, B, C, D, E , F . As you can
see this can make for a very long and tedious calculation very quickly. C’est la vie!
There is one hiccup in all this. It could be that our guess actually solves the associated
homogeneous equation. That is, suppose we have
y − 9y = e3 x .
We would love to guess y = Ae3 x , but if we plug this into the left hand side of the equation we get
y − 9y = 9Ae3 x − 9Ae3 x = 0 e3 x . There is no way we can choose A to make the left hand side be e3 x . The trick in this case is to
multiply our guess by x until we get rid of duplication with the complementary solution. That is
first we compute yc (solution to Ly = 0)
yc = C1 e−3 x + C2 e3 x
and we note that the e3 x term is a duplicate with our desired guess. We modify our guess to
y = Axe3 x and notice there is no duplication anymore. Let us try. Note that y = Ae3 x + 3Axe3 x and
y = 6Ae3 x + 9Axe3 x . So
y − 9y = 6Ae3 x + 9Axe3 x − 9Axe3 x = 6Ae3 x . 2.5. NONHOMOGENEOUS EQUATIONS 73 So 6Ae3 x is supposed to equal e3 x . Hence, 6A = 1 and so A = 1/6. Thus we can now write the
general solution as
1
y = yc + y p = C1 e−3 x + C2 e3 x + xe3 x .
6
Now what about the case when multiplying by x does not get rid of duplication. For example,
y − 6y + 9y = e3 x .
Note that yc = C1 e3 x + C2 xe3 x . So guessing y = Axe3 x would not get us anywhere. In this case we
want to guess y = Ax2 e3 x . Basically, we want to multiply our guess by x until all duplication is gone.
But no more! Multiplying too many times will also make the process not work.
Finally what if the right hand side is several terms, such as
Ly = e2 x + cos x.
In this case we find u that solves Lu = e2 x and v that solves Lv = cos x (do each term separately).
Then note that if y = u + v, then Ly = e2 x + cos x. This is because L is linear; we have Ly =
L(u + v) = Lu + Lv = e2 x + cos x. 2.5.3 Variation of parameters The method of undetermined coefficients will work for many basic problems that crop up. But it
does not work all the time. It only works when the right hand side of the equation Ly = f ( x) has
only finitely many linearly independent derivatives, so that we can write a guess that consists of
them all. Some equations are a bit tougher. Consider
y + y = tan x.
Note that each new derivative of tan x looks completely different and cannot be written as a linear
combination of the previous derivatives. We get sec2 x, 2 sec2 x tan x, etc. . . .
This equation calls for a different method. We present the method of variation of parameters,
which will handle any equation of the form Ly = f ( x), provided we can solve certain integrals. For
simplicity, we will restrict ourselves to second order equations, but the method will work for higher
order equations just as well (the computations will be more tedious).
Let us try to solve the example
Ly = y + y = tan x.
First we find the complementary solution Ly = 0. We get yc = C1 y1 + C2 y2 , where y1 = cos x and
y2 = sin x. Now to try to find a solution to the nonhomogeneous equation we try
y p = y = u1 y1 + u2 y2 , 74 CHAPTER 2. HIGHER ORDER LINEAR ODES where u1 and u2 are functions and not constants. We are trying to satisfy Ly = tan x. That gives us
one condition on the functions u1 and u2 . Compute (note the product rule!)
y = (u1 y1 + u2 y2 ) + (u1 y1 + u2 y2 ).
We can still impose one more condition at our will to simplify computations (we have two unknown
functions, so we are allowed two conditions). We require that (u1 y1 + u2 y2 ) = 0. This makes
computing the second derivative easier.
y = u1 y1 + u2 y2 ,
y = (u1 y1 + u2 y2 ) + (u1 y1 + u2 y2 ).
Since y1 and y2 are solutions to y + y = 0, we know that y1 = −y1 and y2 = −y2 . (Note: If the
equation was instead y + ay + by = 0 we would have yi = −ayi − byi .) So
y = (u1 y1 + u2 y2 ) − (u1 y1 + u2 y2 ).
Now note that
y = (u1 y1 + u2 y2 ) − y,
and hence
y + y = Ly = u1 y1 + u2 y2 .
For y to satisfy Ly = f ( x) we must have f ( x) = u1 y1 + u2 y2 .
So what we need to solve are the two equations (conditions) we imposed on u1 and u2
u1 y1 + u2 y2 = 0,
u1 y1 + u2 y2 = f ( x).
We can now solve for u1 and u2 in terms of f ( x), y1 and y2 . You will always get these formulas for
any Ly = f ( x). There is a general formula for the solution you can just plug into, but it is better to
just repeat what we do below. In our case the two equations become
u1 cos( x) + u2 sin( x) = 0,
−u1 sin( x) + u2 cos( x) = tan( x).
Hence
u1 cos( x) sin( x) + u2 sin2 ( x) = 0,
−u1 sin( x) cos( x) + u2 cos2 ( x) = tan( x) cos( x) = sin( x). 2.5. NONHOMOGENEOUS EQUATIONS 75 And thus
u2 sin2 ( x) + cos2 ( x) = sin( x),
u2 = sin( x),
u1 = − sin2 ( x)
= − tan( x) sin( x).
cos( x) Now we need to integrate u1 and u2 to get u1 and u2 .
1
sin( x) − 1
ln
+ sin( x),
2
sin( x) + 1 u1 = u1 dx = − tan( x) sin( x) dx = u2 = u2 dx = sin( x) dx = − cos( x). So our particular solution is
y p = u1 y1 + u2 y2 = sin( x) − 1
1
cos( x) ln
+ cos( x) sin( x) − cos( x) sin( x) =
2
sin( x) + 1
1
sin( x) − 1
= cos( x) ln
.
2
sin( x) + 1 The general solution to y + y = tan x is, therefore,
y = C1 cos( x) + C2 sin( x) + 2.5.4 sin( x) − 1
1
cos( x) ln
.
2
sin( x) + 1 Exercises Exercise 2.5.2: Find a particular solution of y − y − 6y = e2 x .
Exercise 2.5.3: Find a particular solution of y − 4y + 4y = e2 x .
Exercise 2.5.4: Solve the initial value problem y + 9y = cos(3 x) + sin(3 x) for y(0) = 2, y (0) = 1.
Exercise 2.5.5: Setup the form of the particular solution but do not solve for the coefficients for
y(4) − 2y + y = e x .
Exercise 2.5.6: Setup the form of the particular solution but do not solve for the coefficients for
y(4) − 2y + y = e x + x + sin x.
Exercise 2.5.7: a) Using variation of parameters find a particular solution of y − 2y + y = e x . b)
Find a particular solution using undetermined coefficients. c) Are the two solutions you found the
same? What is going on?
Exercise 2.5.8: Find a particular solution of y − 2y + y = sin( x2 ). It is OK to leave the answer as
a definite integral. 76 2.6 CHAPTER 2. HIGHER ORDER LINEAR ODES Forced oscillations and resonance Note: 2 lectures, §3.6 in [EP]
k F (t)
m Let us return back to the mass on a spring example. We will
now consider the case of forced oscillations. That is, we will
consider the equation
mx + cx + kx = F (t) damping c for some nonzero F (t). The setup is again: m is mass, c is friction, k is the spring constant and F (t)
is an external force acting on the mass.
What we are interested in is some periodic forcing, such as noncentered rotating parts, or perhaps
even loud sounds or other sources of periodic force. Once we learn about Fourier series in chapter 4
we will see that we cover all periodic functions by simply considering F (t) = F0 cos(ωt) (or sine
instead of cosine, the calculations will be essentially the same). 2.6.1 Undamped forced motion and resonance First let us consider undamped (c = 0) motion for simplicity. We have the equation
mx + kx = F0 cos(ωt).
This equation has the complementary solution (solution to the associated homogeneous equation)
xc = C1 cos(ω0 t) + C2 sin(ω0 t),
√
where ω0 = k/m is the natural frequency (angular). It is the frequency at which the system “wants
to oscillate” without external interference.
Let us suppose that ω0 ω. Try the solution x p = A cos(ωt) and solve for A. Note that we need
not have sine in our trial solution as on the left hand side we will only get cosines anyway. If you
include a sine it is fine; you will find that its coefficient will be zero (I could not find a rhyme).
We solve using the method of undetermined coefficients. We find that
xp = F0
cos(ωt).
− ω2 ) m(ω2
0 We leave it as an exercise to do the algebra required.
The general solution is
x = C1 cos(ω0 t) + C2 sin(ω0 t) + F0
cos(ωt).
m(ω2 − ω2 )
0 2.6. FORCED OSCILLATIONS AND RESONANCE 77 or written another way
x = C cos(ω0 t − γ) + F0
cos(ωt).
− ω2 ) m(ω2
0 Hence it is a superposition of two cosine waves at different frequencies.
Example 2.6.1: Take
0.5 x + 8 x = 10 cos(πt), x(0) = 0, x (0) = 0.
√
Let us compute. First we read off the parameters: ω = π, ω0 = 8/0.5 = 4, F0 = 10, m = 0.5.
The general solution is
x = C1 cos(4t) + C2 sin(4t) + 20
cos(πt).
16 − π2 Solve for C1 and C2 using the initial conditions. It is easy to see that C1 =
Hence
20
x=
cos(πt) − cos(4t) .
16 − π2
Notice the “beating” behavior in Figure 2.5.
First use the trigonometric identity
0 5 10 −20
16−π2 15 and C2 = 0. 20 10 A−B
A+B
sin
= cos B − cos A
2
2 5 5 0 0 -5 2 sin 10 -5 to get that
20
4−π
4+π
x=
2 sin
t sin
t.
2
16 − π
2
2
Notice that x is a high frequency wave modulated
by a low frequency wave.
-10 -10
0 5 10 15 20 Now suppose that ω0 = ω. Obviously, we
cannot try the solution A cos(ωt) and then use the Figure 2.5: Graph of 1620π2 cos(πt) − cos(4t) .
−
method of undetermined coefficients. We notice
that cos(ωt) solves the associated homogeneous equation. Therefore, we need to try x p = At cos(ωt)+
Bt sin(ωt). This time we do need the sine term since the second derivative of t cos(ωt) does contain
sines. We write the equation
F0
x + ω2 x =
cos(ωt).
m
Plugging into the left hand side we get
2 Bω cos(ωt) − 2Aω sin(ωt) = F0
cos(ωt).
m 78 CHAPTER 2. HIGHER ORDER LINEAR ODES Hence A = 0 and B = F0
.
2mω Our particular solution is F0
2mω x = C1 cos(ωt) + C2 sin(ωt) + t sin(ωt) and our general solution is
F0
t sin(ωt).
2mω The important term is the last one (the particular solution we found). We can see that this term
t
F0
grows without bound as t → ∞. In fact it oscillates between 2F0ω and −mωt . The first two terms only
m
2
2
2
oscillate between ± C1 + C2 , which becomes smaller and smaller in proportion to the oscillations
of the last term as t gets larger. In Figure 2.6 we see the graph with C1 = C2 = 0, F0 = 2, m = 1,
ω = π.
By forcing the system in just the right frequency we produce very wild oscillations. This
kind of behavior is called resonance or sometimes
1
is due to different buildings having different resoFigure 2.6: Graph of π t sin(πt).
nance frequencies. So figuring out the resonance
frequency can be very important.
A common (but wrong) example of destructive force of resonance is the Tacoma Narrows bridge
failure. It turns out there was an altogether different phenomenon at play there∗ .
0 5 10 15 20 5.0 5.0 2.5 2.5 0.0 0.0 -2.5 -2.5 -5.0 -5.0 0 2.6.2 5 10 15 20 Damped forced motion and practical resonance In real life things are not as simple as they were above. There is, of course, some damping. Our
equation becomes
mx + cx + kx = F0 cos(ωt),
(2.8)
for some c > 0. We have solved the homogeneous problem before. We let
p=
∗ c
2m ω0 = k
.
m K. Billah and R. Scanlan, Resonance, Tacoma Narrows Bridge Failure, and Undergraduate Physics Textbooks,
American Journal of Physics, 59(2), 1991, 118–124, 2.6. FORCED OSCILLATIONS AND RESONANCE 79 We replace equation (2.8) with
x + 2 px + ω2 x =
0 F0
cos(ωt).
m We find the roots of the characteristic equation of the associated homogeneous problem are r1 , r2 =
−p ± p2 − ω2 . The form of the general solution of the associated homogeneous equation depends
0 on the sign of p2 − ω2 , or equivalently on the sign of c2 − 4km, as we have seen before. That is
0 C1 er1 t + C2 er2 t if c2 > 4km, − pt xc = C1 e + C2 te− pt
if c2 = 4km, − pt
e C cos(ω t) + C sin(ω t) if c2 < 4km , 1
1
2
1
where ω1 = ω2 − p2 . In any case, we can see that xc (t) → 0 as t → ∞. Furthermore, there can
0
be no conflicts when trying to solve for the undetermined coefficients by trying x p = A cos(ωt) +
B sin(ωt). Let us plug in and solve for A and B. We get (the tedious details are left to reader)
(ω2 − ω2 ) B − 2ω pA sin(ωt) + (ω2 − ω2 )A + 2ω pB cos(ωt) =
0
0 F0
cos(ωt).
m We get that
A=
B=
We also compute C = √ (ω2 − ω2 )F0
0
2 , 2 . m(2ω p)2 + m(ω2 − ω2 )
0
2ω pF0
m(2ω p)2 + m(ω2 − ω2 )
0 A2 + B2 to be
C= F0
m (2ω p) +
2 .
(ω2
0 − 2
ω2 ) Thus our particular solution is
xp = (ω2 − ω2 )F0
0
m(2ω p) +
2 m(ω2
0 − 2
ω2 ) cos(ωt) + 2ω pF0 Or in the other notation we have amplitude C and phase shift γ where (if ω
tan γ = 2 m(2ω p) + m(ω2 − ω2 )
0
2 2ω p
B
=2
.
A ω0 − ω2 sin(ωt)
ω0 ) 80 CHAPTER 2. HIGHER ORDER LINEAR ODES Hence we have
xp = F0 cos(ωt − γ).
2 m (2ω p)2 + (ω2 − ω2 )
0 F0
If ω = ω0 we see that A = 0, B = C = 2mω p , and γ = π/2.
The exact formula is not as important as the idea. You should not memorize the above formula,
you should remember the ideas involved. For different forcing function F , you will get a different
formula for x p . So there is no point in memorizing this specific formula. You can always recompute
it later or look it up if you really need it. For reasons we will explain in a moment, we will call xc the transient solution and denote it
by xtr . We will call the x p we found above the steady periodic solution and denote it by x sp . The
general solution to our problem is
x = xc + x p = xtr + x sp .
We note that xc = xtr goes to zero as t → ∞,
as all the terms involve an exponential with a
negative exponent. Hence for large t, the effect
of xtr is negligible and we will essentially only
see x sp . Hence the name transient. Notice that
x sp involves no arbitrary constants, and the initial
conditions will only affect xtr . This means that
the effect of the initial conditions will be negligible after some period of time. Because of this
behavior, we might as well focus on the steady
periodic solution and ignore the transient solution. See Figure 2.7 for a graph of different initial
conditions.
Notice that the speed at which xtr goes to zero
Figure 2.7: Solutions with different initial condepends on p (and hence c). The bigger p is (the
ditions for parameters k = 1, m = 1, F0 = 1,
bigger c is), the “faster” xtr becomes negligible.
c = 0.7, and ω = 1.1.
So the smaller the damping, the longer the “transient region.” This agrees with the observation
that when c = 0, the initial conditions affect the behavior for all time (i.e. an infinite “transient
region”).
0 5 10 15 20 5.0 5.0 2.5 2.5 0.0 0.0 -2.5 -2.5 -5.0 -5.0 0 5 10 15 20 Let us describe what we mean by resonance when damping is present. Since there were no
conflicts when solving with undetermined coefficient, there is no term that goes to infinity. What we
will look at however is the maximum value of the amplitude of the steady periodic solution. Let C
be the amplitude of x sp . If we plot C as a function of ω (with all other parameters fixed) we can find
its maximum. We call the ω that achieves this maximum the practical resonance frequency. We call 2.6. FORCED OSCILLATIONS AND RESONANCE 81 the maximal amplitude C (ω) the practical resonance amplitude. Thus when damping is present we
talk of practical resonance rather than pure resonance. A sample plot for three different values of c
is given in Figure 2.8. As you can see the practical resonance amplitude grows as damping gets
smaller, and any practical resonance can disappear when damping is large.
0.0 0.5 1.0 1.5 2.0 2.5 3.0 2.5 2.5 2.0 2.0 1.5 1.5 1.0 1.0 0.5 0.5 0.0 0.0
0.0 0.5 1.0 1.5 2.0 2.5 3.0 Figure 2.8: Graph of C (ω) showing practical resonance with parameters k = 1, m = 1, F0 = 1. The
top line is with c = 0.4, the middle line with c = 0.8, and the bottom line with c = 1.6.
To find the maximum we need to find the derivative C (ω). Computation shows
C (ω) = −4ω(2 p2 + ω2 − ω2 )F0
0
2 3/2 m (2ω p)2 + (ω2 − ω2 )
0 . This is zero either when ω = 0 or when 2 p2 + ω2 − ω2 = 0. In other words, C (ω) = 0 when
0
ω= ω2 − 2 p2
0 or ω = 0. It can be shown that if ω2 − 2 p2 is positive, then ω2 − 2 p2 is the practical resonance frequency
0
0
(that is the point where C (ω) is maximal, note that in this case C (ω) > 0 for small ω). If ω = 0 is
the maximum, then essentially there is no practical resonance since we assume that ω > 0 in our
system. In this case the amplitude gets larger as the forcing frequency gets smaller.
If practical resonance occurs, the frequency is smaller than ω0 . As damping c (and hence p)
becomes smaller, the closer the practical resonance frequency goes to ω0 . So when damping is very
small, ω0 is a good estimate of the resonance frequency. This behavior agrees with the observation
that when c = 0, then ω0 is the resonance frequency.
The behavior will be more complicated if the forcing function is not an exact cosine wave, but
for example a square wave. It will be good to come back to this section once you have learned about
the Fourier series. 82 2.6.3 CHAPTER 2. HIGHER ORDER LINEAR ODES Exercises Exercise 2.6.1: Derive a formula for x sp if the equation is mx + cx + kx = F0 sin(ωt). Assume
c > 0.
Exercise 2.6.2: Derive a formula for x sp if the equation is mx + cx + kx = F0 cos(ωt) + F1 cos(3ωt).
Assume c > 0.
Exercise 2.6.3: Take mx + cx + kx = F0 cos(ωt). Fix m > 0 and k > 0. Now think of the function
C (ω). For what values of c (solve in terms of m, k, and F0 ) will there be no practical resonance
(that is, for what values of c is there no maximum of C (ω) for ω > 0).
Exercise 2.6.4: Take mx + cx + kx = F0 cos(ωt). Fix c > 0 and k > 0. Now think of the function
C (ω). For what values of m (solve in terms of c, k, and F0 ) will there be no practical resonance
(that is, for what values of m is there no maximum of C (ω) for ω >ω2 cos(ωt).
a) What is the natural frequency of the water tower.
b) If ω is not the natural frequency, find a formula for the maximal amplitude of the resulting
oscillations of the water container (the maximal deviation from the rest position). The motion will
be a high frequency wave modulated by a low frequency wave, so simply find? Chapter 3
Systems of ODEs
3.1 Introduction to systems of ODEs Note: 1 lecture, §4.1 in [EP]
Often we do not have just one dependent variable and one equation. And as we will see, we
may end up with systems of several equations and several dependent variables even if we start with
a single equation.
If we have several dependent variables, suppose y1 , y2 , . . . , yn we can have a differential equation
involving all of them and their derivatives. For example, y1 = f (y1 , y2 , y1 , y2 , x). Usually, when we
have two dependent variables we would have two equations such as
y1 = f1 (y1 , y2 , y1 , y2 , x),
y2 = f2 (y1 , y2 , y1 , y2 , x),
for some functions f1 and f2 . We call the above a system of differential equations. More precisely, it
is a second order system. Sometimes a system is easy to solve by solving for one variable and then
for the second variable.
Example 3.1.1: Take the first order system
y1 = y1 ,
y2 = y1 − y2 ,
with initial conditions of the form y1 (0) = 1, y2 (0) = 2.
We note that y1 = C1 e x is the general solution of the first equation. We can then plug this y1 into
the second equation and get the equation y2 = C1 e x − y2 , which is a linear first order equation that is
easily solved for y2 . By the method of integrating factor we get
e x y2 = C1 2 x
e + C2 ,
2
83 84
or y2 = CHAPTER 3. SYSTEMS OF ODES
C1 x
e
2 + C2 e− x . The general solution to the system is, therefore,
y1 = C1 e x ,
y2 = C1 x
e + C 2 e− x .
2 We can now solve for C1 and C2 given the initial conditions. We substitute x = 0 and find that
C1 = 1 and C2 = 3/2.
Generally, we will not be so lucky to be able to solve like in the first example, and we will have
to solve for all variables at once.
As an example application, let us think of mass and spring
systems again. Suppose we have one spring with constant k but
m2
m2
two masses m1 and m2 . We can think of the masses as carts, and
we will suppose that they ride along with no friction. Let x1 be the
displacement of the first cart and x2 be the displacement of the second cart. That is, we put the two
carts somewhere with no tension on the spring, and we mark the position of the first and second cart
and call those the zero position. That is, x1 = 0 is a different position on the floor than the position
corresponding to x2 = 0. The force exerted by the spring on the first cart is k( x2 − x1 ), since x2 − x1
is how far the string is stretched (or compressed) from the rest position. The force exerted on the
second cart is the opposite, thus the same thing with a negative sign. Newton’s second law states
that force equals mass times acceleration.
k m1 x1 = k( x2 − x1 ),
m2 x2 = −k( x2 − x1 ).
In this system we cannot solve for the x1 variable separately. That we must solve for both x1
and x2 at once is intuitively obvious, since where the first cart goes depends exactly on where the
second cart goes and vice-versa.
Before we talk about how to handle systems, let us note that in some sense we need only consider
first order systems. Take an nth order differential equation
y(n) = F (y(n−1) , . . . , y , y, x).
Define new variables u1 , . . . , un and write the system
u1 = u2
u2 = u3
.
.
.
un−1 = un
un = F (un , un−1 , . . . , u2 , u1 , x). 3.1. INTRODUCTION TO SYSTEMS OF ODES 85 Now try to solve this system for u1 , u2 , . . . , un . Once you have solved for the u’s, you can discard u2
through un and let y = u1 . We note that this y solves the original equation.
A similar process can be followed for a system of higher order differential equations. For
example, a system of k differential equations in k unknowns, all of order n, can be transformed into
a first order system of n × k equations and n × k unknowns.
Example 3.1.2: Sometimes we can use this idea in reverse as well. Let us take the system
x = 2y − x, y = x, where the independent variable is t. We wish to solve for the initial conditions x(0) = 1, y(0) = 0.
We first notice that if we differentiate the first equation once we get y = x and now we know
what x is in terms of x and y.
y = x = 2y − x = 2y − y .
So we now have an equation y + y − 2y = 0. We know how to solve this equation and we find that
y = C1 e−2t + C2 et . Once we have y we can plug in to get x.
x = y = −2C1 e−2t + C2 et .
We solve for the initial conditions 1 = x(0) = −2C1 + C2 and 0 = y(0) = C1 + C2 . Hence, C1 = −C2
and 1 = 3C2 . So C1 = −1/3 and C2 = 1/3. Our solution is
2e−2t + et
x=
,
3 −e−2t + et
y=
.
3 Exercise 3.1.1: Plug in and check that this really is the solution.
It is useful to go back and forth between systems and higher order equations for other reasons.
For example, the ODE approximation methods are generally only given as solutions for first order
systems. It is not very hard to adapt the code for the Euler method for a first order equation to first was what we will call a linear first order system, as none of the dependent
variables appear in any functions or with any higher powers than one. It is also autonomous as the
equations do not depend on the independent variable t.
For autonomous systems we can easily draw the so-called direction field or vector field. That is,
a plot similar to a slope field, but instead of giving a slope at each point, we give a direction (and a
magnitude). The previous example x = 2y − x, y = x says that at the point ( x, y) the direction in
which we should travel to satisfy the equations should be the direction of the vector (2y − x, x) with
the speed equal to the magnitude of this vector. So we draw the vector (2y − x, x) based at the point 86 CHAPTER 3. SYSTEMS OF ODES ( x, y) and we do this for many points on the xy-plane. We may want to scale down the size of our
vectors to fit many of them on the same direction field. See Figure 3.1.
We can now draw a path of the solution in the plane. That is, suppose the solution is given by
x = f (t), y = g(t), then we can pick an interval of t (say 0 ≤ t ≤ figure the line starts at (1, 0) and travels along
the vector field for a distance of 2 units of t. Since we solved this system precisely we can compute
x(2) and y(2). We get that x(2) ≈ 2.475 and y(2) ≈ 2.457. This point corresponds to the top right
end of the plotted solution curve in the figure.
-1 0 1 2 3 -1 0 1 2 3 3 3 3 3 2 2 2 2 1 1 1 1 0 0 0 0 -1 -1 -1
-1 0 1 2 3 Figure 3.1: The direction field for x = 2y − x,
y = x. -1
-1 0 1 2 3 Figure 3.2: The direction field for x = 2y − x,
y = x with the trajectory of the solution starting
at (1, 0) for 0 ≤ t ≤ 2. field, since the field changes as
t changes. For each t we would get a different direction field. 3.1.1 Exercises Exercise 3.1.2: Find the general solution of x1 = x2 − x1 + t, x2 = x2 .
Exercise 3.1.3: Find the general solution of x1 = 3 x1 − x2 + et , x2 = x1 .
Exercise 3.1.4: Write ay + by + cy = f ( x) as a first order system of ODEs.
Exercise 3.1.5: Write x + y2 y − x3 = sin(t), y + ( x + y )2 − x = 0 as a first order system of ODEs. 3.2. MATRICES AND LINEAR SYSTEMS 3.2 87 Matrices and linear systems Note: 1 and a half lectures, first part of §5.1 in [EP] 3.2.1 Matrices and vectors Before we can start talking about linear systems of ODEs, we will need to talk about matrices, so
let us review these briefly. A matrix is an m × n array of numbers (m rows and n columns). For
example, we denote a 3 × 5 matrix as follows a11 a12 a13 a14 a15 A = a21 a22 a23 a24 a25 . a31 a32 a33 a34 a35
By a vector we will usually mean a column vector that is an n × 1 matrix. If we mean a row
vector we will explicitly say so (a row vector is a 1 × n matrix). We will usually denote matrices by
upper case letters and vectors by lower case letters with an arrow such as x or b. By 0 we will mean
the vector of all zeros.
It is easy to define some operations on matrices. Note that we will want 1 × 1 matrices to really
act like numbers, so our operations will have to be compatible with this viewpoint.
First, we can multiply by a scalar (a number). This means just multiplying each entry by the
same number. For example,
123
246
2
=
.
456
8 10 12
Matrix addition is also easy. We add matrices element by element. For example,
123
1 1 −1
23 2
+
=
.
456
02 4
4 7 10
If the sizes do not match, then addition is not defined.
If we denote by 0 the matrix of with all zero entries, by c, d some scalars, and by A, B, C some
matrices, we have the following familiar rules.
A + 0 = A = 0 + A,
A + B = B + A,
(A + B) + C = A + ( B + C ),
c(A + B) = cA + cB,
(c + d)A = cA + dA. 88 CHAPTER 3. SYSTEMS OF ODES Another useful operation for matrices is the so-called transpose. This operation just swaps rows
and columns of a matrix. The transpose of A is denoted by AT . Example:
123
456 3.2.2 T 1 4 = 2 5 36 Matrix multiplication Let us now define matrix multiplication. First we define the so-called dot product (or inner product)
of two vectors. Usually this will be a row vector multiplied with a column vector of the same size.
For the dot product we multiply each pair of entries from the first and the second vector and we sum
these products. The result is a single number. For example, a1 a2 b 1 a3 · b2 = a1 b1 + a2 b2 + a3 b3 . b3 And similarly for larger (or smaller) vectors.
Armed with the dot product we can define the product of matrices. First let us denote by rowi (A)
the ith row of A and by column j (A) the jth column of A. Now for an m × n matrix A and an n × p
matrix B we can define the product AB. We let AB be an m × p matrix whose i jth entry is
rowi (A) · column j ( B).
Do note how the sizes match up. Example: 1 0 −1 1 2 3 1 1 1 = 4 5 6 10 0
= 1·1+2·1+3·1
4·1+5·1+6·1 1·0+2·1+3·0
4·0+5·1+6·0 1 · (−1) + 2 · 1 + 3 · 0
621
=
4 · (−1) + 5 · 1 + 6 · 0
15 5 1 For multiplication we will want an analogue of a 1. This is the so-called identity matrix. The
identity matrix is a square matrix with 1s on the main diagonal and zeros everywhere else. It is
usually denoted by I . For each size we have a different identity matrix and so sometimes we may
denote the size as a subscript. For example, the I3 would be the 3 × 3 identity matrix 1 0 0 I = I3 = 0 1 0 . 001 3.2. MATRICES AND LINEAR SYSTEMS 89 We have the following rules for matrix multiplication. Suppose that A, B, C are matrices of the
correct sizes so that the following make sense. Let α denote a scalar (number).
A( BC ) = (AB)C,
A( B + C ) = AB + AC,
( B + C )A = BA + CA,
α(AB) = (αA) B = A(α B),
IA = A = AI .
A few warnings are in order however.
(i) AB BA in general (it may be true by fluke sometimes). That is, matrices do not commute. (ii) AB = AC does not necessarily imply B = C even if A is not 0.
(iii) AB = 0 does not necessarily mean that A = 0 or B = 0.
For the last two items to hold we would need to essentially “divide” by a matrix. This is where
matrix inverse comes in. Suppose that A is an n × n matrix and that there exists another n × n matrix
B such that
AB = I = BA.
Then we call B the inverse of A and we denote B by A−1 . If the inverse of A exists, then we call A
invertible. If A is not invertible we say A is singular or just say it is not invertible.
If A is invertible, then AB = AC does imply that B = C (this also means that the inverse is
unique). We just multiply both sides by A−1 to get A−1 AB = A−1 AC or IB = IC or B = C . It is also
−1
not hard to see that (A−1 ) = A. 3.2.3 The determinant We can now talk about determinants of square matrices. We define the determinant of a 1 × 1 matrix
as the value of its own entry. For a 2 × 2 matrix we define
det ab
cd = ad − bc. Before trying to compute determinant for larger matrices, let us first note the meaning of the
determinant. Consider an n × n matrix as a mapping of Rn to Rn . For example, a 2 × 2 matrix A is a
mapping of the plane where x gets sent to A x. Then the determinant of A is the factor by which
the volume of objects gets changed. For example, if we take the unit square (square of sides 1) in
the plane, then A takes the square to a parallelogram of area |det(A)|. The sign of det(A) denotes
changing of orientation (if the axes got flipped). For example,
A= 11
.
−1 1 90 CHAPTER 3. SYSTEMS OF ODES Then det(A) = 1 + 1 = 2. Now let us see where the square with vertices (0, 0), (1, 0), (0, 1), and
(1, 1) gets sent. Obviously (0, 0) gets sent to (0, 0). Now
111
1
=
,
−1 1 0
−1 110
1
=
,
−1 1 1
1 111
2
=
.
−1 1 1
0 √
So it turns out that the image of the square is another square. This one has a side of length 2 and
is therefore of area 2.
If you think back to high school geometry, you may have seen a formula for computing the area
of a parallelogram with vertices (0, 0), (a, c), (b, d) and (a + b, c + d). And it is precisely
det ab
cd . The vertical lines here mean absolute value. The matrix
parallelogram. ab
cd carries the unit square to the given Now we can define the determinant for larger matrices. We define Ai j as the matrix A with the
ith row and the jth column deleted. To compute the determinant of a matrix, pick one row, say the ith
row and compute.
n (−1)i+ j ai j det(Ai j ). det(A) =
j =1 For example, for the first row we get +a det(A ) if n is odd, 1n 1n
det(A) = a11 det(A11 ) − a12 det(A12 ) + a13 det(A13 ) − · · · −a det(A ) if n even. 1n
1n
We alternately add and subtract the determinants of the submatrices Ai j for a fixed i and all j. For
example, for a 3 × 3 matrix, picking the first row, we would get det(A) = a11 det(A11 ) − a12 det(A12 ) +
a13 det(A13 ). For example, 1 2 3 56
46
45 det 4 5 6 = 1 · det
− 2 · det
+ 3 · det 89
79
78 789
= 1(5 · 9 − 6 · 8) − 2(4 · 9 − 6 · 7) + 3(4 · 8 − 5 · 7) = 0.
The numbers (−1)i+ j det(Ai j ).
ab
ab
= det
.
cd
cd 3.2. MATRICES AND LINEAR SYSTEMS 91 I personally find this notation confusing since vertical lines for me usually mean a positive quantity,
while determinants can be negative. So I will not ever use this notation in these notes.
One of the most important properties of determinants (in the context of this course) is the
following theorem.
Theorem 3.2.1. An n × n matrix A is invertible if and only if det(A) 0. In fact, we have a formula for the inverse of a 2 × 2 matrix
ab
cd −1 = 1
d −b
.
ad − bc −c a may be best
shown by example. Suppose that we have the following system of linear equations
2 x1 + 2 x2 + 2 x3 = 2,
x1 + x2 + 3 x3 = 5,
x1 + 4 x2 + x3 = 10.
Without changing the solution, we could swap equations in this system, we could multiply any
of the equations by a nonzero number, and we could add a multiple of one equation to another
equation. It turns out these operations always suffice to find a solution.
It is easier to write the system as a matrix equation. Note that the system can be written as 2 2 2 x1 2 1 1 3 x2 = 5 . 1 4 1 x3
10
To solve the system we put the coefficient matrix (the matrix on the left hand side of the equation)
together with the vector on the right and side and get the so-called augmented matrix 2 2 2 2 1 1 3 5 . 1 4 1 10
We then apply the following three elementary operations. 92 CHAPTER 3. SYSTEMS OF ODES (i) Swap two rows.
(ii) Multiply a row by a nonzero number.
(iii) Add a multiple of one row to another row.
We will keep doing these operations until we get into a state where it is easy to read off the answer or
until we get into a contradiction indicating no solution, for example if we come up with an equation
such as 0 = 1.
Let us work through the example. First multiply the first row by 1/2 to obtain 1 1 1 1 1 1 3 5 . 1 4 1 10
Now subtract the first row from the second and third row. 1 1 1 1 0 0 2 4 0309
Multiply the last row by 1/3 and the second row by 1/2. 1 1 1 1 0 0 1 2 0103
Swap rows 2 and 3. 1 1 1 1 0 1 0 3 0012
Subtract the last row from the first, then subtract the second row from the first. 1 0 0 −4 0 1 0 3 001 2
If we think about what equations this augmented matrix represents, we see that x1 = −4, x2 = 3,
and x3 = 2. We try this solution in the original system and, voilà, it works!
Exercise 3.2.1: Check that this solution works. 3.2. MATRICES AND LINEAR SYSTEMS 93 If we write this equation in matrix notation as
A x = b,
where A is the matrix
inverse, 222
113
141 and b is the vector 2
5
10 . The solution can be also computed with the x = A −1 A x = A −1 find a row such as
[ 0 0 0 1 ] in the augmented matrix, you know the system is inconsistent.
You generally try to use row operations until the following conditions are satisfied. The first
nonzero entry in each row is called the leading entry.
(i) There is only one leading entry in each column.
(ii) All the entries above and below a leading entry are zero.
(iii). 1 2 0 3 0 0 1 1 0000
If the variables are named x1 , x2 , and x3 , then x2 is the free variable and x1 = 3 − 2 x2 and x3 = 1.
On the other hand if during the row reduction process you come up with the matrix 1 2 13 3 0 0 1 1 , 00 0 3
there is no need to go further. The last row corresponds to the equation 0 x1 + 0 x2 + 0 x3 = 3, which
is preposterous. Hence, no solution exists. 94 3.2.5 CHAPTER 3. SYSTEMS OF ODES Computing the inverse If the coefficient matrix is square and there exists a unique solution x to A x = b for any b, then A
is invertible. In fact by multiplying both sides by A−1 you can see that x = A−1 b. So it is useful to
compute the inverse, if you want to solve the equation for many different right hand sides b.
The 2 × 2 inverse is basically given by a formula, but it is not hard to also compute inverses of
larger matrices. While we will not have too much occasion to compute inverses for larger matrices
than 2 × 2 by hand, let us touch on how to do it. Finding the inverse of A is actually just solving a
bunch of linear equations. If you can solve A xk = ek where ek is the vector with all zeros except a
1 at the kth position, then the inverse is the matrix with the columns xk for k = 1, . . . , n (exercise:
why?). Therefore, to find the inverse we can write a larger n × 2n augmented matrix [ A I ], where I
is the identity. If you do row reduction and put the matrix in reduced row echelon form, then the
matrix will be of the form [ I A−1 ] if and only if A is invertible, so you can just read off the inverse
A−1 . 3.2.6 Exercises Exercise 3.2.2: Solve x= 12
34 5
6 by using matrix inverse. Exercise 3.2.3: Compute determinant of 9 −2 −6
−8 3 6
10 −2 −6 Exercise 3.2.4: Compute determinant of 1
4
6
8 2
0
0
0 3
5
7
10 1
0
0
1 .
. Hint: Expand along the proper row or column to make the calculations simpler.
123
111
010 Exercise 3.2.5: Compute inverse of . 123
456
78h not invertible? Is there only one such h? Are there several? Exercise 3.2.7: For which h is h11
0h0
11h not invertible? Find all such h. Exercise 3.2.8: Solve 9 −2 −6
−8 3 6
10 −2 −6 x= 1
2
3 Exercise 3.2.9: Solve 537
844
633 Exercise 3.2.6: For which h is
Infinitely many. Exercise 3.2.10: Solve 3
3
0
2 2
3
2
3 x=
3
3
4
4 0
3
2
3 2
0
0 x= . .
2
0
4
1 . 3.3. LINEAR SYSTEMS OF ODES 3.3 95 Linear systems of ODEs Note: less than 1 lecture, second part of §5.1 in [EP]
First let us talk about matrix or vector valued functions. This is essentially just a matrix whose
entries depend on some variable. Let us say the independent variable is t. Then a vector valued
function x(t) is really something like x1 (t) x2 (t) . . x(t) = . . xn (t)
Similarly a matrix valued function is something such as a11 (t) a12 (t) · · · a1n (t) a21 (t) a22 (t) · · · a2n (t) A(t) = .
.
.
. .
.. .
.
.
. .
. an1 (t) an2 (t) · · · ann (t)
We can talk about the derivative A (t) or dA and this is just the matrix valued function whose i jth
dt
entry is ai j (t).
Rules of differentiation of matrix valued functions are similar to rules for normal functions. Let
A and B be matrix valued functions. Let c a scalar and C be a constant matrix. Then
(A + B)
(AB)
(cA)
(CA)
(AC ) =A +B
= A B + AB
= cA
= CA
=AC Do note the order in the last two expressions.
A first order linear system of ODEs is a system that can be written as
x (t) = P(t) x(t) + f (t).
Where P is a matrix valued function, and x and f are vector valued functions. We will often suppress
the dependence on t and only write x = P x + f . A solution is of course a vector valued function x
satisfying the equation.
For example, the equations
x1 = 2tx1 + et x2 + t2 ,
x1
x2 =
− x2 + et ,
t 96 CHAPTER 3. SYSTEMS OF ODES can be written as
x= t2
2t e t
x+ t .
1/t −1
e We will mostly concentrate on equations that are not just linear, but are in fact constant coefficient
equations. That is, the matrix P will be a constant and not depend on t.
When f = 0 (the zero vector), then we say the system is homogeneous. For homogeneous linear
systems we still have the principle of superposition, just like for single homogeneous equations.
Theorem 3.3.1 (Superposition). Let x = P x be a linear homogeneous system of ODEs. Suppose
that x1 , . . . , xn are n solutions of the equation, then
x = c1 x1 + c2 x2 + · · · + cn xn , (3.1) is also a solution. If furthermore this is a system of n equations (P is n × n), and x1 , . . . , xn are
linearly independent. Then every solution can be written as (3.1).
Linear independence for vector valued functions is essentially the same as for normal functions.
x1 , . . . , xn are linearly independent if and only if
c1 x1 + c2 x2 + · · · + cn xn = 0
has only the solution c1 = c2 = · · · = cn = 0.
The linear combination c1 x1 + c2 x2 + · · · + cn xn could always be written as
X (t) c,
where X (t) is the matrix with columns x1 , . . . , xn , and c is the column vector with entries c1 , . . . , cn .
X (t) is called the fundamental matrix, or fundamental matrix solution.
To solve nonhomogeneous first order linear systems. We apply the same technique as we did
before.
Theorem 3.3.2. Let x = P x + f be a linear system of ODEs. Suppose x p is one particular solution.
Then every solution can be written as
x = xc + x p ,
where xc is a solution to the associated homogeneous equation ( x = P x).
So the procedure will be exactly the same. We find a particular solution to the nonhomogeneous
equation, then we find the general solution to the associated homogeneous equation and we add the
two.
Alright, suppose you have found the general solution x = P x + f . Now you are given an initial
condition of the form x(t0 ) = b for some constant vector b. Suppose that X (t) is the fundamental 3.3. LINEAR SYSTEMS OF ODES 97 matrix solution of the associated homogeneous equation (i.e. columns of X are solutions). The
general solution is written as
x(t) = X (t)c + x p (t).
Then we are seeking a vector c such that
b = x(t0 ) = X (t0 )c + x p (t0 ).
Or in other words we are solving the nonhomogeneous system of linear equations
X (t0 )c = b − x p (t0 )
for c.
Example 3.3.1: In § 3.1 we solved the following system
x1 = x1 ,
x2 = x1 − x2 .
with initial conditions x1 (0) = 1, x2 (0) = 2.
This is a homogeneous system, so f = 0. We write the system as
x= 10
x,
1 −1 x(0) = 1
.
2 We found the general solution was x1 = c1 et and x2 = c21 et + c2 e−t . Hence in matrix notation, the
fundamental matrix solution is
et 0
X (t) = 1 t −t .
ee
2
It is not hard to see that the columns of this matrix are linearly independent. To see this, just plug in
t = 0 and note that the two constant vectors are already linearly independent here.
Hence to solve the initial problem we solve the equation
X (0)c = b,
or in other words,
10
1
c=
.
1
1
2
2
After a single elementary row operation we find that c =
x(t) = X (t)c =
This agrees with our previous solution. et
1t
e
2 01
=
e−t 3
2 1
3/2 . Hence our solution is 1t
e
2 et
.
3
+ 2 e−t 98 3.3.1 CHAPTER 3. SYSTEMS OF ODES Exercises Exercise 3.3.1: Write the system x1 = 2 x1 − 3tx2 + sin t, x2 = et x1 + 3 x2 + cos t as in the form
x = P(t) x + f (t).
1
Exercise 3.3.2: a) Verify that the system x = 1 3 x has the two solutions 1 e4t and −1 e−2t . b)
31
1
Write down the general solution. c) Write down the general solution in the form x1 =?, x2 =? (i.e.
write down a formula for each element of the solution). Exercise 3.3.3: Verify that 1
1 et and 1
−1 1 1 et are linearly independent. Hint: Just plug in t = 0. Exercise 3.3.4: Verify that 1 et and −1 et and
0
1
be a bit more tricky than in the previous exercise.
Exercise 3.3.5: Verify that t
t2 and t3
t4 1
−1
1 e2t are linearly independent. Hint: You must are linearly independent. 3.4. EIGENVALUE METHOD 3.4 99 Eigenvalue method Note: 2 lectures, §5.2 in [EP]
In this section we will learn how to solve linear homogeneous constant coefficient systems
of ODEs by the eigenvalue method. Suppose we have a linear constant coefficient homogeneous
system
x = P x,
where P is a constant square matrix. Suppose we try to adapt the method for the single constant
coefficient equation by trying the function eλt . However, x is a vector. So we try x = veλt , where v is
an arbitrary constant vector. We plug this x into the equation to get
λveλt = Pveλt .
We divide by eλt and notice that we are looking for a scalar λ and a vector v that satisfy the equation
λv = Pv.
To solve this equation we need a little bit more linear algebra, which we now review. 3.4.1 Eigenvalues and eigenvectors of a matrix Let A be a constant square matrix. Suppose there is a scalar λ and a nonzero vector v such that
Av = λv.
We then call λ an eigenvalue of A and v is said to be a corresponding eigenvector.
Example 3.4.1: The matrix
because 21
01 has an eigenvalue of λ = 2 with a corresponding eigenvector 1
0 211
2
1
=
=2
.
010
0
0
If we rewrite the equation for an eigenvalue as
(A − λI )v = 0,
we notice that this equation has a nonzero solution v only if A − λI is not invertible. Were it
invertible, we could write (A − λI )−1 (A − λI )v = (A − λI )−1 0, which implies v = 0. Therefore, A
has the eigenvalue λ if and only if λ solves the equation
det(A − λI ) = 0.
This means that we will be able to find an eigenvalue without finding the corresponding
eigenvector. The eigenvector will have to be found later, once λ is known. 100 CHAPTER 3. SYSTEMS OF ODES
211 Example 3.4.2: Find all eigenvalues of 1 2 0 .
002
We write 2 1 1
1 0 0
2 − λ
1
1 2−λ
0 =
det 1 2 0 − λ 0 1 0 = det 1 002
001
0
0
2−λ
= (2 − λ)2 (2 − λ)2 − 1 = −(λ − 1)(λ − 2)(λ − 3).
and so the eigenvalues are λ = 1, λ = 2, and λ = 3.
Note that for an n × n matrix, the polynomial we get by computing det(A − λI ) will be of degree
n, and hence we will in general have n eigenvalues.
To find an eigenvector corresponding to λ, we write
(A − λI )v = 0,
and solve for a nontrivial (nonzero) vector v. If λ is an eigenvalue, this will always be possible.
211 Example 3.4.3: Find the eigenvector of 1 2 0 corresponding to the eigenvalue λ = 3.
002
We write 1 0 0 v1 −1 1 1 v1 2 1 1 (A − λI )v = 1 2 0 − 3 0 1 0 v2 = 1 −1 0 v2 = 0. 0 0 −1 v3
0 0 1 v3
002
It is easy to solve this system of linear equations. We write down the augmented matrix −1 1 1 0 1 −1 0 0 0 0 −1 0
and perform row operations (exercise: which ones?) 1 −1 0 0 0 1 000 until we get 0 0 . 0 The equations the entries of v have to satisfy are, therefore, v1 − v2 = 0, v3 = 0, and v2 is a free
variable. We can pick v2 to be arbitrary (but nonzero) and let v1 = v2 and of course v3 = 0. For
example, v = 1
1
0 . Let us verify that we really have an eigenvector corresponding to λ = 3: 2 1 1 1 3
1 1 2 0 1 = 3 = 3 1 . 0020
0
0 Yay! It worked. 3.4. EIGENVALUE METHOD 101 Exercise 3.4.1 (easy): Are the eigenvectors unique? Can you find a different eigenvector for λ = 3
in the example above? How are the two eigenvectors related?
Exercise 3.4.2: Note that when the matrix is 2 × 2 you do not need to write down the augmented
matrix and do row operations when computing eigenvectors (if you have computed the eigenvalues
correctly). Can you see why? Try it for the matrix 2 1 .
12 3.4.2 The eigenvalue method with distinct real eigenvalues OK. We have the system of equations
x = P x.
We find the eigenvalues λ1 , λ2 , . . . , λn of the matrix P, and the corresponding eigenvectors v1 , v2 ,
. . . , vn . Now we notice that the functions v1 eλ1 t , v2 eλ2 t , . . . , vn eλn t are solutions of the system of
equations and hence x = c1 v1 eλ1 t + c2 v2 eλ2 t + · · · + cn vn eλn t is a solution.
Theorem 3.4.1. Take x = P x. If P is n × n and has n distinct real eigenvalues λ1 , λ2 , . . . , λn , then
there are n linearly independent corresponding eigenvectors v1 , v2 , . . . , vn , and the general solution
to this system of ODEs can be written as.
x = c1 v1 eλ1 t + c2 v2 eλ2 t + · · · + cn vn eλn t .
Example 3.4.4: Suppose we take the system 2 1 1 x = 1 2 0 x. 002
Find the general solution.
We have found the eigenvalues 1, 2, 3 earlier. We have found the eigenvector
1 eigenvalue 3. In similar fashion we find the eigenvector −1 for the eigenvalue 1 and
0
eigenvalue 2 (exercise: check). Hence our general solution is t 3t
1 t 0 2t 1 3t e t+ e 3t x = −1 e + 0 e + 1 e = −e + e . 2t
0
1
0
e 1
1
0
0
1
−1 for the
for the Exercise 3.4.3: Check that this really solves the system.
Note: If you write a homogeneous linear constant coefficient nth order equation as a first order
system (as we did in § 3.1), then the eigenvalue equation
det(P − λI ) = 0.
is essentially the same as the characteristic equation we got in § 2.2 and § 2.3. 102 3.4.3 CHAPTER 3. SYSTEMS OF ODES Complex eigenvalues A matrix might very well have complex eigenvalues even if all the entries are real. For example,
suppose that we have the system
11
x=
x.
−1 1
Let us compute the eigenvalues of the matrix P =
det(P − λI ) = det 1−λ
1
−1 1 − λ 11
−1 1 . = (1 − λ)2 + 1 = λ2 − 2λ + 2 = 0. Thus λ = 1 ± i. The corresponding eigenvectors will also be complex. First take λ = 1 − i,
(P − (1 − i)I )v = 0,
i1
v = 0.
−1 i
It is obvious that the equations iv1 + v2 = 0 and −v1 + iv2 = 0 are multiples of each other. So we only
i
need to consider one of them. After picking v2 = 1, for example, we have an eigenvector v = 1 .
−i
In similar fashion we find that 1 is an eigenvector corresponding to the eigenvalue 1 + i.
We could write the solution as
x = c1 i (1−i)t
−i (1+i)t
c ie(1−i)t − c2 ie(1+i)t
e
+ c2
e
= 1 (1−i)t
.
1
1
c1 e
+ c2 e(1+i)t 1 But then we would need to look for complex values c1 and c2 to solve any initial conditions. And
even then it is perhaps not completely clear that we get a real solution. We could use Euler’s formula
here and do the whole song and dance we did before, but we will not. We will do something a bit
smarter first.
We claim that we did not have to look for the second eigenvector (nor for the second eigenvalue).
All complex eigenvalues come in pairs (because the matrix P is real).
¯
First a small side note. The real part of a complex number z can be computed as z+z , where the
2
bar above z means a + ib = a − ib. This operation is called the complex conjugate. Note that for a
real number a, a = a. Similarly we can bar whole vectors or matrices. If a matrix P is real, then
¯
P = P. We note that P x = P x = P x. Or
¯
(P − λI )v = (P − λI )v.
So if v is an eigenvector corresponding to eigenvalue a + ib, then v is an eigenvector corresponding
to an eigenvalue a − ib.
Now suppose that a + ib is a complex eigenvalue of P, v the corresponding eigenvector and
hence
x1 = ve(a+ib)t 3.4. EIGENVALUE METHOD 103 is a solution (complex valued) of x = P x. Then note that ea+ib = ea−ib and
x2 = x1 = ve(a−ib)t
is also a solution. The function
x3 = Re x1 = Re ve(a+ib)t = x1 + x1 x1 + x2
=
2
2 is also a solution. And it is real-valued! Similarly as Im z =
x4 = Im x1 = z−z
¯
2i is the imaginary part we find that x1 − x2
.
2i is also a real-valued solution. It turns out that x3 and x4 are linearly independent.
Returning to our problem, we take
x1 = i (1−i)t
it
iet cos t + et sin t
e
=
e cos t − iet sin t = t
.
1
1
e cos t − iet sin t It is easy to see that
Re x1 = et sin t
,
et cos t Im x1 = et cos t
,
−et sin t are the solutions we seek.
Exercise 3.4.4: Check that these really are solutions.
The general solution is
x = c1 et sin t
et cos t
c et sin t + c2 et cos t
+ c2
= 1t
.
t
t
e cos t
−e sin t
c1 e cos t − c2 et sin t This solution is real-valued for real c1 and c2 . Now we can solve for any initial conditions that we
have.
The process follows. When you have complex eigenvalues, you notice that they always come
in pairs. You take one λ = a + ib from the pair, you find a corresponding eigenvector v. You note
that Re ve(a+ib)t and Im ve(a+ib)t are also solutions to the equation, are real-valued and are linearly
independent. You go on to the next eigenvalue, which is either a real eigenvalue or another complex
eigenvalue pair. Hence, you will end up with n linearly independent solutions if you had n distinct
eigenvalues (real or complex).
You can now find a real-valued general solution to any homogeneous system where the matrix
has distinct eigenvalues. When you have repeated eigenvalues, matters get a bit more complicated
and we will look at that situation in § 3.7. 104 3.4.4 CHAPTER 3. SYSTEMS OF ODES Exercises Exercise 3.4.5 (easy): Let A be an 3 × 3 matrix with an eigenvalue of 3 and a corresponding
eigenvector v = 1
−1
3 . Find Av. Exercise 3.4.6: a) Find the general solution of x1 = 2 x1 , x2 = 3 x2 using the eigenvalue method
(first write the system in the form x = A x). b) Solve the system by solving each equation separately
and verify you get the same general solution.
Exercise 3.4.7: Find the general solution of x1 = 3 x1 + x2 , x2 = 2 x1 + 4 x2 using the eigenvalue
method.
Exercise 3.4.8: Find the general solution of x1 = x1 − 2 x2 , x2 = 2 x1 + x2 using the eigenvalue
method. Do not use complex exponentials in your solution.
Exercise 3.4.9: a) Compute eigenvalues and eigenvectors of A =
solution of x = A x.
Exercise 3.4.10: Compute eigenvalues and eigenvectors of −2 −1 −1
321
−3 −1 0 9 −2 −6
−8 3 6
10 −2 −6 . . b) Find the general 3.5. TWO DIMENSIONAL SYSTEMS AND THEIR VECTOR FIELDS 3.5 105 Two dimensional systems and their vector fields Note: 1 lecture, should really be in [EP] §5.2, but is in [EP] §6.2
Let us take a moment to talk about homogeneous systems in the plane. We want to think about
how the vector fields look and how this depends on the eigenvalues. So we have a 2 × 2 matrix P
and the system
x
x
=P
.
(3.2)
y
y
We will be able to visually tell how the vector field looks once we find the eigenvalues and
eigenvectors of the matrix.
Case 1. Suppose that the eigenvalues are real
and positive. Find the two eigenvectors and plot
them in the plane. For example, take the matrix
1 1 . The eigenvalues are 1 and 2 and the corre02
sponding eigenvectors are 1 and 1 . See Fig0
1
ure 3.3.
Now suppose that x and y are on the line determined by an eigenvector v for an eigenvalue λ.
x
That is, y = av for some scalar a. Then
x
x
=P
= P(av) = a(Pv) = aλv.
y
y -3 -2 -1 0 1 2 3 3 3 2 2 1 1 0 0 -1 -1 -2 -2 -3 -3
-3 -2 -1 0 1 2 3 The derivative is a multiple of v and hence points
Figure 3.3: Eigenvectors of P.
along the line determined by v. As λ > 0, the
derivative points in the direction of v when a is
positive and in the opposite direction when a is
negative. Let us draw arrows on the lines to indicate the directions. See Figure 3.4 on the following
page.
We fill in the rest of the arrows and we also draw a few solutions. See Figure 3.5 on the next
page. You will notice that the picture looks like a source with arrows coming out from the origin.
Hence we call this type of picture a source or sometimes an unstable node.
Case 2. Suppose both eigenvalues were negative. For example, take the negation of the matrix
in case 1, −1 −1 . The eigenvalues are −1 and −2 and the corresponding eigenvectors are the same,
0 −2
1 and 1 . The calculation and the picture are almost the same. The only difference is that the
0
1
eigenvalues are negative and hence all arrows are reversed. We get the picture in Figure 3.6 on the
following page. We call this kind of picture a sink or sometimes a stable node.
1
Case 3. Suppose one eigenvalue is positive and one is negative. For example the matrix 1 −2 .
0
1
The eigenvalues are 1 and −2 and the corresponding eigenvectors are the same, 1 and −3 . We
0 106
-3 CHAPTER 3. SYSTEMS OF ODES
-2 -1 0 1 2 3 -3 -2 -1 0 1 2 3 3 3 3 3 2 2 2 2 1 1 1 1 0 0 0 0 -1 -1 -1 -1 -2 -2 -2 -2 -3 -3 -3
-3 -2 -1 0 1 2 3 Figure 3.4: Eigenvectors of P with directions. -3 -2 -1 0 1 2 -3
-3 -2 -1 0 1 2 3 Figure 3.5: Example source vector field with
eigenvectors and solutions. 3 -3 -2 -1 0 1 2 3 3 3 3 3 2 2 2 2 1 1 1 1 0 0 0 0 -1 -1 -1 -1 -2 -2 -2 -2 -3 -3 -3
-3 -2 -1 0 1 2 3 Figure 3.6: Example sink vector field with
eigenvectors and solutions. -3
-3 -2 -1 0 1 2 3 Figure 3.7: Example saddle vector field with
eigenvectors and solutions. reverse the arrows on one line (corresponding to the negative eigenvalue) and we obtain the picture
in Figure 3.7. We call this picture a saddle point.
The next three cases we will assume the eigenvalues are complex. In this case the eigenvectors
are also complex and we cannot just plot them on the plane.
Case 4. Suppose the eigenvalues are purely imaginary. That is, suppose the eigenvalues are ±ib.
01
1
For example, let P = −4 0 . The eigenvalues turn out to be ±2i and the eigenvectors are 2i and
1
1
−2i . We take the eigenvalue 2i and its eigenvector 2i and note that the real and imaginary parts 3.5. TWO DIMENSIONAL SYSTEMS AND THEIR VECTOR FIELDS 107 of vei2t are
Re 1 i2t
cos(2t)
e=
,
2i
−2 sin(2t) Im 1 i2t
sin(2t)
e=
.
2i
2 cos(2t) We can take any linear combination of them, and which one we take depends on the initial conditions.
For example, the real part is a parametric equation for an ellipse. Same with the imaginary part and
in fact any linear combination of them. It is not difficult to see that this is what happens in general
when the eigenvalues are purely imaginary. So when the eigenvalues are purely imaginary, you get
ellipses for your solutions. This type of picture is sometimes called a center. See Figure 3.8.
-3 -2 -1 0 1 2 3 -3 -2 -1 0 1 2 3 3 3 3 3 2 2 2 2 1 1 1 1 0 0 0 0 -1 -1 -1 -1 -2 -2 -2 -2 -3 -3 -3
-3 -2 -1 0 1 2 Figure 3.8: Example center vector field. 3 -3
-3 -2 -1 0 1 2 3 Figure 3.9: Example spiral source vector field. Case 5. Now the complex eigenvalues have positive real part. That is, suppose the eigenvalues
1
are a ± ib for some a > 0. For example, let P = −4 1 . The eigenvalues turn out to be 1 ± 2i and
1
1
1
the eigenvectors are 2i and −1 i . We take 1 + 2i and its eigenvector 2i and find the real and
2
(1+2i)t
imaginary of ve
are
Re 1 (1+2i)t
cos(2t)
e
= et
,
2i
−2 sin(2t) Im 1 (1+2i)t
sin(2t)
e
= et
.
2i
2 cos(2t) Now note the et in front of the solutions. This means that the solutions grow in magnitude while
spinning around the origin. Hence we get a spiral source. See Figure 3.9.
Case 6. Finally suppose the complex eigenvalues have negative real part. That is, suppose the
eigenvalues are −a ± ib for some a > 0. For example, let P = −1 −1 . The eigenvalues turn out to
4 −1 108 CHAPTER 3. SYSTEMS OF ODES be −1 ± 2i and the eigenvectors are −1 i and
2
the real and imaginary of ve(1+2i)t are 1
2i . We take −1 − 2i and its eigenvector Re and find 1 (−1−2i)t
cos(2t)
e
= e−t
,
2i
2 sin(2t) Im 1
2i 1 (−1−2i)t
− sin(2t)
e
= e−t
.
2i
2 cos(2t) Now note the e−t in front of the solutions. This means that the solutions shrink in magnitude while
spinning around the origin. Hence we get a spiral sink. See Figure 3.10.
-3 -2 -1 0 1 2 3 3 3 2 2 1 1 0 0 -1 -1 -2 -2 -3 -3
-3 -2 -1 0 1 2 3 Figure 3.10: Example spiral sink vector field. We summarize the behavior of linear homogeneous two dimensional systems in Table 3.1.
Eigenvalues Behavior real and both positive
real and both negative
real and opposite signs
purely imaginary
complex with positive real part
complex with negative real part source / unstable node
sink / stable node
saddle
center point / ellipses
spiral source
spiral sink Table 3.1: Summary of behavior of linear homogeneous two dimensional systems. 3.5. TWO DIMENSIONAL SYSTEMS AND THEIR VECTOR FIELDS 3.5.1 109 Exercises Exercise 3.5.1: Take the equation mx + cx + kx = 0, with m > 0, c ≥ 0, k > 0 for the mass-spring
system. a) Convert this to a system of first order equations. b) Classify for what m, c, k do you get
which behavior. c) Can you explain from physical intuition why you do not get all the different kinds
of behavior here?
Exercise 3.5.2: Can you find what happens in the case when P = 1 1 . In this case the eigenvalue
01
is repeated and there is only one eigenvector. What picture does this look like?
Exercise 3.5.3: Can you find what happens in the case when P =
the pictures we have drawn? 11
11 . Does this look like any of 110 3.6 CHAPTER 3. SYSTEMS OF ODES Second order systems and applications Note: more than 2 lectures, §5.3 in [EP] 3.6.1 Undamped mass spring systems m1 , m2 , and m3 and the spring constants are k1 ,
k2 , k3 , and k4 . Let x1 be the displacement from rest position of the first mass, and x2 and x3 the
displacement of the second and third mass. We will make, as usual, positive values go right (as x1
grows the first mass is moving right). See Figure 3.11.
k1 k2
m1 k3
m2 k4
m3 Figure 3.11: System of masses and springs.
This simple system turns up in unexpected places. Note for example that our world really
consists of small particles of matter interacting together. When we try this system with many more
masses, we obtain a good approximation to how an elastic material will behave. By somehow taking
a limit of the number of masses going to infinity, we obtain the continuous one dimensional wave
equation..
m1 x1 = −k1 x1 + k2 ( x2 − x1 )
m2 x2 = −k2 ( x2 − x1 ) + k3 ( x3 − x2 )
m3 x3 = −k3 ( x3 − x2 ) − k4 x3
We define the matrices m1 0 0 M = 0 m2 0 0 0 m3 and = −(k1 + k2 ) x1 + k2 x2 ,
= k2 x1 − (k2 + k3 ) x2 + k3 x3 ,
= k3 x2 − (k3 + k4 ) x3 . −(k1 + k2 ) k2
0 . k2
−(k2 + k3 )
k3
K= 0
k3
−(k3 + k4 ) 3.6. SECOND ORDER SYSTEMS AND APPLICATIONS 111 We write the equation simply as
M x = K x.
At this point we could introduce 3 new variables and write out a system of 6 equations. We claim
this simple setup is easier to handle as a second order system. We will call x the displacement
vector, M the mass matrix, and K the stiffness matrix.
Exercise 3.6.1: Repeat this setup for 4 masses (find the matrices M and K ). Do it for 5 masses.
Can you find a prescription to do it for n masses?
As with a single equation we will want to “divide by M .” This means computing the inverse of
M . The masses are all nonzero and M is a diagonal matrix, so comping the inverse is easy.
1 m1 0 0 0 1 0 . −1 M = m2 1
0 0 m3
This fact follows readily by how we multiply diagonal matrices. You should verify that MM −1 =
M −1 M = I as an exercise.
Let A = M −1 K . We look at the system x = M −1 K x, or
x = A x.
Many real world systems can be modeled by this equation. For simplicity, we will only talk about
the given masses-and-springs problem. We try a solution of the form
x = veαt .
We compute that for this guess, x = α2 veαt . We plug our guess into the equation and get
α2 veαt = Aveαt .
We can divide by eαt to get that α2 v = Av. Hence if α2 is an eigenvalue of A and v is the
corresponding eigenvector, we have found a solution.
In our example, and in other common applications, it turns out that A has only real negative
eigenvalues (and possibly a zero eigenvalue). So we will study only this case. When an eigenvalue λ
is negative, it means that α2 = λ is negative. Hence there is some real number ω such that −ω2 = λ.
Then α = ±iω. The solution we guessed was
x = v cos(ωt) + i sin(ωt) .
By taking real and imaginary parts (note that v is real), we find that v cos(ωt) and v sin(ωt) are
linearly independent solutions.
If an eigenvalue is zero, it turns out that both v and vt are solutions, where v is the corresponding
eigenvector. 112 CHAPTER 3. SYSTEMS OF ODES Exercise 3.6.2: Show that if A has a zero eigenvalue and v is the corresponding eigenvector, then
x = v(a + bt) is a solution of x = A x for arbitrary constants a and b.
Theorem 3.6.1. Let A be an n × n with n distinct real negative eigenvalues we denote by −ω2 >
1
−ω2 > · · · > −ω2 , and the corresponding eigenvectors by v1 , v2 , . . . , vn . If A is invertible (that is, if
n
2
ω1 > 0), then
n x(t) = vi ai cos(ωi t) + bi sin(ωi t) ,
i=1 is the general solution of
x = A x,
for some arbitrary constants ai and bi . If A has a zero eigenvalue, that is ω1 = 0, and all other
eigenvalues are distinct and negative, then the general solution becomes
n x(t) = v1 (a1 + b1 t) + vi ai cos(ωi t) + bi sin(ωi t) .
i =2 Note that we can use this solution and the setup from the introduction of this section even when
some of the masses and springs are missing. For example, when there are say 2 masses and only 2
springs, simply take only the equations for the two masses and set all the spring constants for the
springs that are missing to zero. 3.6.2 Examples Example 3.6.1: Suppose we have the system in Figure 3.12, with m1 = 2, m2 = 1, k1 = 4, and
k2 = 2.
k1 k2
m1 m2 Figure 3.12: System of masses and springs. The equations we write down are
20
−(4 + 2) 2
x=
x,
01
2
−2
or
x= −3 1
x.
2 −2 3.6. SECOND ORDER SYSTEMS AND APPLICATIONS 1
2 113 We find the eigenvalues of A to be λ = −1, −4 (exercise). Now we find the eigenvectors to be
1
and −1 respectively (exercise).
We check the theorem and note that ω1 = 1 and ω2 = 2. Hence the general solution is
x= 1
1
a1 cos(t) + b1 sin(t) +
a cos(2t) + b2 sin(2t) .
2
−1 2 The two terms in the solution represent the two so-called natural or normal modes of oscillation. And the two (angular) frequencies are the natural frequencies. The two modes are plotted
in Figure 3.13.
0.0 2.5 5.0 7.5 10.0 0.0 2.5 5.0 7.5 10.0 2 2 1.0 1.0 1 1 0.5 0.5 0 0 0.0 0.0 -1 -1 -0.5 -0.5 -2 -1.0 -2
0.0 2.5 5.0 7.5 10.0 -1.0
0.0 2.5 5.0 7.5 10.0 Figure 3.13: The two modes of the mass spring system. In the left plot the masses are moving in
unison and the right plot are masses moving in the opposite direction.
Let us write the solution as
x=
The first term, 1
1
c cos(t − α1 ) +
c cos(2t − α2 ).
21
−1 2
1
c cos(t − α1 )
c1 cos(t − α1 ) = 1
,
2
2c1 cos(t − α1 ) corresponds to the mode where the masses move synchronously in the same direction.
On the other hand the second term,
1
c cos(2t − α2 )
c cos(2t − α2 ) = 2
,
−1 2
−c2 cos(2t − α2 )
corresponds to the mode where the masses move synchronously but in opposite directions.
The general solution is a combination of the two modes. That is, the initial conditions determine
the amplitude and phase shift of each mode. 114 CHAPTER 3. SYSTEMS OF ODES k = 2 N/m. The second car is 10 meters from a wall. See Figure 3.14.
k m1 m2
10 meters Figure 3.14: The crash of two rail cars. We want to ask several question. At what time after the cars link does impact with the wall
happen? What is the speed of car 2 when it hits the wall?
OK, let us first set the system up. Let t = 0 be the time when the two cars link up. Let x1 be the
displacement of the first car from the position at t = 0, and let x2 be the displacement of the second
car from its original location. Then the time when x2 (t) = 10 is exactly the time when impact with
wall occurs. For this t, x2 (t) is the speed at impact. This system acts just like the system of the
previous example but without k1 . Hence the equation is
20
−2 2
x=
x.
01
2 −2
or
x= −1 1
x.
2 −2 We compute the eigenvalues of A. It is not hard to see that the eigenvalues are 0 and −3
1
(exercise). Furthermore, the eigenvectors are 1 and −2 respectively (exercise). We note that
1
√
ω2 = 3 and we use the second part of the theorem to find our general solution to be
√
√
1
1
(a1 + b1 t) +
a2 cos( 3 t) + b2 sin( 3 t)
1
−2
√
√
a1 + b1 t + a2 cos(√3 t) + b2 sin( √ t)
3
=
a1 + b1 t − 2a2 cos( 3 t) − 2b2 sin( 3 t) x= We now apply the initial conditions. First the cars start at position 0 so x1 (0) = 0 and x2 (0) = 0.
The first car is traveling at 3 m/s, so x1 (0) = 3 and the second car starts at rest, so x2 (0) = 0. The first
conditions says
a + a2
0 = x(0) = 1
.
a1 − 2a2 3.6. SECOND ORDER SYSTEMS AND APPLICATIONS 115 It is not hard to see that this implies that a1 = a2 = 0. We plug a1 and a2 and differentiate to get
√
√
b1 + √ b2 cos( √ t)
3
3
x (t) =
.
b1 − 2 3 b2 cos( 3 t)
So √
3
b1 + √ b2
3
= x (0) =
.
0
b1 − 2 3 b2 It is not hard to solve these two equations to find b1 = 2 and b2 =
is (until the impact with the wall)
√ 1
2t + √ sin( 3 t) 3 x= 2t − √ sin(√3 t) . 2
3 1
√.
3 Hence the position of our cars Note how the presence of the zero eigenvalue resulted in a term containing t. This means that the
carts will be traveling in the positive direction as time grows, which is what we expect.
What we are really interested in is the second expression, the one for x2 . We have x2 (t) =
√
2
2t − √3 sin( 3 t). See Figure 3.15 for the plot of x2 versus time.
0 1 2 3 4 5 6 12.5 12.5 10.0 10.0 7.5 7.5 5.0 5.0 2.5 2.5 0.0 0.0
0 1 2 3 4 5 6 Figure 3.15: Position of the second car in time (ignoring the wall).
Just from the graph we can see that time of impact will be a little more than 5 seconds from
√
2
time zero. For this you have to solve the equation 10 = x2 (t) = 2t − √3 sin( 3 t). Using a computer
(or even a graphing calculator) we find that timpact ≈ 5.22 seconds.
√
As for the speed we note that x2 = 2 − 2 cos( 3 t). At time of impact (5.22 seconds from t = 0)
we get that x2 (timpact ) ≈ 3.85.
√
The maximum speed is the maximum of 2 − 2 cos( 3 t), which is 4. We are traveling at almost
the maximum speed when we hit the wall. 116 CHAPTER 3. SYSTEMS OF ODES Now suppose that Bob is a tiny person sitting on car 2. Bob has a Martini in his hand and would
like to in? A distance
such that the impact with the wall is at zero speed?
The answer is yes. Looking at Figure 3.15 on the preceding page, we note the “plateau” between
t = 3 and t = 4. There is a point where the speed is zero. To find it we need to solve x2 (t) = 0. This
√
2
4
is when cos( 3 t) = 1 or in other words when t = √π , √π , . . . and so on. We plug in the first value to
3
3
2
4
obtain x2 √π = √π ≈ 7.26. So a “safe” distance is about 7 and a quarter meters from the wall.
3
3
Alternatively Bob could move away from the wall towards the incoming car 2 where another
8
safe distance is √π ≈ 14.51 and so on, using all the different t such that x2 (t) = 0. Of course t = 0 is
3
always a solution here, corresponding to x2 = 0, but that means standing right at the wall. 3.6.3 Forced oscillations Finally we move to forced oscillations. Suppose that now our system is
x = A x + F cos(ωt). (3.3) That is, we are adding periodic forcing to the system in the direction of the vector F .
Just like before this system just requires us to find one particular solution x p , add it to the general
solution of the associated homogeneous system xc and we will have the general solution to (3.3).
Let us suppose that ω is not one of the natural frequencies of x = A x, then we can guess
x p = c cos(ωt),
where c is an unknown constant vector. Note that we do not need to use sine since there are only
second derivatives. We solve for c to find x p . This is really just the method of undetermined
coefficients for systems. Let us differentiate x p twice to get
x p = −ω2 c cos(ωt).
Now plug into the equation
−ω2 c cos(ωt) = Ac cos(ωt) + F cos(ωt)
We can cancel out the cosine and rearrange the equation to obtain
(A + ω2 I )c = −F .
So −1 c = (A + ω2 I ) (−F ). 3.6. SECOND ORDER SYSTEMS AND APPLICATIONS 117 Of course this this is possible only if (A + ω2 I ) = (A − (−ω2 )I ) is invertible. That matrix is invertible
if and only if −ω2 is not an eigenvalue of A. That is true if and only if ω is not a natural frequency
of the system.
Example 3.6.3: Let us take the example in Figure 3.12 on page 112 with the same parameters as
before: m1 = 2, m2 = 1, k1 = 4, and k2 = 2. Now suppose that there is a force 2 cos(3t) acting on
the second cart.
The equation is
−3 1
0
x=
x+
cos(3t).
2 −2
2
We have solved the associated homogeneous equation before and found the complementary solution
to be
1
1
(a cos(t) + b1 sin(t)) +
(a cos(2t) + b2 sin(2t)) .
xc =
21
−1 2
We note that the natural frequencies were 1 and 2. Hence 3 is not a natural frequency, we can
try c cos(3t). We can invert (A + 32 I )
−3 1
+ 32 I
2 −2 −1 61
=
27 −1 = 7
40
−1
20 −1
40
3
20 . Hence,
−1 c = (A + ω I ) (−F ) =
2 7
40
−1
20 −1
40
3
20 0
=
−2 1
20
−3
10 . Combining with what we know the general solution of the associated homogeneous problem to
be we get that the general solution to x = A x + F cos(ωt) is
1
1
(a1 cos(t) + b1 sin(t)) +
(a2 cos(2t) + b2 sin(2t)) +
x = xc + x p =
2
−1 1
20
−3
10 cos(3t). The constants a1 , a2 , b1 , and b2 must then be solved for given any initial conditions.
If ω is a natural frequency of the system resonance occurs because you will have to try a
particular solution of the form
x p = c t sin(ωt) + d cos(ωt).
That is assuming that all eigenvalues of the coefficient matrix are distinct. Note that the amplitude
of this solution grows without bound as t grows. 118 3.6.4 CHAPTER 3. SYSTEMS OF ODES Exercises Exercise 3.6.3: Find a particular solution to
x= 0
−3 1
x+
cos(2t).
2
2 −2 Exercise 3.6.4 (challenging): Let us take the example in Figure 3.12 on page 112 with the same
parameters as before: m1 = 2, k1 = 4, and k2 = 2, except for m2 , which is unknown. Suppose
that there is a force cos(5t) acting on the first mass. Find an m2 on page 114, on page 112 with parameters m1 = m2 = 1,
k1 = k2 = 1. Does there exist a set of initial conditions for which the first cart moves but the second
cart does not? If so find those conditions, if not argue why not. 3.7. MULTIPLE EIGENVALUES 3.7 119 Multiple eigenvalues Note: 1–2 lectures, §5.4 in [EP]
It may very well happen that a matrix has some “repeated” eigenvalues. That is, the characteristic
equation det(A − λI ) = 0 may have repeated roots. As we have said before, this is actually unlikely
to happen for a random matrix. If you take a small perturbation of A (you change the entries of A
slightly) you will get a matrix with distinct eigenvalues. As any system you will want to solve in
practice is an approximation to reality anyway, it is not indispensable to know how to solve these
corner cases. But it may happen on occasion that it is easier or desirable to solve such a system
directly. 3.7.1 Geometric multiplicity Take the diagonal matrix
A= 30
.
03 A has an eigenvalue 3 of multiplicity 2. We usually call the multiplicity of the eigenvalue in the
characteristic equation the algebraic multiplicity. In this case, there also exist 2 linearly independent
eigenvectors, 1 and 0 corresponding to the eigenvalue 3. This means that the so-called geometric
0
1
multiplicity of this eigenvalue is also 2.
In all the theorems where we required a matrix to have n distinct eigenvalues, we only really
needed to have n linearly independent eigenvectors. For example, let x = A x has the general
solution
1 3t
0 3t
x = c1
e + c2
e.
0
1
Let us restate the theorem about real eigenvalues. In the following theorem we will repeat eigenvalues according to (algebraic) multiplicity. So for A above we would say that it has eigenvalues 3 and
3.
Theorem 3.7.1. Take x = P x. If P is n × n and has n real eigenvalues (not necessarily distinct),
λ1 , . . . , λn , and if there are n linearly independent corresponding eigenvectors v1 , . . . , vn , and the
general solution to the ODE can be written as.
x = c1 v1 eλ1 t + c2 v2 eλ2 t + · · · + cn vn eλn t .
The geometric multiplicity of an eigenvalue of algebraic multiplicity n is equal to the number of
corresponding linearly independent eigenvectors we can find. It is not hard to see that the geometric
multiplicity is always less than or equal to the algebraic multiplicity. We have, therefore, handled the
case when these two multiplicities are equal. If the geometric multiplicity is equal to the algebraic
multiplicity we say the eigenvalue is complete. 120 CHAPTER 3. SYSTEMS OF ODES In other words, the hypothesis of the theorem could be stated as saying that if all the eigenvalues
of P are complete, then there are n linearly independent eigenvectors and thus we have the given
general solution.
Note that if the geometric multiplicity of an eigenvalue is 2 or greater, then the set of linearly
independent eigenvectors is not unique up to multiples as it was before. For example, for the
1
diagonal matrix A above we could also pick eigenvectors 1 and −1 , or in fact any pair of two
1
linearly independent vectors. The number of eigenvalues is the number of free variables we obtain
when solving Av = λv. We then pick values for those free variables to obtain the eigenvectors. If
you pick different values, you may get different eigenvectors. 3.7.2 Defective eigenvalues If an n × n matrix has less than n linearly independent eigenvectors, it is said to be deficient. Then
there is at least one eigenvalue with an algebraic multiplicity that is higher than its geometric
multiplicity. We call this eigenvalue defective and the difference between the two multiplicities we
call the defect.
Example 3.7.1: The matrix
31
03
has an eigenvalue 3 of algebraic multiplicity 2. Let us try to compute the eigenvectors.
0 1 v1
= 0.
0 0 v2
We must have that v2 = 0. Hence any eigenvector is of the form v01 . Any two such vectors are
linearly dependent, and hence the geometric multiplicity of the eigenvalue is 1. Therefore, the
defect is 1, and we can no longer apply the eigenvalue method directly to a system of ODEs with
such a coefficient matrix.
The key observation we will use here is that if λ is an eigenvalue of A of algebraic multiplicity
m, then we will be able to find m linearly independent vectors solving the equation (A − λI )m v = 0.
We will call these the generalized eigenvectors.
Let us continue with the example A = 3 1 and the equation x = A x. We have an eigenvalue
03
λ = 3 of (algebraic) multiplicity 2 and defect 1. We have found one eigenvector v1 = 1 . We have
0
the solution
x1 = v1 e3t .
In this case, let us try (in the spirit of repeated roots of the characteristic equation for a single
equation) another solution of the form
x2 = (v2 + v1 t) e3t . 3.7. MULTIPLE EIGENVALUES 121 We differentiate to get
x2 = v1 e3t + 3(v2 + v1 t) e3t = (3v2 + v1 ) e3t + 3v1 te3t .
x2 must equal A x2 , and A x2 = A(v2 + v1 t) e3t = Av2 e3t + Av1 te3t . By looking at the coefficients of e3t and te3t we see 3v2 + v1 = Av2 and 3v1 = Av1 . This means that
(A − 3I )v1 = 0, (A − 3I )v2 = v1 . and If these two equations are satisfied, then x2 is a solution. We know the first of these equations is
satisfied because v1 is an eigenvector. If we plug the second equation into the first we obtain
(A − 3I )(A − 3I )v2 = 0, or (A − 3I )2 v2 = 0. If we can, therefore, find a v2 that solves (A − 3I )2 v2 = 0, and such that (A − 3I )v2 = v1 , then we are
done. This is just a bunch of linear equations to solve and we are by now very good at that.
We notice that in this simple case (A − 3I )2 is just the zero matrix (exercise). Hence, any vector
v2 solves (A − 3I )2 v2 = 0. We just have to make sure that (A − 3I )v2 = v1 . Write
01a
1
=
.
00b
0
By inspection we see that letting a = 0 (a could be anything in fact) and b = 1 does the job. Hence
we can take v2 = 0 . Our general solution to x = A x is
1
x = c1 1 3t
0
1
c e3t + c2 te3t
e + c2
+
t e3t = 1
.
0
1
0
c2 e3t Let us check that we really do have the solution. First x1 = c1 3e3t + c2 e3t + 3c2 te3t = 3 x1 + x2 . Good.
Now x2 = 3c2 e3t = 3 x2 . Good.
Note that the system x = A x has a simpler solution since A is a triangular matrix. In particular,
the equation for x2 does not depend on x1 . Mind you, not every defective matrix is triangular.
Exercise 3.7.1: Solve x = 3 1 x by first solving for x2 and then for x1 independently. Now check
03
that you got the same solution as we did above.
Let us describe the general algorithm. First for λ of multiplicity 2, defect 1. First find an
eigenvector v1 of λ. Now find a vector v2 such that
(A − 3I )2 v2 = 0,
(A − 3I )v2 = v1 . 122 CHAPTER 3. SYSTEMS OF ODES This gives us two linearly independent solutions
x1 = v1 eλt ,
x2 = v2 + v1 t eλt .
This machinery can also be generalized to larger matrices and higher defects. We will not go
over this method in detail, but let us just sketch the ideas. Suppose that A has a multiplicity m
eigenvalue λ. We find vectors such that
(A − λI )k v = 0, but (A − λI )k−1 v 0. Such vectors are called generalized eigenvectors. For every eigenvector v1 we find a chain of
generalized eigenvectors v2 through vk such that:
(A − λI )v1 = 0,
(A − λI )v2 = v1 ,
.
.
.
(A − λI )vk = vk−1 .
We form the linearly independent solutions
x1 = v1 eλt ,
x2 = (v2 + v1 t) eλt ,
.
.
.
xk = vk + vk−1 t + · · · + v2 t k −1
t k −2
+ v1
eλt .
(k − 2)!
(k − 1)! We proceed to find chains until we form m linearly independent solutions (m is the multiplicity).
You may need to find several chains for every eigenvalue. 3.7.3 Exercises Exercise 3.7.2: Let A = 5 −3
3 −1 . Solve x = A x. Exercise 3.7.3: Let A = 5 −4 4
030
−2 4 −1 . a) What are the eigenvalues? b) What is/are the defect(s) of the eigenvalue(s)? c) Solve x = A x.
Exercise 3.7.4: Let A = 210
020
002 . a) What are the eigenvalues? b) What is/are the defect(s) of the eigenvalue(s)? c) Solve x = A x in two different ways and verify you get the same answer. 3.7. MULTIPLE EIGENVALUES
Exercise 3.7.5: Let A = 123 012
−1 −2 −2
−4 4 7 . a) What are the eigenvalues? b) What is/are the defect(s) of the 0 4 −2
−1 −4 1
0 0 −2 . a) What are the eigenvalues? b) What is/are the defect(s) of the 2 1 −1
−1 0 2
−1 −2 4 . a) What are the eigenvalues? b) What is/are the defect(s) of the eigenvalue(s)? c) Solve x = A x.
Exercise 3.7.6: Let A = eigenvalue(s)? c) Solve x = A x.
Exercise 3.7.7: Let A = eigenvalue(s)? c) Solve x = A x. Exercise 3.7.8: Suppose that A is a 2 × 2 matrix with a repeated eigenvalue λ. Suppose that there
are two linearly independent eigenvectors. Show that the matrix is diagonal, in particular A = λI. 124 3.8 CHAPTER 3. SYSTEMS OF ODES Matrix exponentials Note: 2 lectures, §5.5 in [EP] 3.8.1 Definition In this section we present a different way of finding the fundamental matrix solution of a system.
Suppose that we have the constant coefficient equation
x = P x,
as usual. Now suppose that this was one equation (P is a number or a 1 × 1 matrix). Then the
solution to this would be
x = ePt .
It turns out the same computation works for matrices when we define ePt properly. First let us write
down the Taylor series for eat for some number a.
eat = 1 + at + (at)2 (at)3 (at)4
+
+
+ ··· =
2
6
24 ∞
k =0 (at)k
.
k! Recall k! = 1 · 2 · 3 · · · k, and 0! = 1. We differentiate this series term by term
a + a2 t + a3 t2 a4 t3
(at)2 (at)3
+
+ · · · = a 1 + at +
+
+ · · · = aeat .
2
6
2
6 Maybe we can write try the same trick here. Suppose that for an n × n matrix A we define the matrix
exponential as
1
1
1
def
e A = I + A + A2 + A3 + · · · + Ak + · · ·
2
6
k!
Let us not worry about convergence. The series really does always converge. We usually write Pt
as tP by convention when P is a matrix. With this small change and by the exact same calculation
as above we have that
d tP
e = PetP .
dt
Now P and hence etP is an n × n matrix. What we are looking for is a vector. We note that in the
1 × 1 case we would at this point multiply by an arbitrary constant to get the general solution. In the
matrix case we multiply by a column vector c.
Theorem 3.8.1. Let P be an n × n matrix. Then the general solution to x = P x is
x = etP c,
where c is an arbitrary constant vector. In fact x(0) = c. 3.8. MATRIX EXPONENTIALS 125 Let us check. d tP
d
x=
e c = PetP c = P x.
dt
dt
Hence etP is the fundamental matrix solution of the homogeneous system. If we find a way
to compute the matrix exponential, we will have another method of solving constant coefficient
homogeneous systems. It also makes it easy to solve for initial conditions. To solve x = A x,
x(0) = b, we take the solution
x = etA b.
This equation follows because e0A = I , so x(0) = e0A b = b.
We mention a drawback of matrix exponentials. In general eA+B eA eB . The trouble is that
matrices do not commute, that is, in general AB BA. If you try to prove eA+B eA eB using the
Taylor series, you will see why the lack of commutativity becomes a problem. However, it is still
true that if AB = BA, that is, if A and B commute, then eA+B = eA eB . We will find this fact useful.
Let us restate this as a theorem to make a point.
Theorem 3.8.2. If AB = BA, then eA+B = eA eB . Otherwise eA+B 3.8.2 eA eB in general. Simple cases In some instances it may work to just plug into the series definition. Suppose the matrix is diagonal.
a
For example, D = 0 0 . Then
b
ak 0
Dk =
,
0 bk
and
1
1
1 a2 0
1 a3 0
10
a0
ea 0
eD = I + D + D2 + D3 + · · · =
+
+
+
+ ··· =
.
01
0b
0 eb
2
6
2 0 b2
6 0 b3
So by this rationale we have that
eI = e0
0e and eaI = ea 0
.
0 ea This makes exponentials of certain other matrices easy to compute. Notice for example that
the matrix A = 5 −3 can be written as 2I + B where B = 3 −3 . Notice that 2I and B commute,
3 −3
3 −1
and that B2 = 0 0 . So Bk = 0 for all k ≥ 2. Therefore, eB = I + B. Suppose we actually want to
00
compute etA . 2tI and tB still commute (exercise: check this) and etB = I + tB, since (tB)2 = t2 B2 = 0.
We write
etA = e2tI +tB = e2tI etB = e2t 0
(I + tB) =
0 e2t
= e2t 0 1 + 3t −3t
(1 + 3t) e2t
−3te2t
=
.
0 e2t
3t
1 − 3t
3te2t
(1 − 3t) e2t 126 CHAPTER 3. SYSTEMS OF ODES So we have found the fundamental matrix solution for the system x = A x. Note that this matrix has
a repeated eigenvalue with a defect; there is only one eigenvector for the eigenvalue 2. So we have
found a perhaps easier way to handle this case. In fact, if a matrix A is 2 × 2 and has an eigenvalue
λ of multiplicity 2, then either it is diagonal, or A = λI + B where B2 = 0. This is a good exercise.
Exercise 3.8.1: Suppose that A is 2 × 2 and λ is the only eigenvalue. Then show that (A − λI )2 = 0.
Then we can write A = λI + B, where B2 = 0. Hint: First write down what does it mean for the
eigenvalue to be of multiplicity 2. You will get an equation for the entries. Now compute the square
of B.
Matrices B such that Bk = 0 for some k are called nilpotent. Computation of the matrix
exponential for nilpotent matrices is easy by just writing down the first k terms of the Taylor series. 3.8.3 General matrices In general, the exponential is not as easy to compute as above. We cannot usually write any matrix
as a sum of commuting matrices where the exponential is simple for each one. But fear not, it is still
not too difficult provided we can find enough eigenvectors. First we need the following interesting
result about matrix exponentials. For any two square matrices A and B, we have
−1 eBAB = BeA B−1 .
This can be seen by writing down the Taylor series. First note that
2 ( BAB−1 ) = BAB−1 BAB−1 = BAIAB−1 = BA2 B−1 .
k And hence by the same reasoning ( BAB−1 ) = BAk B−1 . So now write down the Taylor series for
−1
eBAB
1
1
−1
2
3
eBAB = I + BAB−1 + ( BAB−1 ) + ( BAB−1 ) + · · ·
2
6
1 2 −1 1 3 −1
= BB−1 + BAB−1 + BA B + BA B + · · ·
2
6
12 13
= B I + A + A + A + · · · B−1
2
6
A −1
= Be B .
Now we will write a general matrix A as EDE −1 , where D is diagonal. This procedure is called
diagonalization. If we can do that, you can see that the computation of the exponential becomes
easy. Adding t into the mix we see that
etA = EetD E −1 . 3.8. MATRIX EXPONENTIALS 127 Now to do this we will need n linearly independent eigenvectors of A. Otherwise this method
does not work and we need to be trickier, but we will not get into such details in this course. We
let E be the matrix with the eigenvectors as columns. Let λ1 , . . . , λn be the eigenvalues and let v1 ,
. . . , vn be the eigenvectors, then E = [ v1 v2 · · · vn ]. Let D be the diagonal matrix with the
eigenvalues on the main diagonal. That is λ1 0 · · · 0 0 λ2 · · · 0 . . .
D=. . . .
.. . . . . 0 0 · · · λn
Now we write
AE = A[ v1 v2 · · · vn ]
= [ Av1 Av2 · · · Avn ]
= [ λ1 v1 λ2 v2 · · · λn vn ]
= [ v1 v2 · · · vn ]D
= ED.
Now the columns of E are linearly independent as these are the eigenvectors of A. Hence E is
invertible. Since AE = ED, we right multiply by E −1 and we get
A = EDE −1 .
This means that eA = EeD E −1 . With t is turns into λ1 t 0 ··· 0 e 0 eλ2 t · · · 0 −1 tA
tD −1
.
e = Ee E = E . .
. E .
.. .
.
.
. .
. λn t 0
0 ··· e (3.4) The formula (3.4), therefore, gives the formula for computing the fundamental matrix solution etA
for the system x = A x, in the case where we have n linearly independent eigenvectors.
Notice that this computation still works when the eigenvalues and eigenvectors are complex,
though then you will have to compute with complex numbers. Note that it is clear from the definition
that if A is real, then etA is real. So you will only need complex numbers in the computation and
you may need to apply Euler’s formula to simplify the result. If simplified properly the final matrix
will not have any complex numbers in it.
Example 3.8.1: Compute the fundamental matrix solution using the matrix exponentials for the
system
x
12x
=
.
y
21y 128 CHAPTER 3. SYSTEMS OF ODES Then compute the particular solution for the initial conditions x(0) = 4 and y(0) = 2.
Let A be the coefficient matrix 1 2 . We first compute (exercise) that the eigenvalues are 3 and
21
1
−1 and the corresponding eigenvectors are 1 and −1 . Hence we write
1
−1 1 1 e3t 0 1 1
1 −1 0 e−t 1 −1
1 1 e3t 0 −1 −1 −1
=
1 −1 0 e−t 2 −1 1
−1 e3t e−t −1 −1
=
2 e3t −e−t −1 1 etA = = −1 −e3t − e−t −e3t + e−t
=
2 −e3t + e−t −e3t − e−t e 3 t +e − t
2
e 3 t −e − t
2 e3t −e−t
2
e3t +e−t
2 . The initial conditions are x(0) = 4 and y(0) = 2. Hence, by the property that e0A = I we find that
the particular solution we are looking for is etA b where b is 4 . Then the particular solution we are
2
looking for is
x
=
y 3.8.4 e 3 t +e − t
2
e 3 t −e − t
2 e3t −e−t
2
e3t +e−t
2 4
2e3t + 2e−t + e3t − e−t
3e3t + e−t
=
=
.
2
2e3t − 2e−t + e3t + e−t
3e3t − e−t Fundamental matrix solutions We note that if you can compute the fundamental matrix solution in a different way, you can use
this to find the matrix exponential etA . The fundamental matrix solution of a system of ODEs is
not unique. The exponential is the fundamental matrix solution with the property that for t = 0
we get the identity matrix. So we must find the right fundamental matrix solution. Let X be any
fundamental matrix solution to x = A x. Then we claim
etA = X (t) [X (0)]−1 .
Obviously if we plug t = 0 into X (t) [X (0)]−1 we get the identity. It is not hard to see that we can
multiply a fundamental matrix solution on the right by any constant invertible matrix and we still
get a fundamental matrix solution. All we are doing is changing what the arbitrary constants are in
the general solution x(t) = X (t)c. 3.8.5 Approximations If you think about it, the computation of any fundamental matrix solution X using the eigenvalue
method is just as difficult as computation of etA . So perhaps we did not gain much by this new tool.
However, the Taylor series expansion actually gives us a very easy way to approximate solutions,
which the eigenvalue method did not. 3.8. MATRIX EXPONENTIALS 129 The simplest thing we can do is to just compute the series up to a certain number of terms. There
are better ways to approximate the exponential∗ . In many cases however, few terms of the Taylor
series give a reasonable approximation for the exponential and may suffice for the application. For
example, let us compute the first 4 terms of the series for the matrix A = 1 2 .
21
5
12
t2 2 t3 3
22 2
3
+t
e ≈ I + tA + A + A = I + t
5 +t
2
6
21
22
tA 13
6
7
3 7
3
13
6
52
t
2
2 = 1+t+
+ 13 t3
2 t + 2 t2 + 7 t3
6
3
=
.
73
52
2t + 2t + 3 t
1 + t + 2 t + 13 t3
6
Just like the scalar version of the Taylor series approximation, the approximation will be better for
small t and worse for larger t. For larger t, we will generally have to compute more terms. Let us see
how we stack up against the real solution with t = 0.1. The approximate solution is approximately
(rounded to 8 decimal places)
e0.1 A ≈ I + 0.1 A + 0.12 2 0.13 3
1.12716667 0.22233333
A+
A=
.
0.22233333 1.12716667
2
6 And plugging t = 0.1 into the real solution (rounded to 8 decimal places) we get
e0.1 A = 1.12734811 0.22251069
.
0.22251069 1.12734811 This is not bad at all. Although if we take the same approximation for t = 1 we get (using the Taylor
series)
6.66666667 6.33333333
,
6.33333333 6.66666667
while the real value is (again rounded to 8 decimal places)
10.22670818 9.85882874
.
9.85882874 10.22670818
So the approximation is not very good once we get up to t = 1. To get a good approximation at
t = 1 (say up to 2 decimal places) we would need to go up to the 11th power (exercise). 3.8.6 Exercises Exercise 3.8.2: Find a fundamental matrix solution for the system x = 3 x + y, y = x + 3y.
Exercise 3.8.3: Find eAt for the matrix A =
∗ 23
02 . C. Moler and C.F. Van Loan, Nineteen Dubious Ways to Compute the Exponential of a Matrix, Twenty-Five Years
Later, SIAM Review 45 (1), 2003, 3–49 130 CHAPTER 3. SYSTEMS OF ODES Exercise 3.8.4: Find a fundamental matrix solution for the system x1 = 7 x1 + 4 x2 + 12 x3 , x2 =
x1 + 2 x2 + x3 , x3 = −3 x1 − 2 x2 − 5 x3 . Then find the solution that satisfies x =
Exercise 3.8.5: Compute the matrix exponential eA for A = 12
01 0
1
−2 . . Exercise 3.8.6: Suppose AB = BA (matrices commute). Show that eA+B = eA eB .
−1 Exercise 3.8.7: Use Exercise 3.8.6 to show that (eA )
invertible even if A is not. = e−A . In particular this means that eA is Exercise 3.8.8: Suppose A is a matrix with eigenvalues −1, 1, and corresponding eigenvectors 1 ,
1
0 . a) Find matrix A with these properties. b) Find the fundamental matrix solution to x = A x. c)
1
Solve the system in with initial conditions x(0) = 2 .
3
Exercise 3.8.9: Suppose that A is an n × n matrix with a repeated eigenvalue λ of multiplicity n.
Suppose that there are n linearly independent eigenvectors. Show that the matrix is diagonal, in
particular A = λI . Hint: Use diagonalization and the fact that the identity matrix commutes with
every other matrix. 3.9. NONHOMOGENEOUS SYSTEMS 3.9 131 Nonhomogeneous systems Note: 3 lectures (may have to skip a little), somewhat different from §5.6 in [EP] 3.9.1 First order constant coefficient Integrating factor
Let us first focus on the nonhomogeneous first order equation
x (t) = A x(t) + f (t),
where A is a constant matrix. The first method we will look at is the integrating factor method. For
simplicity we rewrite the equation as
x (t) + P x(t) = f (t),
where P = −A. We multiply both sides of the equation by etP (being mindful that we are dealing
with matrices that may not commute) to obtain
etP x (t) + etP P x(t) = etP f (t).
We notice that PetP = etP P. This fact follows by writing down the series definition of etP ,
1
1
PetP = P I + I + tP + (tP)2 + · · · = P + tP2 + t2 P3 + · · · =
2
2
1
= I + I + tP + (tP)2 + · · · P = PetP .
2
We have already seen that d
dt etP = PetP . Hence,
d tP
e x(t) = etP f (t).
dt We can now integrate. That is, we integrate each component of the vector separately
etP x(t) =
−1 Recall from Exercise 3.8.7 that (etP ) etP f (t) dt + c. = e−tP . Therefore, we obtain x(t) = e−tP etP f (t) dt + e−tP c. 132 CHAPTER 3. SYSTEMS OF ODES Perhaps it is better understood as a definite integral. In this case it will be easy to also solve for
the initial conditions as well. Suppose we have the equation with initial conditions
x (t) + P x(t) = f (t), x(0) = b. The solution can then be written as
t x(t) = e e sP f ( s) ds + e−tP b. −tP (3.5) 0 Again, the integration means that each component of the vector e sP f ( s) is integrated separately. It is
not hard to see that (3.5) really does satisfy the initial condition x(0) = b.
0 x(0) = e−0P e sP f ( s) ds + e−0P b = I b = b.
0 Example 3.9.1: Suppose that we have the system
x1 + 5 x1 − 3 x2 = et ,
x2 + 3 x1 − x2 = 0,
with initial conditions x1 (0) = 1, x2 (0) = 0.
Let us write the system as
x+ 5 −3
et
x=
,
3 −1
0 x(0) = 1
.
0 We have previously computed etP for P = 5 −3 . We immediately also have e−tP , simply by negating
3 −1
t.
(1 + 3t) e2t
−3te2t
(1 − 3t) e−2t
3te−2t
etP =
,
e−tP =
.
3te2t
(1 − 3t) e2t
−3te−2t
(1 + 3t) e−2t
Instead of computing the whole formula at once. Let us do it in stages. First
t (1 + 3 s) e2 s
−3 se2 s
es
ds
2s
2s
3 se
(1 − 3 s) e
0 t t (1 + 3 s) e3 s
ds
3 se3 s e f ( s) ds =
sP 0 0 =
0 = te3t
(3t−1) e3t +1
3 . 3.9. NONHOMOGENEOUS SYSTEMS 133 Then
t x(t) = e e sP f ( s) ds + e−tP b −tP
0 =
=
= (1 − 3t) e−2t
3te−2t
−3te−2t
(1 + 3t) e−2t
te
t
−e
3 t
−e
3 + 1
3 −2t +t e −2t + te3t
(3t−1) e3t +1
3
−2t + 1
(1 − 3t) e−2t
3te−2t
−2t
−2t
−3te
(1 + 3t) e
0 (1 − 3t) e
−3te−2t (1 − 2t) e−2t
.
+ 1 − 2t e−2t
3 Phew!
Let us check that this really works.
x1 + 5 x1 − 3 x2 = (4te−2t − 4e−2t ) + 5(1 − 2t) e−2t + et − (1 − 6t) e−2t = et .
Similarly (exercise) x2 + 3 x1 − x2 = 0. The initial conditions are also satisfied as well (exercise).
For systems, the integrating factor method only works if P does not depend on t, that is, P is
constant. The problem is that in general
d
e
dt P(t) dt P(t) e P(t) dt , because matrices generally do not commute.
Eigenvector decomposition
For the next method, we note that
x (t) = A x(t) + f (t).
(3.6)
Assume that A has n linearly independent eigenvectors v1 , . . . , vn . Let us write
x(t) = v1 ξ1 (t) + v2 ξ2 (t) + · · · + vn ξn (t). (3.7) That is, we wish to write our solution as a linear combination of the eigenvectors of A. If we can
solve for the scalar functions ξ1 through ξn we have our solution x. Let us decompose f in terms of
the eigenvectors as well. Write
f (t) = v1 g1 (t) + v2 g2 (t) + · · · + vn gn (t). (3.8) 134 CHAPTER 3. SYSTEMS OF ODES That is, we wish to find g1 through gn that satisfy (3.8). We note that since all the eigenvectors of A
are independent, the matrix E = [ v1 v2 · · · vn ] is invertible. We see that (3.8) can be written
as f = E g, where the components of g are the functions g1 through gn . Then g = E −1 f . Hence it is
always possible to find g when there are n linearly independent eigenvectors.
We plug (3.7) into (3.6), and note that Avk = λk vk . ).
If we identify the coefficients of the vectors v1 through vn we get the equations
ξ1 = λ1 ξ1 + g1 ,
ξ2 = λ2 ξ2 + g2 ,
.
.
.
ξn = λn ξn + gn .
Each one of these equations is independent of the others. They are all linear first order equations
and can easily be solved by the standard integrating factor method for single equations. That is, for
example for the kth equation we write
ξk (t) − λk ξk (t) = gk (t).
We use the integrating factor e−λk t to find that
d
ξk (t) e−λk t = e−λk t gk (t).
dx
Now we integrate and solve for ξk to get
ξk (t) = eλk t e−λk t gk (t) dt + Ck eλk t . Note that if you are looking for just any particular solution, you could set Ck to be zero. If we leave
these constants in, we will get the general solution. Write x(t) = v1 ξ1 (t) + v2 ξ2 (t) + · · · + vn ξn (t),
and we are done.
Again, as always, it is perhaps better to write these integrals as definite integrals. Suppose that
we have an initial condition x(0) = b. We take c = E −1 b and note b = v1 a1 + · · · + vn an , just like
before. Then if we write
t ξk (t) = eλk t
0 e−λk s gk ( s) dt + ak eλk t , 3.9. NONHOMOGENEOUS SYSTEMS 135 we will actually get the particular solution x(t) = v1 ξ1 (t) + v2 ξ2 (t) + · · · + vn ξn (t) satisfying x(0) = b,
because ξk (0) = ak .
3/16
Example 3.9.2: Let A = 1 3 . Solve x = A x + f where f (t) = 22et for x(0) = −5/16 .
31
1
The eigenvalues of A are −2 and 4 and the corresponding eigenvectors are −1 and 1 respec1
tively. This calculation is left as an exercise. We write down the matrix E of the eigenvectors and
compute its inverse (using the inverse formula for 2 × 2 matrices)
t E= 11
,
−1 1 We are looking for a solution of the form x =
of the eigenvectors. That is we wish to write f = E −1 =
1
−1
2et
2t 1 1 −1
.
21 1 ξ1 + 1 ξ2 . We also wish to write f in terms
1
1
= −1 g1 + 1 g2 . Thus
1 1 1 −1 2et
g1
2et
et − t
= E −1
=
=t
.
2t
g2
e +t
2 1 1 2t
So g1 = et − t and g2 = et + t.
We further want to write x(0) in terms of the eigenvectors. That is, we wish to write x(0) =
3/16
1
1
−5/16 = −1 a1 + 1 a2 . Hence
a1
= E −1
a2 3
16
−5
16 1
4
−1
16 = . So a1 = 1/4 and a2 = −1/16. We plug our x into the equation and get that
1
1
1
1
1
1
ξ1 +
ξ2 = A
ξ1 + A
ξ2 +
g1 +
g
−1
1
−1
1
−1
12
= 1
1
1
1t
(−2ξ1 ) +
4ξ2 +
(et − t) +
(e − t).
−1
1
−1
1 We get the two equations
ξ1 = −2ξ1 + et − t,
ξ2 = 4ξ2 + et + t, 1
where ξ1 (0) = a1 = ,
4
−1
where ξ2 (0) = a2 =
.
16 We solve with integrating factor. Computation of the integral is left as an exercise to the student.
Note that you will need integration by parts.
ξ1 = e−2t e2t (et − t) dt + C1 e−2t = et t 1
− + + C1 e−2t .
324 136 CHAPTER 3. SYSTEMS OF ODES C1 is the constant of integration. As ξ1 (0) = 1/4, then 1/4 = 1/3 + 1/4 + C1 and hence C1 =
Similarly
et t
1
ξ2 = e4t e−4t (et + t) dt + C2 e4t = − − −
+ C2 e4t .
3 4 16 −1/3. As ξ2 (0) = 1/16 we have that −1/16 = −1/3 − 1/16 + C2 and hence C2 = 1/3. The solution is
1
x(t) =
−1
That is, x1 = e 4 t −e − 2 t
3 + et − e−2t 1 − 2t
1
+
+
1
3
4
3−12t
16 and x2 = e−2t +e4t +2et
3 + e4t − et 4t + 1
−
=
3
16 e4t −e−2t
+ 3−12t
3
16
−2t +e4t +2et
t−
e
+ 4165
3 . 4t−5
.
16 Exercise 3.9.1: Check that x1 and x2 solve the problem. Check both that they satisfy the differential
equation and that they satisfy the initial conditions.
Undetermined coefficients
The method of undetermined coefficients also works. The only difference here is that we will have
to take unknown vectors rather than just numbers. Same caveats apply to undetermined coefficients
for systems as they do for single equations. This method does not always work. Furthermore if the
right hand side is complicated, we will have to solve for lots of variables. In this case we can think
of each element of an unknown vector as an unknown number. So in system of 3 equations if we
have say 4 unknown vectors (this would not be uncommon), then we already have 12 unknowns that
we need to solve for. The method can turn into a lot of tedious work. As this method is essentially
the same as it is for single equations, let us just do an example.
Example 3.9.3: Let A = −1 0 . Find a particular solution of x = A x + f where f (t) = et .
−2 1
Note that we can solve this system in an easier way (can you see how), but for the purposes of
the example, let us use the eigenvalue method plus undetermined coefficients.
The eigenvalues of A are −1 and 1 and the corresponding eigenvectors are 1 and 0 respec1
1
tively. Hence our complementary solution is
t xc = α1 1 −t
0t
e + α2
e,
1
1 for some arbitrary constants α1 and α2 .
We would want to guess a particular solution of
x = aet + bt + c.
However, something of the form aet appears in the complementary solution. Because we do not yet
know if the vector a is a multiple of 0 we do not know if a conflict arises. It is possible that no
1 3.9. NONHOMOGENEOUS SYSTEMS 137 conflict arises, but to be safe we should also try btet . Here we find the crux of the difference for
systems. You want to try both aet and btet in your solution, not just btet . Therefore, we try
x = aet + btet + ct + d.
Thus we have 8 unknowns. We write a = a1 , b =
a2
this into the equation. First let us compute x . b1
b2 ,c= c1
c2 , and d = d1
d2 , We have to plug x = a + b et + btet + c.
Now x must equal A x + f so
A x + f = Aaet + Abtet + Act + Ad + f =
= −a1
−b1
−c1
−d1
et
et +
t et +
t+
+
.
−2a1 + a2
−2b1 + b2
−2c1 + c2
−2d1 + d2
t Now we identify the coefficients of et , tet , t and any constants.
a1 + b1 = −a1 + 1,
a2 + b2 = −2a1 + a2 ,
b1 = −b1 ,
b2 = −2b1 + b2 ,
0 = −c1 ,
0 = −2c1 + c2 + 1,
c1 = −d1 ,
c2 = −2d1 + d2 .
We could write this is an 8 × 9 augmented matrix and start row reduction, but it is easier to just do
this in an ad hoc manner. Immediately we see that b1 = 0, c1 = 0, d1 = 0. Plugging these back in
we get that c2 = −1 and d2 = −1. The remaining equations that tell us something are
a1 = −a1 + 1,
a2 + b2 = −2a1 + a2 .
So a1 = 1 and b2 = −1. a2 can be arbitrary and still satisfy the equation. We are looking for just a
2
single solution so presumably the simplest one is when a2 = 0. Therefore,
x = aet + btet + ct + d = 1
2 0 et + 1t
0
0
0
e
2
t et +
t+
=
.
t
−1
−1
−1
−te − t − 1 That is, x1 = 1 et , x2 = −tet − t − 1. You would add this to the complementary solution to get the
2
general solution of the problem. Notice also that both aet and btet really was needed. 138 CHAPTER 3. SYSTEMS OF ODES Exercise 3.9.2: Check that x1 and x2 solve the problem. Also try setting a2 = 1. 3.9.2 First order variable coefficient you have somehow solved the associated homogeneous problem.
Suppose we have the equation
x = A(t) x + f (t).
(3.9)
Further, suppose that you have solved the associated homogeneous equation x = A(t) x and found
the fundamental matrix solution X (t). The general solution to the associated homogeneous equation
is X (t)c for a constant vector c. Just like for variation of parameters for single equation we try the
solution to the nonhomogeneous equation of the form
x p = X (t) u(t),
where u(t) is a vector valued function instead of a constant. Now substitute into (3.9) to obtain
x p (t) = X (t) u(t) + X (t) u (t) = A(t) X (t) u(t) + f (t).
But X is the fundamental matrix solution to the homogeneous problem so X (t) = A(t)X (t), and thus
X (t) u(t) + X (t) u (t) = X (t) u(t) + f (t).
Hence X (t) u (t) = f (t). If we compute [X (t)]−1 , then u (t) = [X (t)]−1 f (t). Now integrate to obtain
u and we have the particular solution x p = X (t) u(t). Let us write this as a formula
x p = X (t) [X (t)]−1 f (t) dt. Note that if A is constant and you let X (t) = etA , then [X (t)]−1 = e−tA and hence we get a solution
x p = etA e−tA f (t) dt, which is precisely what we got using the integrating factor method.
Example 3.9.4: Find a particular solution to
x= t2 1
t −1
t2
x+
(t + 1).
1t
1
+1 (3.10) 3.9. NONHOMOGENEOUS SYSTEMS 139 t
Here A = t21 1 1 −t1 is most definitely not constant. Perhaps by a lucky guess, we find that
+
X = 1 −t solves X (t) = A(t)X (t). Once we know the complementary solution we can easily find a
t1
solution to (3.10). First we find [X (t)]−1 = t2 1
1t
.
+ 1 −t 1 Next we know a particular solution to (3.10) is
x p = X (t) [X (t)]−1 f (t) dt
1
1tt2
(t + 1) dt
2 + 1 −t 1 1
t
2t
dt
−t2 + 1 = 1 −t
t1 = 1 −t
t1 = 1 −t
t2
t 1 − 1 t3 + t
3 = 14
t
3
23
t+
3 t . Adding the complementary solution we have that the general solution to (3.10).
x= 1 −t c1
+
t 1 c2 14
t
3
23
t+
3 t = 1
c1 − c2 t + 3 t4
.
c2 + (c1 + 1) t + 2 t3
3 2
Exercise 3.9.3: Check that x1 = 1 t4 and x2 = 3 t3 + t really solve (3.10).
3 In the variation of parameters, just like in the integrating factor method we can obtain the general
solution by adding in constants of integration. That is, we will add X (t)c for a vector of arbitrary
constants. But that is precisely the complementary solution. 3.9.3 Second order constant coefficients Undetermined coefficients
We have already previously did you can make, as we did in § 3.6. Let the
equation be
x = A x + F (t),
where A is a constant matrix. If F (t) is of the form F0 cos(ωt), then you can try a solution of the
form
x p = c cos(ωt), 140 CHAPTER 3. SYSTEMS OF ODES and you do not need to introduce sines.
If the F is a sum of cosines, you note that we still have the superposition principle, so if
F (t) = F0 cos(ω0 t) + F1 cos(ω1 t), you could try a cos(ω0 t) for the problem x = A x + F0 cos(ω0 t),
and you would try b cos(ω1 t) for the problem x = A x + F0 cos(ω1 t). Then sum the solutions.
However, if there is duplication with the complementary solution, or the equation is of the form
x = A x + B x + F (t), then you need to do the same thing as you do for first order systems.
Actually you will never go wrong with putting in more terms than needed into your guess. You
will just find that the extra coefficients will turn out to be zero. But it is useful to save some time
and effort.
Eigenvector decomposition
If we have the system
x = A x + F (t),
we can do eigenvector decomposition, just like for first order systems.
Let λ1 , . . . , λn be the eigenvalues and v1 , . . . , vn be the eigenvectors. Again form the matrix
E = [ v1 · · · vn ]. Write
x(t) = v1 ξ1 (t) + v2 ξ2 (t) + · · · + vn ξn (t).
Decompose F in terms of the eigenvectors
F (t) = v1 g1 (t) + v2 g2 (t) + · · · + vn gn (t).
And again g = E −1 F .
Now plug in and doing the same thing as before ).
Identify the coefficients of the eigenvectors to get the equations
ξ1 = λ1 ξ1 + g1 ,
ξ2 = λ2 ξ2 + g2 ,
.
.
.
ξn = λn ξn + gn .
Each one of these equations is independent of the others. Now solve each one of these using
the methods of chapter 2. Now write x(t) = v1 ξ1 (t) + · · · + vn ξn (t), and we are done; we have
a particular solution. If you have found the general solution for ξ1 through ξn , then again x(t) =
v1 ξ1 (t) + · · · + vn ξn (t) is the general solution. 3.9. NONHOMOGENEOUS SYSTEMS 141 Example 3.9.5: Let us do the example from § 3.6 using this method. The equation is
x= 0
−3 1
x+
cos(3t).
2
2 −2 The eigenvalues were −1 and −4, with eigenvectors
1
1
E −1 = 3 1 −1 . Therefore,
2 1
2 and 0
g1
11 1
=
= E −1 F (t) =
3 2 −1 2 cos(3t)
g2 1
−1 . Therefore E = 2
cos(3t)
3
−2
cos(3t)
3 11
2 −1 and . So after the whole song and dance of plugging in, the equations we get are
2
cos(3t),
3
2
ξ2 = −4 ξ2 − cos(3t).
3 ξ1 = −ξ1 + For each we can try the method of undetermined coefficients and try C1 cos(3t) for the first equation
and C2 cos(3t) for the second equation. We plug in to get
2
cos(3t),
3
2
−9C2 cos(3t) = −4C2 cos(3t) − cos(3t).
3
−9C1 cos(3t) = −C1 cos(3t) + Each of these equations we solve separately. We get −9C1 = −C1 + 2/3 and −9C2 = −4C2 − 2/3. And
hence C1 = −1/12 and C2 = 2/15. So our particular solution is
x= 1
2 −1
1
cos(3t) +
−1
12 2
cos(3t) =
15 1/20
−3/10 cos(3t). This solution matches what we got previously in § 3.6. 3.9.4 Exercises Exercise 3.9.4: Find a particular solution to x = x + 2y + 2t, y = 3 x + 2y − 4, a) using integrating
factor method, b) using eigenvector decomposition, c) using undetermined coefficients.
Exercise 3.9.5: Find the general solution to x = 4 x + y − 1, y = x + 4y − et , a) using integrating
factor method, b) using eigenvector decomposition, c) using undetermined coefficients.
Exercise 3.9.6: Find the general solution to x1 = −6 x1 + 3 x2 + cos(t), x2 = 2 x1 − 7 x2 + 3 cos(t), a)
using eigenvector decomposition, b) using undetermined coefficients. 142 CHAPTER 3. SYSTEMS OF ODES Exercise 3.9.7: Find the general solution to x1 = −6 x1 + 3 x2 + cos(2t), x2 = 2 x1 − 7 x2 + 3 cos(2t),
a) using eigenvector decomposition, b) using undetermined coefficients.
Exercise 3.9.8: Take the equation
x= 1
t 1 −1
1
t x+ t2
.
−t a) Check that
xc = c1 t sin t
t cos t
+ c2
−t cos t
t sin t is the complementary solution. b) Use variation of parameters to find a particular solution. Chapter 4
Fourier series and PDEs
4.1 Boundary value problems Note: 2 lectures, similar to §3.8 in [EP] 4.1.1 Boundary value problems Before we tackle the Fourier series, we need to study the so-called boundary value problems (or
endpoint problems). For example, suppose we have
x + λ x = 0, x(a) = 0, x(b) = 0, for some constant λ, where x(t) is defined for t in the interval [a, b]. Unlike before, when we
specified the value of the solution and its derivative at a single point, we now specify the value of
the solution at two different points. Note that x = 0 is a solution to this equation, so existence of
solutions is not an issue here. Uniqueness of solutions is another issue. The general solution to
x + λ x = 0 will have two arbitrary constants present. It is, therefore, natural (but wrong) to believe
that requiring two conditions will guarantee a unique solution.
Example 4.1.1: Take λ = 1, a = 0, b = π. That is,
x + x = 0, x(0) = 0, x(π) = 0. Then x = sin t is another solution (besides x = 0) satisfying both boundary conditions. There are
more. Write down the general solution of the differential equation, which is x = A cos t + B sin t.
The condition x(0) = 0 forces A = 0. Letting x(π) = 0 does not give us any more information as
x = B sin t already satisfies both boundary conditions. Hence, there are infinitely many solutions of
the form x = B sin t, where B is an arbitrary constant.
143 144 CHAPTER 4. FOURIER SERIES AND PDES Example 4.1.2: On the other hand, change to λ = 2.
x + 2 x = 0, x(0) = 0, x(π) = 0.
√
√
Then the general solution is x = A cos( 2 t) + B sin( 2 t). Letting x(0) = 0 still forces A = 0. We
√
√
apply the second condition to find 0 = x(π) = B sin( 2 π). As sin( 2 π) 0 we obtain B = 0.
Therefore x = 0 is the unique solution to this problem.
What is going on? We will be interested in finding which constants λ allow a nonzero solution,
and we will be interested in finding those solutions. This problem is an analogue of finding
eigenvalues and eigenvectors of matrices. 4.1.2 Eigenvalue problems For basic Fourier series theory we will need the following three eigenvalue problems. We will
consider more general equations, but we will postpone this until chapter 5.
x + λ x = 0, x(a) = 0, x(b) = 0, (4.1) x + λ x = 0, x (a) = 0, x (b) = 0, (4.2) x (a) = x (b), (4.3) and
x + λ x = 0, x(a) = x(b), A number λ is called an eigenvalue of (4.1) (resp. (4.2) or (4.3)) if and only if there exists a nonzero
(not identically zero) solution to (4.1) (resp. (4.2) or (4.3)) given that specific λ. The nonzero
solution we found is called the corresponding eigenfunction.
Note the similarity to eigenvalues and eigenvectors of matrices. The similarity is not just
coincidental. If we think of the equations as differential operators, then we are doing the same exact
d2
thing. For example, let L = − dt2 . We are looking for nonzero functions f satisfying certain endpoint
conditions that solve (L − λ) f = 0. A lot of the formalism from linear algebra can still apply here,
though we will not pursue this line of reasoning too far.
Example 4.1.3: Let us find the eigenvalues and eigenfunctions of
x + λ x = 0, x(0) = 0, x(π) = 0. For reasons that will be clear from the computations, we will have to handle the cases λ > 0,
λ = 0, λ < 0 separately. First suppose that λ > 0, then the general solution to x + λ x = 0 is
√
√
x = A cos( λ t) + B sin( λ t).
The condition x(0) = 0 implies immediately A = 0. Next
√
0 = x(π) = B sin( λ π). 4.1. BOUNDARY VALUE PROBLEMS 145 If B√ zero, then x is not a nonzero solution. So to get a nonzero solution we must have that
is
√
√
sin( λ π) = 0. Hence, λ π must be an integer multiple of π. In other words, λ = k for a
positive integer k. Hence the positive eigenvalues are k2 for all integers k ≥ 1. The corresponding
eigenfunctions can be taken as x = sin(kt). Just like for eigenvectors, we get all the multiples of an
eigenfunction, so we only need to pick one.
Now suppose that λ = 0. In this case the equation is x = 0 and the general solution is x = At + B.
The condition x(0) = 0 implies that B = 0, and x(π) = 0 implies that A = 0. This means that λ = 0
is not an eigenvalue.
Finally, suppose that λ < 0. In this case we have the general solution
√
√
x = A cosh( −λ t) + B sinh( −λ t).
Letting x(0) = 0 implies that A = 0 (recall cosh 0 = 1 and sinh 0 = 0). So our solution must be
√
x = B sinh( −λ t) and satisfy x(π) = 0. This is only possible if B is zero. Why? Because sinh ξ is
only zero for ξ = 0, you should plot sinh to see this. We can also see this from the definition of sinh.
t
−t
We get 0 = sinh t = e −e . Hence et = e−t , which implies t = −t and that is only true if t = 0. So
2
there are no negative eigenvalues.
In summary, the eigenvalues and corresponding eigenfunctions are
λk = k2 with an eigenfunction xk = sin(kt) for all integers k ≥ 1. Example 4.1.4: Let us compute the eigenvalues and eigenfunctions of
x + λ x = 0, x (0) = 0, x (π) = 0. Again we will have to handle the cases λ > 0,√ = 0, λ < 0 √
λ
separately. First suppose that λ > 0.
The general solution to x + λ x = 0 is x = A cos( λ t) + B sin( λ t). So
√
√
√
√
x = −A λ sin( λ t) + B λ cos( λ t).
The condition x (0) = 0 implies immediately B = 0. Next
√
√
0 = x (π) = −A λ sin( λ π).
√
√
Again A cannot be zero if λ is to be an eigenvalue, and sin( λ π) is only zero if λ = k for a positive
integer k. Hence the positive eigenvalues are again k2 for all integers k ≥ 1. And the corresponding
eigenfunctions can be taken as x = cos(kt).
Now suppose that λ = 0. In this case the equation is x = 0 and the general solution is x = At + B
so x = A. x (0) = 0 implies that A = 0. Obviously setting x (π) = 0 does not get us anything new.
This means that B could be anything (let us take it to be 1). So λ = 0 is an eigenvalue and x = 1 is a
corresponding eigenfunction.
√
√
Finally, let λ < 0. In this case we have the general solution x = A cosh( −λ t) + B sinh( −λ t)
and hence
√
√
√
√
x = A −λ sinh( −λ t) + B −λ cosh( −λ t). 146 CHAPTER 4. FOURIER SERIES AND PDES We have already seen (with roles of A and B switched) that for this to be zero at t = 0 and t = π it
implies that A = B = 0. Hence there are no negative eigenvalues.
In summary, the eigenvalues and corresponding eigenfunctions are
λk = k2 with an eigenfunction xk = cos(kt) for all integers k ≥ 1, and there is another eigenvalue
λ0 = 0 with an eigenfunction x0 = 1. The following problem is the one that leads to the general Fourier series.
Example 4.1.5: Let us compute the eigenvalues and eigenfunctions of
x + λ x = 0, x(−π) = x(π), x (−π) = x (π). You should notice that we have not specified the values or the derivatives at the endpoints, but rather
that they are the same at the beginning and at the end of the interval.
Let us skip λ < 0. The computations are the same and again we find that there are no negative
eigenvalues.
For λ = 0, the general solution is x = At + B. The condition x(−π) = x(π) implies that A = 0
(Aπ + B = −Aπ + B implies A = 0). The second condition x (−π) = x (π) says nothing about B and
hence λ = 0 is an eigenvalue with a √
corresponding eigenfunction x = 1.
√
For λ > 0 we get that x = A cos( λ t) + B sin( λ t). Now
√
√
√
√
A cos(− λ π) + B sin(− λ π) = A cos( λ π) + B sin( λ π).
We remember that cos(−θ) = cos(θ) and sin(−θ) = − sin(θ). Therefore,
√
√
√
√
A cos( λ π) − B sin( λ π) = A cos( λ π) + B sin( λ π).
√
and hence either B = 0 or sin( λ π) = 0. Similarly (exercise) if we differentiate x and plug in the
√
second condition we find that A = 0 or sin(√λ π) = 0. Therefore, unless we want A and B to both be
√
zero (which we do not) we must have sin( λ π) = 0. Hence, λ is an integer and the eigenvalues
are yet again λ = k2 for an integer k ≥ 1. In this case, however, x = A cos(kt) + B sin(kt) is an
eigenfunction for any A and any B. So we have two linearly independent eigenfunctions sin(kt) and
cos(kt). Remember that for a matrix we could also have had two eigenvectors corresponding to a
single eigenvalue if the eigenvalue was repeated.
In summary, the eigenvalues and corresponding eigenfunctions are
λk = k2
λ0 = 0 with the eigenfunctions
with an eigenfunction cos(kt)
x0 = 1. and sin(kt) for all integers k ≥ 1, 4.1. BOUNDARY VALUE PROBLEMS 4.1.3 147 Orthogonality of eigenfunctions Something that will be very useful in the next section is the orthogonality property of the eigenfunctions. This is an analogue of the following fact about eigenvectors of a matrix. A matrix is
called symmetric if A = AT . Eigenvectors for two distinct eigenvalues of a symmetric matrix are
orthogonal. That symmetry is required. We will not prove this fact here. The differential operators
we are dealing with act much like a symmetric matrix. We, therefore, get the following theorem.
Theorem 4.1.1. Suppose that x1 (t) and x2 (t) are two eigenfunctions of the problem (4.1), (4.2) or
(4.3) for two different eigenvalues λ1 and λ2 . Then they are orthogonal in the sense that
b x1 (t) x2 (t) dt = 0.
a Note that the terminology comes from the fact that the integral is a type of inner product. We
will expand on this in the next section. The theorem has a very short, elegant, and illuminating
proof so let us give it here. First note that we have the following two equations.
x1 + λ1 x1 = 0 x2 + λ2 x2 = 0. and Multiply the first by x2 and the second by x1 and subtract to get
(λ1 − λ2 ) x1 x2 = x2 x1 − x2 x1 .
Now integrate both sides of the equation.
b (λ1 − λ2 ) b x1 x2 dt =
a x2 x1 − x2 x1 dt
a
b =
a d
x x1 − x2 x1 dt
dt 2 = x2 x1 − x2 x1 b
t =a = 0. The last equality holds because of the boundary conditions. For example, if we consider (4.1) we
have x1 (a) = x1 (b) = x2 (a) = x2 (b) = 0 and so x2 x1 − x2 x1 is zero at both a and b. As λ1 λ2 , the
theorem follows.
Exercise 4.1.1 (easy): Finish the theorem (check the last equality in the proof) for the cases (4.2)
and (4.3).
We have seen previously that sin(nt) was an eigenfunction for the problem x + λ x = 0, x(0) = 0,
x(π) = 0. Hence we have the integral
π sin(mt) sin(nt) dt = 0,
0 when m n. 148 CHAPTER 4. FOURIER SERIES AND PDES Similarly π cos(mt) cos(nt) dt = 0, when m n. sin(mt) sin(nt) dt = 0, when m n, cos(mt) cos(nt) dt = 0, when m n, 0 And finally we also get
π
−π
π
−π and π
−π 4.1.4 cos(mt) sin(nt) dt = 0. Fredholm alternative We now touch on a very useful theorem in the theory of differential equations. The theorem holds
in a more general setting than we are going to state it, but for our purposes the following statement
is sufficient. We will give a slightly more general version in chapter 5.
Theorem 4.1.2 (Fredholm alternative∗ ). Exactly one of the following statements holds. Either
x + λ x = 0, x(a) = 0, x(b) = 0 (4.4) has a nonzero solution, or
x + λ x = f (t), x(a) = 0, x(b) = 0 (4.5) has a unique solution for every function f continuous on [a, b].
The theorem is also true for the other types of boundary conditions we considered. The theorem
means that if λ is not an eigenvalue, the nonhomogeneous equation (4.5) has a unique solution for
every right hand side. On the other hand if λ is an eigenvalue, then (4.5) need not have a solution
for every f , and furthermore, even if it happens to have a solution, the solution is not unique.
We also want to reinforce the idea here that linear differential operators have much in common
with matrices. So it is no surprise that there is a finite dimensional version of Fredholm alternative
for matrices as well. Let A be an n × n matrix. The Fredholm alternative then states that either
(A − λI ) x = 0 has a nontrivial solution, or (A − λI ) x = b has a solution for every b.
A lot of intuition from linear algebra can be applied for linear differential operators, but one
must be careful of course. For example, one obvious difference we have already seen is that in
general a differential operator will have infinitely many eigenvalues, while a matrix has only finitely
many.
∗ Named after the Swedish mathematician Erik Ivar Fredholm (1866 – 1927). 4.1. BOUNDARY VALUE PROBLEMS 4.1.5 149 Application Let us consider a physical application of an endpoint problem. Suppose we have a tightly stretched
quickly spinning elastic string or rope of uniform linear density ρ. Let us put this problem into the
xy-plane. The x axis represents the position on the string. The string rotates at angular velocity ω,
so we will assume that the whole xy-plane rotates at angular velocity ω. We will assume that the
string stays in this xy-plane and y will measure its deflection from the equilibrium position, y = 0,
on the x axis. Hence, we will find a graph giving the shape of the string. We will idealize the string
to have no volume to just be a mathematical curve. If we take a small segment and we look at the
tension at the endpoints, we see that this force is tangential and we will assume that the magnitude
is the same at both end points. Hence the magnitude is constant everywhere and we will call its
magnitude T . If we assume that the deflection is small, then we can use Newton’s second law to get
an equation
T y + ρω2 y = 0.
Let L be the length of the string and the string is fixed at the beginning and end points. Hence,
y(0) = 0 and y(L) = 0. See Figure 4.1.
y
y
0 L x Figure 4.1: Whirling string.
We rewrite the equation as y + ρω y = 0. The setup is similar to Example 4.1.3 on page 144,
T
except for the interval length being L instead of π. We are looking for eigenvalues of y + λy =
2
0, y(0) = 0, y(L) = 0 where λ = ρω . As before there are no nonpositive eigenvalues. With λ > 0, the
T
√
√
general solution to the equation is y = A cos( λ x) + B sin( λ x). The condition y(0) = 0 implies
√
√
that A = 0 as before. The condition y(L) = 0 implies that sin( λ L) = 0 and hence λ L = kπ for
some integer k > 0, so
ρω2
k2 π2
=λ= 2 .
T
L
What does this say about the shape of the string? It says that for all parameters ρ, ω, T not
2
22
satisfying the above equation, the string is in the equilibrium position, y = 0. When ρω = kLπ ,
2
T
then the string will “pop out” some distance B at the midpoint. We cannot compute B with the
information we have.
Let us assume that ρ and T are fixed and we are changing ω. For most values of ω the string is
√
πT
in the equilibrium state. When the angular velocity ω hits a value ω = kL √ρ , then the string will pop
2 150 CHAPTER 4. FOURIER SERIES AND PDES out and will have the shape of a sin wave crossing the x axis k times. When ω changes again, the
string returns to the equilibrium position. You can see that the higher the angular velocity the more
times it crosses the x axis when it is popped out. 4.1.6 Exercises Hint for the following exercises: Note that when λ > 0, then cos
also solutions of the homogeneous equation. √
√
λ (t − a) and sin λ (t − a) are Exercise 4.1.2: Compute all eigenvalues and eigenfunctions of x + λ x = 0, x(a) = 0, x(b) = 0
(assume a < b).
Exercise 4.1.3: Compute all eigenvalues and eigenfunctions of x + λ x = 0, x (a) = 0, x (b) = 0
(assume a < b).
Exercise 4.1.4: Compute all eigenvalues and eigenfunctions of x + λ x = 0, x (a) = 0, x(b) = 0
(assume a < b).
Exercise 4.1.5: Compute all eigenvalues and eigenfunctions of x + λ x = 0, x(a) = x(b), x (a) =
x (b) (assume a < b).
Exercise 4.1.6: We have skipped the case of λ < 0 for the boundary value problem x + λ x =
0, x(−π) = x(π), x (−π) = x (π). Finish the calculation and show that there are no negative
eigenvalues. 4.2. THE TRIGONOMETRIC SERIES 4.2 151 The trigonometric series Note: 2 lectures, §9.1 in [EP] 4.2.1 Periodic functions and motivation As motivation for studying Fourier series, suppose we have the problem
x + ω2 x = f (t),
0 (4.6) for some periodic function f (t). We have already solved
x + ω2 x = F0 cos(ωt).
0 (4.7) One way to solve (4.6) is to decompose f (t) as a sum of cosines (and sines) and then solve many
problems of the form (4.7). We then use the principle of superposition, to sum up all the solutions
we got to get a solution to (4.6).
Before we proceed, let us talk a little bit more in detail about periodic functions. A function
is said to be periodic with period P if f (t) = f (t + P) for all t. For brevity we will say f (t) is
P-periodic. Note that a P-periodic function is also 2P-periodic, 3P-periodic and so on. For example,
cos(t) and sin(t) are 2π-periodic. So are cos(kt) and sin(kt) for all integers k. The constant functions
are an extreme example. They are periodic for any period (exercise).
Normally we will start with a function f (t) defined on some interval [−L, L] and we will want
to extend periodically to make it a 2L-periodic function. We do this extension by defining a new
function F (t) such that for t in [−L, L], F (t) = f (t). For t in [L, 3L], we define F (t) = f (t − 2L), for
t in [−3L, −L], F (t) = f (t + 2L), and so on. We assumed that f (−L) = f (L). We could have also
started with f defined only on the half-open interval (−L, L] and then define f (−L) = f (L).
Example 4.2.1: Define f (t) = 1 − t2 on [−1, 1]. Now extend periodically to a 2-periodic function.
See Figure 4.2 on the following page.
You should be careful to distinguish between f (t) and its extension. A common mistake is to
assume that a formula for f (t) holds for its extension. It can be confusing when the formula for f (t)
is periodic, but with perhaps a different period.
Exercise 4.2.1: Define f (t) = cos t on [−π/2, π/2]. Now take the π-periodic extension and sketch its
graph. How does it compare to the graph of cos t. 4.2.2 Inner product and eigenvector decomposition Suppose we have a symmetric matrix, that is AT = A. We have said before that the eigenvectors of A
are then orthogonal. Here the word orthogonal means that if v and w are two distinct eigenvectors 152 CHAPTER 4. FOURIER SERIES AND PDES
-3 -2 -1 0 1 2 3 1.5 1.5 1.0 1.0 0.5 0.5 0.0 0.0 -0.5 -0.5
-3 -2 -1 0 1 2 3 Figure 4.2: Periodic extension of the function 1 − t2 . of A, then v, w = 0. In this case the inner product v, w is the dot product, which can be computed
as vT w.
To decompose a vector v in terms of mutually orthogonal vectors w1 and w2 we write
v = a1 w1 + a2 w2 .
Let us find the formula for a1 and a2 . First let us compute
v, w1 = a1 w1 + a2 w2 , w1 = a1 w1 , w1 + a2 w2 , w1 = a1 w1 , w1 .
Therefore,
a1 = v, w1
.
w1 , w1 Similarly v, w2
.
w2 , w2
You probably remember this formula from vector calculus.
a2 = 1
Example 4.2.2: Write v = 2 as a linear combination of w1 = −1 and w2 = 1 .
3
1
First note that w1 and w2 are orthogonal as w1 , w2 = 1(1) + (−1)1 = 0. Then 2(1) + 3(−1)
−1
v, w1
=
=
,
1(1) + (−1)(−1)
2
w1 , w1
v, w2
2+3 5
=
a2 =
=.
1+1 2
w2 , w2 a1 = Hence −1 1
51
2
=
+
.
3
2 −1
21 4.2. THE TRIGONOMETRIC SERIES 4.2.3 153 The trigonometric series Instead of decomposing a vector in terms of the eigenvectors of a matrix, we will decompose a
function in terms of eigenfunctions of a certain eigenvalue problem. The eigenvalue problem we
will use for the Fourier series is
x + λ x = 0, x(−π) = x(π), x (−π) = x (π). We have previously computed that the eigenfunctions are 1, cos(kt), sin(kt). That is, we will want to
find a representation of a 2π-periodic function f (t) as
a0
f (t) =
+
2 ∞ an cos(nt) + bn sin(nt).
n=1 This series is called the Fourier series† or the trigonometric series for f (t). We write the coefficient
of the eigenfunction 1 as a20 for convenience. We could also think of 1 = cos(0t), so that we only
need to look at cos(kt) and sin(kt).
As for matrices we will want to find a projection of f (t) onto the subspace generated by the
eigenfunctions. So we will want to define an inner product of functions. For example, to find an we
want to compute f (t) , cos(nt) . We define the inner product as
def f (t) , g(t) = π f (t) g(t) dt.
−π With this definition of the inner product, we have seen in the previous section that the eigenfunctions
cos(kt) (including the constant eigenfunction), and sin(kt) are orthogonal in the sense that
cos(mt) , cos(nt) = 0
sin(mt) , sin(nt) = 0
sin(mt) , cos(nt) = 0 for m n,
for m n,
for all m and n. By elementary calculus for n = 1, 2, 3, . . . we have cos(nt) , cos(nt) = π and sin(nt) , sin(nt) =
π. For the constant we get that 1 , 1 = 2π. The coefficients are given by
f (t) , cos(nt)
1
an =
=
cos(nt) , cos(nt)
π
f (t) , sin(nt)
1
bn =
=
sin(nt) , sin(nt)
π π f (t) cos(nt) dt,
−π
π f (t) sin(nt) dt.
−π Compare these expressions with the finite-dimensional example. For a0 we get a similar formula
a0 = 2
† f (t) , 1
1
=
1, 1
π π f (t) dt.
−π Named after the French mathematician Jean Baptiste Joseph Fourier (1768 – 1830). 154 CHAPTER 4. FOURIER SERIES AND PDES Let us check the formulas using the orthogonality properties. Suppose for a moment that
a0
f (t) =
+
2 ∞ an cos(nt) + bn sin(nt).
n=1 Then for m ≥ 1 we have
a0
f (t) , cos(mt) =
+
2
= ∞ an cos(nt) + bn sin(nt) , cos(mt)
n=1 a0
1 , cos(mt) +
2 ∞ an cos(nt) , cos(mt) + bn sin(nt) , cos(mt)
n=1 = am cos(mt) , cos(mt) .
And hence am = f (t) , cos(mt)
cos(mt) , cos(mt) . Exercise 4.2.2: Carry out the calculation for a0 and bm .
Example 4.2.3: Take the function
f (t) = t
for t in (−π, π]. Extend f (t) periodically and write it as a Fourier series. This function is called the
sawtooth.
-5.0 -2.5 0.0 2.5 5.0 3 3 2 2 1 1 0 0 -1 -1 -2 -2 -3 -3
-5.0 -2.5 0.0 2.5 5.0 Figure 4.3: The graph of the sawtooth function.
The plot of the extended periodic function is given in Figure 4.3. Let us compute the coefficients.
We start with a0 ,
1π
a0 =
t dt = 0.
π −π 4.2. THE TRIGONOMETRIC SERIES 155 We will often use the result from calculus that says that the integral of an odd function over a
symmetric interval is zero. Recall that an odd function is a function ϕ(t) such that ϕ(−t) = −ϕ(t).
For example the functions t, sin t, or (importantly for us) t cos(nt) are all odd functions. Thus
an = 1
π π
−π t cos(nt) dt = 0. Let us move to bn . Another useful fact from calculus is that the integral of an even function over a
symmetric interval is twice the integral of the same function over half the interval. Recall an even
function is a function ϕ(t) such that ϕ(−t) = ϕ(t). For example t sin(nt) is even.
bn =
=
=
=
=
We have used the fact that 1π
t sin(nt) dt
π −π
2π
t sin(nt) dt
π0
π
2 −t cos(nt)
1π
+
cos(nt) dt
π
n
n0
t =0
2 −π cos(nπ)
+0
π
n
−2 cos(nπ) 2 (−1)n+1
=
.
n
n 1 if n even, cos(nπ) = (−1) = −1 if n odd. n The series, therefore, is
∞
n=1 2 (−1)n+1
sin(nt).
n Let us write out the first 3 harmonics of the series for f (t).
2 sin(t) − sin(2t) + 2
sin(3t) + · · ·
3 The plot of these first three terms of the series, along with a plot of the first 20 terms is given
in Figure 4.4 on the following page.
Example 4.2.4: Take the function 0 f (t) = π if −π < t ≤ 0,
if 0 < t ≤ π. 156 CHAPTER 4. FOURIER SERIES AND PDES
-5.0 -2.5 0.0 2.5 5.0 -5.0 -2.5 0.0 2.5 5.0 3 3 3 3 2 2 2 2 1 1 1 1 0 0 0 0 -1 -1 -1 -1 -2 -2 -2 -2 -3 -3 -3 -3 -5.0 -2.5 0.0 2.5 5.0 -5.0 -2.5 0.0 2.5 5.0 Figure 4.4: First 3 (left graph) and 20 (right graph) harmonics of the sawtooth function.
-5.0 -2.5 0.0 2.5 5.0 3 3 2 2 1 1 0 0 -5.0 -2.5 0.0 2.5 5.0 Figure 4.5: The graph of the square wave function. Extend f (t) periodically and write it as a Fourier series. This function or its variants appear often in
applications and the function is called the square wave.
The plot of the extended periodic function is given in Figure 4.5. Now we compute the
coefficients. Let us start with a0
a0 =
an = 1
π 1
π π
−π f (t) dt = π
−π f (t) cos(nt) dt = 1
π
1
π π π dt = π.
0 π π cos(nt) dt = 0.
0 4.2. THE TRIGONOMETRIC SERIES 157 And finally
1π
f (t) sin(nt) dt
π −π
1π
=
π sin(nt) dt
π0
π
− cos(nt)
=
n
t =0 bn = 1 − cos(πn) 1 − (−1)n 2 =
=
= n
0 n
n if n is odd,
if n is even. The Fourier series is
π
+
2 ∞
n=1
n odd 2
π
sin(nt) = +
n
2 ∞ 2
sin (2k − 1) t .
2k − 1 k =1 Let us write out the first 3 harmonics of the series for f (t).
2
π
+ 2 sin(t) + sin(3t) + · · ·
2
3
The plot of these first three and also of the first 20 terms of the series is given in Figure 4.6.
-5.0 -2.5 0.0 2.5 5.0 -5.0 -2.5 0.0 2.5 5.0 3 3 3 3 2 2 2 2 1 1 1 1 0 0 0 0 -5.0 -2.5 0.0 2.5 5.0 -5.0 -2.5 0.0 2.5 5.0 Figure 4.6: First 3 (left graph) and 20 (right graph) harmonics of the square wave function. We have so far skirted the issue of convergence. For example, if f (t) is the square wave function,
the equation
∞
π
2
f (t) = +
sin (2k − 1) t .
2 k=1 2k − 1 158 CHAPTER 4. FOURIER SERIES AND PDES is only an equality for such t where f (t) is continuous. That is, we do not get an equality for
t = −π, 0, π and all the other discontinuities of f (t). It is not hard to see that when t is an integer
multiple of π (which includes all the discontinuities), then
π
+
2 ∞
k =1 2
π
sin (2k − 1) t = .
2k − 1
2 We redefine f (t) on [−π, π] as 0 f (t) = π π /2 if −π < t < 0,
if 0 < t < π,
if t = −π, t = 0, or t = π, and extend periodically. The series equals this extended f (t) everywhere, including the discontinuities. We will generally not worry about changing the function values at several (finitely many)
points.
We will say more about convergence in the next section. Let us however mention briefly an
effect of the discontinuity. Let us zoom in near the discontinuity in the square wave. Further, let
us plot the first 100 harmonics, see Figure 4.7. You will notice that while the series is a very good
approximation away from the discontinuities, the error (the overshoot) near the discontinuity at
t = π does not seem to be getting any smaller. This behavior is known as the Gibbs phenomenon.
The region where the error is large does get smaller, however, the more terms in the series you take.
1.75 2.00 2.25 2.50 2.75 3.00 3.25 3.50 3.50 3.25 3.25 3.00 3.00 2.75 2.75 1.75 2.00 2.25 2.50 2.75 3.00 3.25 Figure 4.7: Gibbs phenomenon in action. We can think of a periodic function as a “signal” being a superposition of many signals of pure
frequency. For example, we could think of the square wave as a tone of certain base frequency. It
will be, in fact, a superposition of many different pure tones of frequencies that are multiples of the 4.2. THE TRIGONOMETRIC SERIES 159 base frequency. On the other hand a simple sine wave is only the pure tone. The simplest way to
make sound using a computer is the square wave, and the sound will be a very different from nice
pure tones. If you have played video games from the 1980s or so you have heard what square waves
sound like. 4.2.4 Exercises Exercise 4.2.3: Suppose f (t) is defined on [−π, π] as sin(5t) + cos(3t). Extend periodically and
compute the Fourier series of f (t).
Exercise 4.2.4: Suppose f (t) is defined on [−π, π] as |t|. Extend periodically and compute the
Fourier series of f (t).
Exercise 4.2.5: Suppose f (t) is defined on [−π, π] as |t|3 . Extend periodically and compute the
Fourier series of f (t).
Exercise 4.2.6: Suppose f (t) is defined on (−π, π] as −1 if −π < t ≤ 0, f (t) = 1 if 0 < t ≤ π.
Extend periodically and compute the Fourier series of f (t).
Exercise 4.2.7: Suppose f (t) is defined on (−π, π] as t3 . Extend periodically and compute the
Fourier series of f (t).
Exercise 4.2.8: Suppose f (t) is defined on [−π, π] as t2 . Extend periodically and compute the
Fourier series of f (t).
There is another form of the Fourier series using complex exponentials that is sometimes easier
to work with.
Exercise 4.2.9: Let
a0
f (t) =
+
2 ∞ an cos(nt) + bn sin(nt).
n=1 Use Euler’s formula eiθ = cos(θ) + i sin(θ) to show that there exist complex numbers cm such that
∞ f (t) = cm eimt .
m=−∞ Note that the sum now ranges over all the integers including negative ones. Do not worry about
convergence in this calculation. Hint: It may be better to start from the complex exponential form
and write the series as
∞
c0 + cm eimt + c−m e−imt .
m=1 160 4.3 CHAPTER 4. FOURIER SERIES AND PDES More on the Fourier series Note: 2 lectures, §9.2 – §9.3 in [EP]
Before reading the lecture, it may be good to first try Project IV (Fourier series) from the
IODE website:. After reading the lecture it may be good to
continue with Project V (Fourier series again). 4.3.1 2L-periodic functions We have computed the Fourier series for a 2π-periodic function, but what about functions of different
periods. Well, fear not, the computation is a simple case of change of variables. We can just rescale
the independent axis. Suppose that you have the 2L-periodic function f (t) (L is called the half
π
period). Let s = L t, then the function
g( s) = f L
s
π is 2π-periodic. We want to also rescale all our sines and cosines. We want to write
f (t) = a0
+
2 ∞ an cos
n=1 nπ
nπ
t + bn sin
t.
L
L If we change variables to s we see that
a0
g( s) =
+
2 ∞ an cos(ns) + bn sin(ns).
n=1 We can compute an and bn as before. After we write down the integrals we change variables back to
t.
1π
1L
a0 =
g( s) ds =
f (t) dt,
π −π
L −L
1π
1L
nπ
an =
g( s) cos(ns) ds =
f (t) cos
t d t,
π −π
L −L
L
1π
1L
nπ
bn =
g( s) sin(ns) ds =
f (t) sin
t d t.
π −π
L −L
L
The two most common half periods that show up in examples are π and 1 because of the
simplicity. We should stress that we have done no new mathematics, we have only changed
variables. If you understand the Fourier series for 2π-periodic functions, you understand it for 2Lperiodic functions. All that we are doing is moving some constants around, but all the mathematics
is the same. 4.3. MORE ON THE FOURIER SERIES 161 Example 4.3.1: Let
f (t) = |t| for −1 < t ≤ 1, extended periodically. The plot of the periodic extension is given in Figure 4.8. Compute the Fourier
series of f (t).
-2 -1 0 1 2 1.00 1.00 0.75 0.75 0.50 0.50 0.25 0.25 0.00 0.00 -2 -1 0 1 2 Figure 4.8: Periodic extension of the function f (t).
We want to write f (t) =
is even and hence a0
2 + ∞
n=1 an cos(nπt) + bn sin(nπt). For n ≥ 1 we note that |t| cos(nπt) 1 an = f (t) cos(nπt) dt
−1
1 =2 t cos(nπt) dt
0 t
sin(nπt)
=2
nπ 1 1
t =0 −2 1
= 0 + 2 2 cos(nπt)
nπ 0
1
t =0 1
sin(nπt) dt
nπ 0 2 (−1)n − 1 =
= −4 2 π2
22
n
nπ Next we find a0 if n is even,
if n is odd. 1 a0 = |t| dt = 1.
−1 You should be able to find this integral by thinking about the integral as the area under the graph
without doing any computation at all. Finally we can find bn . Here, we notice that |t| sin(nπt) is odd
and, therefore,
1 bn = f (t) sin(nπt) dt = 0.
−1 162 CHAPTER 4. FOURIER SERIES AND PDES Hence, the series is
1
+
2 ∞
n=1
n odd −4
cos(nπt).
n2 π2 Let us explicitly write down the first few terms of the series up to the 3rd harmonic.
4
14
− 2 cos(πt) − 2 cos(3πt) − · · ·
2π
9π
The plot of these few terms and also a plot up to the 20th harmonic is given in Figure 4.9. You
should notice how close the graph is to the real function. You should also notice that there is no
“Gibbs phenomenon” present as there are no discontinuities.
-2 -1 0 1 2 -2 -1 0 1 2 1.00 1.00 1.00 1.00 0.75 0.75 0.75 0.75 0.50 0.50 0.50 0.50 0.25 0.25 0.25 0.25 0.00 0.00 0.00 0.00 -2 -1 0 1 2 -2 -1 0 1 2 Figure 4.9: Fourier series of f (t) up to the 3rd harmonic (left graph) and up to the 20th harmonic
(right graph). 4.3.2 Convergence We will need the one sided limits of functions. We will use the following notation
f (c−) = lim f (t),
t↑c and f (c+) = lim f (t).
t↓c If you are unfamiliar with this notation, limt↑c f (t) means we are taking a limit of f (t) as t approaches
c from below (i.e. t < c) and limt↓c f (t) means we are taking a limit of f (t) as t approaches c from
above (i.e. t > c). For example, for the square wave function 0 if −π < t ≤ 0, f (t) = (4.8)
π if 0 < t ≤ π, 4.3. MORE ON THE FOURIER SERIES 163 we have f (0−) = 0 and f (0+) = π.
Let f (t) be a function defined on an interval [a, b]. Suppose that we find finitely many points
a = t0 , t1 , t2 , . . . , tk = b in the interval, such that f (t) is continuous on the intervals (t0 , t1 ), (t1 , t2 ),
. . . , (tk−1 , tk ). Also suppose that all the one sided limits exist, that is, all of f (t0 +), f (t1 −), f (t1 +),
f (t2 −), f (t2 +), . . . , f (tk −) exist and are finite. Then we say f (t) is piecewise continuous.
If moreover, f (t) is differentiable at all but finitely many points, and f (t) is piecewise continuous,
then f (t) is said to be piecewise smooth.
Example 4.3.2: The square wave function (4.8) is piecewise smooth on [−π, π] or any other interval.
In such a case we simply say that the function is piecewise smooth.
Example 4.3.3: The function f (t) = |t| is piecewise smooth.
Example 4.3.4: The function f (t) = 1 is not piecewise smooth on [−1, 1] (or any other interval
t
containing zero). In fact, it is not even piecewise continuous.
√
Example 4.3.5: The function f (t) = 3 t is not piecewise smooth on [−1,
a0
+
2 ∞ an cos
n=1 nπ
nπ
t + bn sin
t
L
L be the Fourier series for f (t). Then the series converges for all t. If f (t) is continuous near t, then
f (t) =
Otherwise a0
+
2 ∞ an cos
n=1 f (t−) + f (t+) a0
=
+
2
2 nπ
nπ
t + bn sin
t.
L
L ∞ an cos
n=1 nπ
nπ
t + bn sin
t.
L
L If we happen to have that f (t) = f (t−)+ f (t+) at all the discontinuities, the Fourier series converges
2
to f (t) everywhere. We can always just redefine f (t) by changing the value at each discontinuity
appropriately. Then we can write an equals sign between f (t) and the series without any worry. We
mentioned this fact briefly at the end last section.
Note that the theorem does not say how fast the series converges. Think back the discussion of
the Gibbs phenomenon in last section. The closer you get to the discontinuity, the more terms you
need to take to get an accurate approximation to the function. 164 4.3.3 CHAPTER 4. FOURIER SERIES AND PDES Differentiation and integration of Fourier series Not only does Fourier series converge nicely, but it is easy to differentiate and integrate the series.
We can do this just by differentiating or integrating term by term.
Theorem 4.3.2. Suppose
a0
+
f (t) =
2 ∞ an cos
n=1 nπ
nπ
t + bn sin
t,
L
L is a piecewise smooth continuous function and the derivative f (t) is piecewise smooth. Then the
derivative can be obtained by differentiating term by term.
∞ f (t) =
n=1 nπ
nπ
−an nπ
bn nπ
sin
t+
cos
t.
L
L
L
L It is important that the function is continuous. It can have corners, but no jumps. Otherwise the
differentiated series will fail to converge. For an exercise, take the series obtained for the square
wave and try to differentiate the series. Similarly, we can also integrate a Fourier series.
Theorem 4.3.3. Suppose
f (t) = a0
+
2 ∞ an cos
n=1 nπ
nπ
t + bn sin
t,
L
L is a piecewise smooth function. Then the antiderivative is obtained by antidifferentiating term by
term and so
∞
a0 t
an L
nπ
−bn L
nπ
F (t) =
+C +
sin
t+
cos
t.
2
nπ
L
nπ
L
n=1
where F (t) = f (t) and C is an arbitrary constant.
0
Note that the series for F (t) is no longer a Fourier series as it contains the a2 t term. The
antiderivative of a periodic function need no longer be periodic and so we should not expect a
Fourier series. 4.3.4 Rates of convergence and smoothness Let us do an example of a periodic function with one derivative everywhere.
Example 4.3.6: Take the function (t + 1) t f (t) = (1 − t) t if −1 < t ≤ 0,
if 0 < t ≤ 1, and extend to a 2-periodic function. The plot is given in Figure 4.10 on the facing page.
Note that this function has one derivative everywhere, but it does not have a second derivative
derivative whenever t is an integer. 4.3. MORE ON THE FOURIER SERIES
-2 165 -1 0 1 2 0.50 0.50 0.25 0.25 0.00 0.00 -0.25 -0.25 -0.50 -0.50
-2 -1 0 1 2 Figure 4.10: Smooth 2-periodic function. Exercise 4.3.1: Compute f (0+) and f (0−).
Let us compute the Fourier series coefficients. The actual computation involves several integration by parts and is left to student.
1 a0 = 0 f (t) dt =
−1
1 1 (t + 1) t dt +
−1
0 f (t) cos(nπt) dt = an = (1 − t) t dt = 0,
0 −1
1 1 (t + 1) t cos(nπt) dt +
−1
0 (1 − t) t cos(nπt) dt = 0
0
1 bn = f (t) sin(nπt) dt =
(t + 1) t sin(nπt) dt +
−1 4(1 − (−1)n ) π38n3 if n is odd, =
=
0 π3 n3
if n is even.
−1 That is, the series is ∞
n=1
n odd 8
π3 n3 (1 − t) t sin(nπt) dt
0 sin(nπt). This series converges very fast. If you plot up to the third harmonic, that is the function
8
8
sin(πt) +
sin(3πt),
3
π
27π3
it is almost indistinguishable from the plot of f (t) in Figure 4.10. In fact, the coefficient 278π3 is
already just 0.0096 (approximately). The reason for this behavior is the n3 term in the denominator.
The coefficients bn in this case go to zero as fast as n13 goes to zero. 166 CHAPTER 4. FOURIER SERIES AND PDES It is a general fact that if you have one derivative, the Fourier coefficients will go to zero
approximately like n13 . If you have only a continuous function, then the Fourier coefficients will go
to zero as n12 . If you have discontinuities, then the Fourier coefficients will go to zero approximately
as 1 . Therefore, we can tell a lot about the smoothness of a function by looking at its Fourier
n
coefficients.
To justify this behavior take for example the function defined by the Fourier series
∞ f (t) =
n=1 1
sin(nt).
n3 When we differentiate term by term we notice
∞ f (t) =
n=1 1
cos(nt).
n2 Therefore, the coefficients now go down like n12 , which we said means that we have a continuous
function. The derivative of f (t) is defined at most points, but there are points where f (t) is not
differentiable. It has corners, but no jumps. If we differentiate again (where we can) we find that the
function f (t), now fails to be continuous (has jumps)
∞ f (t ) =
n=1 −1
sin(nt).
n This function is similar to the sawtooth. If we tried to dierentiate again we would obtain
∞ − cos(nt),
n =1 which does not converge!
Exercise 4.3.2: Use a computer to plot f (t), f (t) and f (t). That is, plot say the first 5 harmonics
of the functions. At what points does f (t) have the discontinuities. 4.3.5 Exercises Exercise 4.3.3: Let 0 if −1 < t ≤ 0, f (t) = t if 0 < t ≤ 1, extended periodically. a) Compute the Fourier series for f (t). b) Write out the series explicitly up to
the 3rd harmonic. 4.3. MORE ON THE FOURIER SERIES
Exercise 4.3.4: Let 167 −t f (t) = 2
t if −1 < t ≤ 0,
if 0 < t ≤ 1, extended periodically. a) Compute the Fourier series for f (t). b) Write out the series explicitly up to
the 3rd harmonic.
Exercise 4.3.5: Let −t f (t) = 10
t 10 if −10 < t ≤ 0,
if
0 < t ≤ 10, extended periodically (period is 20). a) Compute the Fourier series for f (t). b) Write out the series
explicitly up to the 3rd harmonic.
Exercise 4.3.6: Let f (t) = ∞ 1 n13 cos(nt). Is f (t) continuous and differentiable everywhere? Find
n=
the derivative (if it exists everywhere) or justify why f (t) is not differentiable everywhere.
n 1)
Exercise 4.3.7: Let f (t) = ∞ 1 (−n sin(nt). Is f (t) differentiable everywhere? Find the derivative
n=
(if it exists everywhere) or justify why f (t) is not differentiable everywhere. Exercise 4.3.8: Let 0 if −2 < t ≤ 0, f (t) = t
if 0 < t ≤ 1, −t + 2 if 1 < t ≤ 2, extended periodically. a) Compute the Fourier series for f (t). b) Write out the series explicitly up to
the 3rd harmonic.
Exercise 4.3.9: Let
f (t) = et for −1 < t < 1 extended periodically. a) Compute the Fourier series for f (t). b) Write out the series explicitly up to
the 3rd harmonic. c) What does the series converge to at t = 1. 168 4.4 CHAPTER 4. FOURIER SERIES AND PDES Sine and cosine series Note: 2 lectures, §9.3 in [EP] 4.4.1 Odd and even periodic functions You may have noticed by now that an odd function has no cosine terms in the Fourier series and an
even function has no sine terms in the Fourier series. This observation is not a coincidence. Let us
look at even and odd periodic function in more detail.
Recall that a function f (t) is odd if f (−t) = − f (t). A function f (t) is even if f (−t) = f (t). For
example, cos(nt) is even and sin(nt) is odd. Similarly the function tk is even if k is even and odd
when k is odd.
Exercise 4.4.1: Take two functions f (t) and g(t) and define their product h(t) = f (t)g(t). a) Suppose
both are odd, is h(t) odd or even? b) Suppose one is even and one is odd, is h(t) odd or even? c)
Suppose both are even, is h(t) odd or even?
If f (t) and g(t) are both odd, then f (t) + g(t) is odd. Similarly for even functions. On the other
hand, if f (t) is odd and g(t) even, then we cannot say anything about the sum f (t) + g(t). In fact, the
Fourier series of any function is a sum of an odd (the sine terms) and an even (the cosine terms)
function.
In this section we are interested in odd and even periodic functions. We have previously defined
the 2L-periodic extension of a function defined on the interval [−L, L]. Sometimes we are only
interested in the function on the range [0, L] and it would be convenient to have an odd (resp. even)
function. If the function is odd (resp. even), all the cosine (resp. sine) terms will disappear. What
we will do is take the odd (resp. even) extension of the function to [−L, L] and then we extend
periodically to a 2L-periodic function.
Take a function f (t) defined on [0, L]. On (−L, L] define the functions if 0 ≤ t ≤ L, def f (t)
Fodd (t) = − f (−t) if −L < t < 0, if 0 ≤ t ≤ L, def f (t)
Feven (t) = f (−t) if −L < t < 0. Extend Fodd (t) and Feven (t) to be 2L-periodic. Then Fodd (t) is called the odd periodic extension of
f (t), and Feven (t) is called the even periodic extension of f (t).
Exercise 4.4.2: Check that Fodd (t) is odd and that Feven (t) is even.
Example 4.4.1: Take the function f (t) = t (1 − t) defined on [0, 1]. Figure 4.11 on the facing page
shows the plots of the odd and even extensions of f (t). 4.4. SINE AND COSINE SERIES
-2 -1 0 169 1 2 -2 -1 0 1 2 0.3 0.3 0.3 0.3 0.2 0.2 0.2 0.2 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 -0.1 -0.1 -0.1 -0.1 -0.2 -0.2 -0.2 -0.2 -0.3 -0.3 -0.3
-2 -1 0 1 2 -0.3
-2 -1 0 1 2 Figure 4.11: Odd and even 2-periodic extension of f (t) = t (1 − t), 0 ≤ t ≤ 1. 4.4.2 Sine and cosine series Let f (t) be an odd 2L-periodic function. We write the Fourier series for f (t). We compute the
coefficients an (including n = 0) and get
1
an =
L L f (t) cos
−L nπ
t d t = 0.
L That is, there are no cosine terms in the Fourier series of an odd function. The integral is zero
because f (t) cos (nπL t) is an odd function (product of an odd and an even function is odd) and the
integral of an odd function over a symmetric interval is always zero. Furthermore, the integral of an
even function over a symmetric interval [−L, L] is twice the integral of the function over the interval
π
[0, L]. The function f (t) sin nL t is the product of two odd functions and hence even.
bn = 1
L L f (t) sin
−L nπ
2
t dt =
L
L L f (t) sin
0 nπ
t d t.
L We can now write the Fourier series of f (t) as
∞ bn sin
n=1 nπ
t.
L Similarly, if f (t) is an even 2L-periodic function. For the same exact reasons as above, we find
that bn = 0 and
2L
nπ
an =
f (t) cos
t d t.
L0
L 170 CHAPTER 4. FOURIER SERIES AND PDES The formula still works for n = 0 in which case it becomes
L 2
a0 =
L
The Fourier series is then
a0
+
2 f (t) dt.
0 ∞ an cos
n=1 nπ
t.
L An interesting consequence is that the coefficients of the Fourier series of an odd (or even)
function can be computed by just integrating over the half interval [0, L]. Therefore, we can compute
the Fourier series of the odd (or even) extension of a function by computing certain integrals over
the interval where the original function is defined.
Theorem 4.4.1. Let f (t) be a piecewise smooth function defined on [0, L]. Then the odd extension
of f (t) has the Fourier series
∞ Fodd (t) = bn sin
n=1 nπ
t,
L where
2
bn =
L L f (t) sin
0 nπ
t d t.
L The even extension of f (t) has the Fourier series
a0
Feven (t) =
+
2 ∞ an cos
n=1 nπ
t,
L where
an = 2
L L f (t) cos
0 nπ
t d t.
L π
π
The series ∞ 1 bn sin nL t is called the sine series of f (t) and the series a20 + ∞ 1 an cos nL t
n=
n=
is called the cosine series of f (t). It is often the case that we do not actually care what happens
outside of [0, L]. In this case, we can pick whichever series fits our problem better.
It is not necessary to start with the full Fourier series to obtain the sine and cosine series. The
sine series is really the eigenfunction expansion of f (t) using the eigenfunctions of the eigenvalue
problem x + λ x = 0, x(0) = 0, x(L) = L. The cosine series is the eigenfunction expansion of f (t)
using the eigenfunctions of the eigenvalue problem x + λ x = 0, x (0) = 0, x (L) = L. We could
have, therefore, have gotten the same formulas by defining the inner product
L f (t), g(t) = f (t)g(t) dt,
0 4.4. SINE AND COSINE SERIES 171 and following the procedure of § 4.2. This point of view is useful because many times we use a
specific series because our underlying question will lead to a certain eigenvalue problem. If the
eigenvalue value problem is not one of the three we covered so far, you can still do an eigenfunction expansion, generalizing the results of this chapter. We will deal with such a generalization
in chapter 5.
Example 4.4.2: Find the Fourier series of the even periodic extension of the function f (t) = t2 for
0 ≤ t ≤ π.
We want to write
∞
a0
an cos(nt),
f (t) =
+
2 n=1
where
a0 = 2
π π t2 dt =
0 2π2
,
3 and
π π
2 π2
4
2 21
an =
t cos(nt) dt =
t sin(nt) −
t sin(nt) dt
π0
πn
nπ 0
0
π
π
4
4(−1)n
4
cos(nt) dt =
.
= 2 t cos(nt) + 2
0
nπ
nπ 0
n2 Note that we have detected the “continuity” of the extension since the coefficients decay as n12 . That
is, the even extension of t2 has no jump discontinuities. It will have corners, since the derivative
(which will be an odd function and a sine series) will have a series whose coefficients decay only as
1
so the derivative will have jumps.
n
Explicitly, the first few terms of the series are
π2
4
− 4 cos(t) + cos(2t) − cos(3t) + · · ·
3
9
Exercise 4.4.3: a) Compute the derivative of the even extension of f (t) above and verify it has jump
discontinuities. Use the actual definition of f (t), not its cosine series! b) Why is it that the derivative
of the even extension of f (t) is the odd extension of f (t). 4.4.3 Application We said that Fourier series ties in to the boundary value problems we studied earlier. Let us see this
connection in more detail.
Suppose we have the boundary value problem for 0 < t < L,
x (t) + λ x(t) = f (t), 172 CHAPTER 4. FOURIER SERIES AND PDES for the Dirichlet boundary conditions x(0) = 0, x(L) = 0. By using the Fredholm alternative
( Theorem 4.1.2 on page 148) we note that as long as λ is not an eigenvalue of the underlying
homogeneous problem, there will exist a unique solution. Note that the eigenfunctions of this
π
eigenvalue problem were the functions sin nL t . Therefore, to find the solution, we first find the
Fourier sine series for f (t). We write x also as a sine series, but with unknown coefficients. We
substitute the series for x into the equation and solve for the unknown coefficients.
If we have the Neumann boundary conditions x (0) = 0, x (L) = 0, we do the same procedure
using the cosine series. These methods are best seen by examples.
Example 4.4.3: Take the boundary value problem for 0 < t < 1,
x (t) + 2 x(t) = f (t),
where f (t) = t on 0 < t < 1, and satisfying the Dirichlet boundary conditions x(0) = 0, x(1) = 0.
We write f (t) as a sine series
∞ f (t) = cn sin(nπt),
n=1 where 1 cn = 2 t sin(nπt) dt =
0 2 (−1)n+1
.
nπ We write x(t) as
∞ x(t) = bn sin(nπt).
n=1 We plug in to obtain
∞ x (t) + 2 x(t) = ∞ −bn n2 π2 sin(nπt) + 2
n=1
∞ = bn sin(nπt)
n=1 bn (2 − n2 π2 ) sin(nπt)
n=1
∞ = f (t) =
n=1 2 (−1)n+1
sin(nπt).
nπ Therefore,
bn (2 − n2 π2 ) =
or
bn = 2 (−1)n+1
nπ 2 (−1)n+1
.
nπ(2 − n2 π2 ) 4.4. SINE AND COSINE SERIES 173 We have thus obtained a Fourier series for the solution
∞ x(t) =
n=1 2 (−1)n+1
sin(nπt).
nπ (2 − n2 π2 ) Example 4.4.4: Similarly we handle the Neumann conditions. Take the boundary value problem
for 0 < t < 1,
x (t) + 2 x(t) = f (t),
where again f (t) = t on 0 < t < 1, but now satisfying the Neumann boundary conditions x (0) = 0,
x (1) = 0. We write f (t) as a cosine series
f (t) = c0
+
2 ∞ cn cos(nπt),
n=1 where 1 c0 = 2 t dt = 1,
0 and
1 cn = 2
0 −4 2 (−1)n − 1
22
t cos(nπt) dt =
= π n
0
2 n2 π if n odd,
if n even. We write x(t) as a cosine series
a0
+
x(t) =
2 ∞ an cos(nπt).
n=1 We plug in to obtain
∞ x (t) + 2 x(t) = ∞ −an n π cos(nπt) + a0 + 2 an cos(nπt) 22 n=1 n=1
∞ = a0 + an (2 − n2 π2 ) cos(nπt)
n=1 1
= f (t) = +
2 ∞
n=1
n odd −4
cos(nπt).
π2 n2 1
Therefore, a0 = 2 , an = 0 for n even (n ≥ 2) and for n odd we have an (2 − n2 π2 ) = −4
,
π2 n2 174 CHAPTER 4. FOURIER SERIES AND PDES or −4
.
− n2 π2 )
We have thus obtained a Fourier series for the solution
an = x(t) = 4.4.4 1
+
4 ∞
n=1
n odd n2 π2 (2 −4
cos(nπt).
n2 π2 (2 − n2 π2 ) Exercises Exercise 4.4.4: Take f (t) = (t − 1)2 defined on 0 ≤ t ≤ 1. a) Sketch the plot of the even periodic
extension of f . b) Sketch the plot of the odd periodic extension of f .
Exercise 4.4.5: Find the Fourier series of both the odd and even periodic extension of the function
f (t) = (t − 1)2 for 0 ≤ t ≤ 1. Can you tell which extension is continuous from the Fourier series
coefficients?
Exercise 4.4.6: Find the Fourier series of both the odd and even periodic extension of the function
f (t) = t for 0 ≤ t ≤ π.
Exercise 4.4.7: Find the Fourier series of the even periodic extension of the function f (t) = sin t
for 0 ≤ t ≤ π.
Exercise 4.4.8: Let
x (t) + 4 x(t) = f (t),
where f (t) = 1 on 0 < t < 1. a) Solve for the Dirichlet conditions x(0) = 0, x(1) = 0. b) Solve for
the Neumann conditions x (0) = 0, x (1) = 0.
Exercise 4.4.9: Let
x (t) + 9 x(t) = f (t),
for f (t) = sin(2πt) on 0 < t < 1. a) Solve for the Dirichlet conditions x(0) = 0, x(1) = 0. b) Solve
for the Neumann conditions x (0) = 0, x (1) = 0.
Exercise 4.4.10: Let
x (t) + 3 x(t) = f (t), x(0) = 0, x(1) = 0, where f (t) = ∞ 1 bn sin(nπt). Write the solution x(t) as a Fourier series, where the coefficients are
n=
given in terms of bn .
Exercise 4.4.11: Let f (t) = t2 (2 − t) for 0 ≤ t ≤ 2. Let F (t) be the odd periodic extension. Compute
F (1), F (2), F (3), F (−1), F (9/2), F (101), F (103). Note: Do not compute using the sine series. 4.5. APPLICATIONS OF FOURIER SERIES 4.5 175 Applications of Fourier series Note: 2 lectures, §9.4 in [EP] 4.5.1 Periodically forced oscillation Let us return to the forced oscillations. We have a mass spring
system as before, where we have a mass m on a spring with spring
constant k, with damping c, and a force F (t) applied to the mass.
Suppose that the forcing function F (t) is 2L-periodic for some
L > 0. We have already seen this problem in chapter 2 with a
simple F (t). The equation that governs this particular setup is
mx (t) + cx (t) + kx(t) = F (t). k F (t)
m damping c (4.9) We know that the general solution will consist of xc , which solves the associated homogeneous
equation mx + cx + kx = 0, and a particular solution of (4.9) we will call x p . For c > 0, the
complementary solution xc will decay as time goes on. Therefore, we are mostly interested in
particular solution x p that does not decay and is periodic with the same period as F (t). We call
this particular solution the steady periodic solution and we write it as x sp as before. The difference
in what we will do now is that we consider an arbitrary forcing function F (t) instead of a simple
cosine.
For simplicity, let us suppose that c = 0. The problem with c > 0 is very similar. The equation
mx + kx = 0
has the general solution
x(t) = A cos(ω0 t) + B sin(ω0 t),
k
where ω0 = m . Any solution to mx (t) + kx(t) = F (t) will be of the form A cos(ω0 t) + B sin(ω0 t) +
x sp . The steady periodic solution x sp has the same period as F (t).
In the spirit of the last section and the idea of undetermined coefficients we will first write c0
F (t) =
+
2 ∞ cn cos
n=1 nπ
nπ
t + dn sin
t.
L
L Then we write a proposed steady periodic solution x as
a0
x(t) =
+
2 ∞ an cos
n=1 nπ
nπ
t + bn sin
t,
L
L where an and bn are unknowns. We plug x into the differential equation and solve for an and bn in
terms of cn and dn . This process is perhaps best understood by example. 176 CHAPTER 4. FOURIER SERIES AND PDES Example 4.5.1: Suppose that k = 2, and m = 1. The units are the mks units (meters-kilogramsseconds) again. There is a jetpack strapped to the mass, which fires with a force of 1 newton for 1
second and then is off for 1 second, and so on. We want to find the steady periodic solution.
The equation is, therefore,
x + 2 x = F (t),
where F (t) is the step function 0 F (t) = 1 if −1 < t < 0,
if 0 < t < 1, extended periodically. We write
F (t) = c0
+
2 ∞ cn cos(nπt) + dn sin(nπt).
n=1 We compute
1 cn = 1 F (t) cos(nπt) dt =
−1
1 c0 = for n ≥ 1, 1 F (t) dt =
−1
1 dn = cos(nπt) dt = 0
0 dt = 1,
0 F (t) sin(nπt) dt
−1
1 = sin(nπt) dt
0 − cos(nπt)
=
nπ
n = 1
t =0 2 πn if n odd,
if n even. 1 − (−1)
=
0 πn So
F (t) = 1
+
2 ∞
n=1
n odd 2
sin(nπt).
πn We want to try
a0
x(t) =
+
2 ∞ an cos(nπt) + bn sin(nπt).
n=1 Once we plug x into the differential equation x + 2 x = F (t), it is clear that an = 0 for n ≥ 1 as there
are no corresponding terms in the series for F (t). Similarly bn = 0 for n even. Hence we try
a0
x(t) =
+
2 ∞ bn sin(nπt).
n=1
n odd 4.5. APPLICATIONS OF FOURIER SERIES 177 We plug into the differential equation and obtain
∞ x + 2x = ∞ −bn n π sin(nπt) + a0 + 2 bn sin(nπt) 22 n=1
n odd n=1
n odd
∞ bn (2 − n2 π2 ) sin(nπt) = a0 +
n=1
n odd 1
= F (t) = +
2 ∞
n=1
n odd 2
sin(nπt).
πn 1
So a0 = 2 , bn = 0 for even n, and for odd n we get bn = 2
.
πn(2 − n2 π2 ) The steady periodic solution has the Fourier series
x sp (t) = 1
+
4 ∞
n=1
n odd 2
sin(nπt).
πn(2 − n2 π2 ) We know this is the steady periodic solution as it contains no terms of the complementary solution
and it is periodic with the same period as F (t) itself. See Figure 4.12 for the plot of this solution.
0.5 0.0 2.5 5.0 7.5 10.0
0.5 0.4 0.4 0.3 0.3 0.2 0.2 0.1 0.1 0.0
0.0 2.5 5.0 7.5 0.0
10.0 Figure 4.12: Plot of the steady periodic solution x sp of Example 4.5.1. 178 4.5.2 CHAPTER 4. FOURIER SERIES AND PDES Resonance Just like when the forcing function was a simple cosine, resonance could still happen. Let us assume
c = 0 and we will discuss only pure resonance. Again, take the equation
mx (t) + kx(t) = F (t).
When we expand F (t) and find that some of its terms coincide with the complementary solution to
mx + kx = 0, we cannot use those terms in the guess. Just like before, they will disappear when
we plug into the left hand side and we will get a contradictory equation (such as 0 = 1). That is,
suppose
xc = A cos(ω0 t) + B sin(ω0 t),
where ω0 = Nπ
L for some positive integer N . In this case we have to modify our guess and try Nπ
Nπ
a0
x(t) =
+ t aN cos
t + bN sin
t+
2
L
L ∞ an cos
n=1
nN nπ
nπ
t + bn sin
t.
L
L In other words, we multiply the offending term by t. From then on, we proceed as before.
Of course, the solution will not be a Fourier series (it will not even be periodic) since it contains these terms multiplied by t. Further, the terms t aN cos N π t + bN sin N π t will eventually
L
L
dominate and lead to wild oscillations. As before, this behavior is called pure resonance or just
resonance.
Note that there now may be infinitely many resonance frequencies to hit. That is, as we change
the frequency of F (we change L), different terms from the Fourier series of F may interfere with the
complementary solution and will cause resonance. However, we should note that since everything
is an approximation and in particular c is never actually zero but something very close to zero, only
the first few resonance frequencies will matter.
Example 4.5.2: Find the steady periodic solution to the equation
2 x + 18π2 x = F (t),
where −1 F (t) = 1 if −1 < t < 0,
if 0 < t < 1, extended periodically. We note that
∞ F (t) =
n=1
n odd 4
sin(nπt).
πn Exercise 4.5.1: Compute the Fourier series of F to verify the above equation. 4.5. APPLICATIONS OF FOURIER SERIES 179 The solution must look like
x(t) = c1 cos(3πt) + c2 sin(3πt) + x p (t)
for some particular solution x p .
We note that if we just tried a Fourier series with sin(nπt) as usual, we would get duplication
when n = 3. Therefore, we pull out that term and multiply by t. We also have to add a cosine term
to get everything right. That is, we must try
∞ x p (t) = a3 t cos(3πt) + b3 t sin(3πt) + bn sin(nπt).
n=1
n odd
n3 Let us compute the second derivative.
x p (t) = −6a3 π sin(3πt) − 9π2 a3 t cos(3πt) + 6b3 π cos(3πt) − 9π2 b3 t sin(3πt)+
∞ (−n2 π2 bn ) sin(nπt). + n=1
n odd
n3 We now plug into the left hand side of the differential equation.
2 x p + 18π2 x = − 12a3 π sin(3πt) − 18π2 a3 t cos(3πt) + 12b3 π cos(3πt) − 18π2 b3 t sin(3πt)+
+ 18π2 a3 t cos(3πt) + 18π2 b3 t sin(3πt)+ ∞ + (−2n2 π2 bn + 18π2 bn ) sin(nπt).
n=1
n odd
n3 If we simplify we obtain
∞ 2 x p + 18π x = −12a3 π sin(3πt) + 12b3 π cos(3πt) +
2 (−2n2 π2 bn + 18π2 bn ) sin(nπt).
n=1
n odd
n3 This series has to equal to the series for F (t). We equate the coefficients and solve for a3 and bn .
−1
4/(3π)
= 2,
−12π
9π
b3 = 0,
4
2
bn =
=3
nπ(18π2 − 2n2 π2 ) π n(9 − n2 ) a3 = for n odd and n 3. 180 CHAPTER 4. FOURIER SERIES AND PDES That is,
−1
x p (t) = 2 t cos(3πt) +
9π ∞
n=1
n odd
n3 2
sin(nπt).
− n2 ) π3 n(9 When c > 0, you will not have to worry about pure resonance. That is, there will never be
any conflicts and you do not need to multiply any terms by t. There is a corresponding concept of
practical resonance and it is very similar to the ideas we already explored in chapter 2. We will not
go into details here. 4.5.3 Exercises Exercise 4.5.2: Let F (t) = 1 + ∞ 1 n12 cos(nπt). Find the steady periodic solution to x + 2 x = F (t).
n=
2
Express your solution as a Fourier series.
Exercise 4.5.3: Let F (t) = ∞ 1 n13 sin(nπt). Find the steady periodic solution to x + x + x = F (t).
n=
Express your solution as a Fourier series.
Exercise 4.5.4: Let F (t) = ∞ 1 n12 cos(nπt). Find the steady periodic solution to x + 4 x = F (t).
n=
Express your solution as a Fourier series.
Exercise 4.5.5: Let F (t) = t for −1 < t < 1 and extended periodically. Find the steady periodic
solution to x + x = F (t). Express your solution as a Fourier series.
Exercise 4.5.6: Let F (t) = t for −1 < t < 1 and extended periodically. Find the steady periodic
solution to x + π2 x = F (t). Express your solution as a Fourier series. 4.6. PDES, SEPARATION OF VARIABLES, AND THE HEAT EQUATION 4.6 181 PDEs, separation of variables, and the heat equation Note: 2 lectures, §9.5 in [EP]
Let us recall that a partial differential equation or PDE is an equation containing the partial
derivatives with respect to several independent variables. Solving PDEs will be our main application
of Fourier series.
A PDE is said to be linear if the dependent variable and its derivatives appear at most to the
first power and in no functions. We will only talk about linear PDEs. Together with a PDE, we
usually have specified some boundary conditions, where the value of the solution or its derivatives
is specified along the boundary of a region, and/or some initial conditions where the value of the
solution or its derivatives is specified for some initial time. Sometimes such conditions are mixed
together and we will refer to them simply as side conditions.
We will study three specific partial differential. 4.6.1 Heat on an insulated wire Let us first study the heat equation. Suppose that we have a wire (or a thin metal rod) of length L
that is insulated except at the endpoints. Let x denote the position along the wire and let t denote
time. See Figure 4.13.
temperature u 0
insulation L x Figure 4.13: Insulated wire.
Let u( x, t) denote the temperature at point x at time t. The equation governing this setup is the
so-called one-dimensional heat equation:
∂u
∂2 u
= k 2,
∂t
∂x
where k > 0 is a constant (the thermal conductivity of the material). That is, the change in heat at a
specific point is proportional to the second derivative of the heat along the wire. This makes sense; 182 CHAPTER 4. FOURIER SERIES AND PDES if at a fixed t the graph of the heat distribution has a maximum (the graph is concave down), then
heat flows away from the maximum. And vice-versa.
We will generally use a more convenient notation for partial derivatives. We will write ut instead
2
of ∂u , and we will write u xx instead of ∂ xu . With this notation the heat equation becomes
∂t
∂2
ut = ku xx .
u(0, t) = 0 and u( L , t ) = 0. If, on the other hand, the ends are also insulated we get the conditions
u x (0, t) = 0 and u x ( L , t ) = 0. In other words, heat is not flowing1
and u2 are solutions and c1 , c2 are constants, then u = c1 u1 + c2 u2 is also a solution.
Exercise 4.6.1: Verify the principle of superposition for the heat equation.
Superposition also preserves some of the side conditions. In particular, if u1 and u2 are solutions
that satisfy u(0, t) = 0 and u(L, t) = 0, and c1 , c2 are constants, then u = c1 u1 + c2 u2 is still a solution
that satisfies u(0, t) = 0 and u(L, t) = 0. Similarly for the side conditions u x (0, t) = 0 and u x (L, t) = 0.
In general, superposition preserves all homogeneous side conditions.
The method of separation of variables is to try to find solutions that are sums or products of
functions of one variable. For example, for the heat equation, we try to find solutions of the form
u( x, t) = X ( x)T (t). 4.6. PDES, SEPARATION OF VARIABLES, AND THE HEAT EQUATION 183 That the desired solution we are looking for is of this form is too much to hope for. What is perfectly
reasonable to ask, however, is to find enough “building-block” solutions of the form u( x, t) =
X ( x)T (t) using this procedure so that the desired solution to the PDE is somehow constructed from
these building blocks by the use of superposition.
Let us try to solve the heat equation
ut = ku xx with u(0, t) = 0, u(L, t) = 0, and u( x, 0) = f ( x). Let us guess u( x, t) = X ( x)T (t). We plug into the heat equation to obtain
X ( x)T (t) = kX ( x)T (t).
We rewrite as X ( x)
T (t)
=
.
kT (t)
X ( x)
This equation is supposed to hold for all x and all t. But the left hand side does not depend on x and
the right hand side does not depend on t. Therefore, each side must be a constant. Let us call this
constant −λ (the minus sign is for convenience later). We obtain the two equations
X ( x)
T (t)
= −λ =
.
kT (t)
X ( x)
Or in other words
X ( x ) + λ X ( x ) = 0,
T (t) + λkT (t) = 0.
The boundary condition u(0, t) = 0 implies X (0)T (t) = 0. We are looking for a nontrivial solution
and so we can assume that T (t) is not identically zero. Hence X (0) = 0. Similarly, u(L, t) = 0
implies X (L) = 0. We are looking for nontrivial solutions X of the eigenvalue problem X + λX = 0,
22
X (0) = 0, X (L) = 0. We have previously found that the only eigenvalues are λn = nLπ , for integers
2
nπ
n ≥ 1, where eigenfunctions are sin L x . Hence, let us pick the solutions
Xn ( x) = sin nπ
x.
L The corresponding T n must satisfy the equation
T n (t) + n2 π2
kT n (t) = 0.
L2 By the method of integrating factor, the solution of this problem is
T n (t) = e −n2 π2
kt
L2 . 184 CHAPTER 4. FOURIER SERIES AND PDES It will be useful to note that T n (0) = 1. Our building-block solutions are
un ( x, t) = Xn ( x)T n (t) = sin
We note that un ( x, 0) = sin nπ
L −n2 π2
nπ
x e L2 kt .
L x . Let us write f ( x) as the sine series
∞ f ( x) = bn sin
n=1 nπ
x.
L That is, we find the Fourier series of the odd periodic extension of f ( x). We used the sine series as
it corresponds to the eigenvalue problem for X ( x) above. Finally, we use superposition to write the
solution as
∞
∞
−n2 π2
nπ
x e L2 kt .
u( x , t ) =
bn un ( x, t) =
bn sin
L
n=1
n=1
Why does this solution work? First note that it is a solution to the heat equation by superposition.
It satisfies u(0, t) = 0 and u(L, t) = 0, because x = 0 or x = L makes all the sines vanish. Finally,
plugging in t = 0, we notice that T n (0) = 1 and so
∞ u( x, 0) = ∞ bn un ( x, 0) =
n=1 bn sin
n=1 nπ
x = f ( x).
L Example 4.6.1: Suppose that we have an insulated wire of length 1, such that the ends of the wire
are embedded in ice (temperature 0). Let k = 0.003. Then suppose that initial heat distribution is
u( x, 0) = 50 x (1 − x). See Figure 4.14.
0.00 0.25 0.50 0.75 1.00 12.5 12.5 10.0 10.0 7.5 7.5 5.0 5.0 2.5 2.5 0.0
0.00 0.0
0.25 0.50 0.75 1.00 Figure 4.14: Initial distribution of temperature in the wire. 4.6. PDES, SEPARATION OF VARIABLES, AND THE HEAT EQUATION 185 We want to find the temperature function u( x, t). Let us suppose we also want to find when (at
what t) does the maximum temperature in the wire drop to one half of the initial maximum of 12.5.
We are solving the following PDE problem:
ut = 0.003 u xx ,
u(0, t) = u(1, t) = 0,
u( x, 0) = 50 x (1 − x) for 0 < x < 1. We write f ( x) = 50 x (1 − x) for 0 < x < 1 as a sine series. That is, f ( x) = 1 200 200 (−1)n 0 bn = 2
50 x (1 − x) sin(nπ x) dx = 3 3 −
= 400 3 n3 πn
π
0 π3 n3 0.00 0 ∞
n=1 bn sin(nπ x), where if n even,
if n odd. t 20
40 0.25
x 60
0.50 80 u(x,t) 100 0.75
1.00
12.5 12.5 10.0 10.0 7.5 7.5 5.0 5.0 2.5 2.5 0.0 0.0 11.700
10.400
9.100
7.800
6.500
5.200
3.900
2.600
1.300
0.000 0.25 0
20 0.50
40 x
0.75 60
t 80
100 1.00 Figure 4.15: Plot of the temperature of the wire at position x at time t.
The solution u( x, t), plotted in Figure 4.15 for 0 ≤ t ≤ 100, is given by the series:
∞ u( x , t ) =
n=1
n odd 400
22
sin(nπ x) e−n π 0.003 t .
3 n3
π 186 CHAPTER 4. FOURIER SERIES AND PDES Finally, let us answer the question about the maximum temperature. It is relatively easy to see
that the maximum temperature will always be at x = 0.5, in the middle of the wire. The plot of
u( x, t) confirms this intuition.
If we plug in x = 0.5 we get
∞ u(0.5, t) =
n=1
n odd 400
22
sin(nπ 0.5) e−n π 0.003 t .
3 n3
π For n = 3 and higher (remember we are taking only odd n), the terms of the series are insignificant
compared to the first term. The first term in the series is already a very good approximation of the
function and hence
400 2
u(0.5, t) ≈ 3 e−π 0.003 t .
π
The approximation gets better and better as t gets larger as the other terms decay much faster. Let
us plot the function u(0.5, t), the temperature at the midpoint of the wire at time t, in Figure 4.16.
The figure also plots the approximation by the first term.
0 25 50 75 100 12.5 12.5 10.0 10.0 7.5 7.5 5.0 5.0 2.5 2.5 0 25 50 75 100 Figure 4.16: Temperature at the midpoint of the wire (the bottom curve), and the approximation of
this temperature by using only the first term in the series (top curve).
After t = 5 or so it would be hard to tell the difference between the first term of the series for
u( x, t) and the real solution u( x, t). This behavior is a general feature of solving the heat equation. If
you are interested in behavior for large enough t, only the first first term we will be close enough. We solve
6.25 = 400 −π2 0.003 t
e
.
π3 4.6. PDES, SEPARATION OF VARIABLES, AND THE HEAT EQUATION 187 That is, 25
ln 6.400π
t=
≈ 24.5.
−π2 0.003
So the maximum temperature drops to half at about t = 24.5.
3 We mention an interesting behavior of the solution to the heat equation. The heat equation
“smoothes” out the function f ( x) as t grows. For a fixed t, the solution is a Fourier series with
−n2 π2 coefficients bn e L2 kt . If t > 0, then these coefficients go to zero faster than any n1p for any power
p. In other words, the Fourier series has infinitely many derivatives everywhere. Thus even if the
function f ( x) has jumps and corners, the solution u( x, t) as a function of x for a fixed t > 0 is as
smooth as we want it. 4.6.3 Insulated ends Now suppose the ends of the wire are insulated. In this case, we are solving the equation
ut = ku xx with u x (0, t) = 0, u x ( L , t ) = 0, and u( x, 0) = f ( x). Yet again we try a solution of the form u( x, t) = X ( x)T (t). By the same procedure as before we plug
into the heat equation and arrive at the following two equations
X ( x ) + λ X ( x ) = 0,
T (t) + λkT (t) = 0.
At this point the story changes slightly. The boundary condition u x (0, t) = 0 implies X (0)T (t) = 0.
Hence X (0) = 0. Similarly, u x (L, t) = 0 implies X (L) = 0. We are looking for nontrivial solutions
X of the eigenvalue problem X + λX = 0, X (0) = 0, X (L) = 0. We have previously found that the
22
π
only eigenvalues are λn = nLπ , for integers n ≥ 0, where eigenfunctions are cos nL x (we include
2
the constant eigenfunction). Hence, let us pick solutions
Xn ( x) = cos nπ
x
L X0 ( x ) = 1. and The corresponding T n must satisfy the equation
T n (t) + n2 π2
kT n (t) = 0.
L2 For n ≥ 1, as before,
T n (t) = e −n2 π2
kt
L2 . For n = 0, we have T 0 (t) = 0 and hence T 0 (t) = 1. Our building-block solutions will be
un ( x, t) = Xn ( x)T n (t) = cos −n2 π2
nπ
x e L2 kt ,
L 188 CHAPTER 4. FOURIER SERIES AND PDES and
u0 ( x, t) = 1.
We note that un ( x, 0) = cos nπ
L x . Let us write f using the cosine series
f ( x) = a0
+
2 ∞ an cos
n=1 nπ
x.
L That is, we find the Fourier series of the even periodic extension of f ( x).
We use superposition to write the solution as
a0
u( x , t ) =
+
2 ∞ a0
an un ( x , t ) =
+
2
n=1 ∞ an cos
n=1 −n2 π2
nπ
x e L2 kt .
L Example 4.6.2: Let us try the same equation as before, but for insulated ends. We are solving the
following PDE problem
ut = 0.003 u xx ,
u x (0, t) = u x (1, t) = 0,
u( x, 0) = 50 x (1 − x) for 0 < x < 1. For this problem, we must find the cosine series of u( x, 0). For 0 < x < 1 we have
25
+
50 x (1 − x) =
3 ∞
n=2
n even −200
cos(nπ x).
π2 n2 The calculation is left to the reader. Hence, the solution to the PDE problem, plotted in Figure 4.17
on the next page, is given by the series
25
u( x, t) =
+
3 ∞
n=2
n even −200
22
cos(nπ x) e−n π 0.003 t .
2 n2
π Note in the graph that the temperature evens out across the wire. Eventually, all the terms except
the constant die out, and you will be left with a uniform temperature of 25 ≈ 8.33 along the entire
3
length of the wire. 4.6.4 Exercises Exercise 4.6.2: Suppose you have a wire of length 2, with k = 0.001 and an initial temperature
distribution of u( x, 0) = 50 x. Suppose that both the ends are embedded in ice (temperature 0). Find
the solution as a series. 4.6. PDES, SEPARATION OF VARIABLES, AND THE HEAT EQUATION 189 0.00 0
x 5 0.25 t
10 0.50 15
20 0.75 u(x,t) 25 1.00 30 12.5 12.5
10.0 10.0
7.5 7.5
5.0 11.700
10.400
9.100
7.800
6.500
5.200
3.900
2.600
1.300
0.000 5.0
2.5 2.5
0.0
0 0.0
0.00 5
0.25 10
15 0.50
20 t 0.75 25 x 30 1.00 Figure 4.17: Plot of the temperature of the insulated wire at position x at time t. Exercise 4.6.3: Find a series solution of
ut = u xx ,
u(0, t) = u(1, t) = 0,
u( x, 0) = 100
for 0 < x < 1.
Exercise 4.6.4: Find a series solution of
ut = u xx ,
u x (0, t) = u x (π, t) = 0,
u( x, 0) = 3 cos( x) + cos(3 x) for 0 < x < π. 190 CHAPTER 4. FOURIER SERIES AND PDES Exercise 4.6.5: Find a series solution of
1
u xx ,
3
u x (0, t) = u x (π, t) = 0,
10 x
u( x, 0) =
for 0 < x < π.
π ut = Exercise 4.6.6: Find a series solution of
ut = u xx ,
u(0, t) = 0, u(1, t) = 100,
u( x, 0) = sin(π x)
for 0 < x < 1.
Hint: Use the fact that u( x, t) = 100 x is a solution satisfying ut = u xx , u(0, t) = 0, u(1, t) = 100.
Then use superposition.
Exercise 4.6.7: Find the steady state temperature solution as a function of x alone, by letting t → ∞
in the solution from exercises 4.6.5 and 4.6.6. Verify that it satisfies the equation u xx = 0.
Exercise 4.6.8: Use separation variables to find a nontrivial solution to u xx + uyy = 0, where
u( x, 0) = 0 and u(0, y) = 0. Hint: Try u( x, y) = X ( x)Y (y).
Exercise 4.6.9 (challenging): Suppose that one end of the wire is insulated (say at x = 0) and the
other end is kept at zero temperature. That is, find a series solution of
ut = ku xx ,
u x (0, t) = u(L, t) = 0,
u( x, 0) = f ( x)
for 0 < x < L.
Express any coefficients in the series by integrals of f ( x).
Exercise 4.6.10 (challenging): Suppose that the wire is circular and insulated, so there are no ends.
You can think of this as simply connecting the two ends and making sure the solution matches up at
the ends. That is, find a series solution of
ut = ku xx ,
u(0, t) = u(L, t),
u( x, 0) = f ( x) u x (0, t) = u x (L, t),
for 0 < x < L. Express any coefficients in the series by integrals of f ( x). 4.7. ONE DIMENSIONAL WAVE EQUATION 4.7 191 One dimensional wave equation Note: 1 lecture, §9.6 in [EP]
Suppose we have a string such as on a guitar of length L. Suppose we only consider vibrations
in one direction. That is let x denote the position along the string, let t denote time and let y denote
the displacement of the string from the rest position. See Figure 4.18.
y
y
0 L x Figure 4.18: Vibrating string. The equation that governs this setup is the so-called one-dimensional wave equation:
ytt = a2 y xx ,
for some a > 0. We will assume that the ends of the string are fixed and hence we get
y(0, t) = 0 and y(L, t) = 0. Note that we always have two conditions along the x axis as there are two derivatives in the x
direction.
There are also two derivatives along the t direction and hence we will need two further conditions
here. We will need to know the initial position and the initial velocity of the string.
y( x, 0) = f ( x) and yt ( x, 0) = g( x), for some known functions f ( x) and g( x).
As the equation is again linear, superposition works just as it did for the heat equation. And
again we will use separation of variables to find enough building-block solutions to get the overall
solution. There is one change however. It will be easier to solve two separate problems and add
their solutions.
The two problems we will solve are
wtt = a2 w xx ,
w(0, t) = w(L, t) = 0,
w( x, 0) = 0
wt ( x, 0) = g( x) for 0 < x < L,
for 0 < x < L. (4.10) 192
and CHAPTER 4. FOURIER SERIES AND PDES
ztt = a2 z xx ,
z(0, t) = z(L, t) = 0,
z( x, 0) = f ( x)
zt ( x, 0) = 0 for 0 < x < L,
for 0 < x < L. (4.11) The principle of superposition will then imply that y = w + z solves the wave equation and
furthermore y( x, 0) = w( x, 0) + z( x, 0) = f ( x) and yt ( x, 0) = wt ( x, 0) + zt ( x, 0) = g( x). Hence, y is a
solution to
ytt = a2 y xx ,
y(0, t) = y(L, t) = 0,
(4.12)
y( x, 0) = f ( x)
for 0 < x < L,
yt ( x, 0) = g( x)
for 0 < x < L.
The reason for all this complexity is that superposition only works for homogeneous conditions
such as y(0, t) = y(L, t) = 0, y( x, 0) = 0, or yt ( x, 0) = 0. Therefore, we will be able to use the
idea of separation of variables to find many building-block solutions solving all the homogeneous
conditions. We can then use them to construct a solution solving the remaining nonhomogeneous
condition.
Let us start with (4.10). We try a solution of the form w( x, t) = X ( x)T (t) again. We plug into the
wave equation to obtain
X ( x)T (t) = a2 X ( x)T (t).
Rewriting we get
T (t)
X ( x)
=
.
2 T (t)
a
X ( x)
Again, left hand side depends only on t and the right hand side depends only on x. Therefore, both
equal a constant, which we will denote by −λ.
X ( x)
T (t)
= −λ =
.
2 T (t)
a
X ( x)
We solve to get two ordinary differential equations
X ( x) + λX ( x) = 0,
T (t) + λa2 T (t) = 0.
The conditions 0 = w(0, t) = X (0)T (t) implies X (0) = 0 and w(L, t) = 0 implies that X (L) = 0.
22
Therefore, the only nontrivial solutions for the first equation are when λ = λn = nLπ and they are
2
Xn ( x) = sin nπ
x.
L The general solution for T for this particular λn is
T n (t) = A cos nπa
nπa
t + B sin
t.
L
L 4.7. ONE DIMENSIONAL WAVE EQUATION 193 We also have the condition that w( x, 0) = 0 or X ( x)T (0) = 0. This implies that T (0) = 0, which in
turn forces A = 0. It will be convenient to pick B = nLa (you will see why in a moment) and hence
π
T n (t ) = nπa
L
sin
t.
nπa
L Our building-block solution will be
wn ( x, t) = nπ
nπa
L
sin
x sin
t.
nπa
L
L We differentiate in t, that is
nπ
nπa
x cos
t.
L
L (wn )t ( x, t) = sin
Hence, (wn )t ( x, 0) = sin nπ
x.
L We expand g( x) in terms of these sines as
∞ g( x) = bn sin
n=1 nπ
x.
L Using superposition we can just write down the solution to (4.10) as a series
∞ w( x , t ) = ∞ bn wn ( x, t) =
n=1 bn
n=1 nπ
nπa
L
sin
x sin
t.
nπa
L
L Exercise 4.7.1: Check that w( x, 0) = 0 and wt ( x, 0) = g( x).
Similarly we proceed to solve (4.11). We again try z( x, y) = X ( x)T (t). The procedure works
exactly the same at first. We obtain
X ( x) + λX ( x) = 0,
T (t) + λa2 T (t) = 0.
and the conditions X (0) = 0, X (L) = 0. So again λ = λn =
Xn ( x) = sin n2 π2
L2 and nπ
x.
L This time the condition on T is T (0) = 0. Thus we get that B = 0 and we take
T n (t) = cos nπa
t.
L 194 CHAPTER 4. FOURIER SERIES AND PDES Our building-block solution will be
zn ( x, t) = sin nπ
nπa
x cos
t.
L
L We expand f ( x) in terms of these sines as
∞ f ( x) = cn sin
n=1 nπ
x.
L And we write down the solution to (4.11) as a series
∞ z( x, t) = ∞ cn zn ( x, t) =
n=1 cn sin
n=1 nπ
nπa
x cos
t.
L
L Exercise 4.7.2: Fill in the details in the derivation of the solution of (4.11). Check that the solution
satisfies all the side conditions.
Putting these two solutions together we will state the result as a theorem.
Theorem 4.7.1. Take the equation
ytt = a2 y xx ,
y(0, t) = y(L, t) = 0,
y( x, 0) = f ( x)
yt ( x, 0) = g( x)
where ∞ cn sin nπ
x.
L n=1
∞ g( x) =
n=1 (4.13) nπ
x.
L bn sin f ( x) =
and for 0 < x < L,
for 0 < x < L, Then the solution y( x, t) can be written as a sum of the solutions of (4.10) and (4.11). In other
words,
∞ y( x , t ) = bn
n=1
∞ = L
nπ
nπa
nπ
nπa
sin
x sin
t + cn sin
x cos
t
nπa
L
L
L
L sin
n=1 nπ
x
L bn L
nπa
nπa
sin
t + cn cos
t.
nπa
L
L 4.7. ONE DIMENSIONAL WAVE EQUATION 195 y
0.1
0 2 x Figure 4.19: Plucked string. Example 4.7.1: Let us try a simple example of a plucked string. Suppose that a string of length 2
is plucked in the middle such that it has the initial shape given in Figure 4.19. That is 0.1 x if 0 ≤ x ≤ 1, f ( x) = 0.1 (2 − x) if 1 < x ≤ 2. The string starts at rest (g( x) = 0). Suppose that a = 1 in the wave equation for simplicity.
We leave it to the reader to compute the sine series of f ( x). The series will be
∞ f ( x) =
n=1 Note that sin nπ
2 nπ
nπ
0.8
x.
sin
sin
n2 π2
2
2 is the sequence 1, 0, −1, 0, 1, 0, −1, . . . for n = 1, 2, 3, 4, . . .. Therefore,
f ( x) = 0.8
0.8
0 .8
π
3π
5π
x+
x − ···
sin x − 2 sin
sin
2
2
π
2
9π
2
25π
2 The solution y( x, t) is given by
∞ y( x, t) =
n=1
∞ =
m =1 = 0 .8
nπ
nπ
nπ
x cos
t
sin
sin
2 π2
n
2
2
2
0.8(−1)m+1
(2m − 1)π
(2m − 1)π
sin
x cos
t
22
2
2
(2m − 1) π π
3π
5π
0.8
π
0.8
3π
0 .8
5π
sin x cos t − 2 sin
x cos
t+
sin
x cos
t − ···
2
2
π
2
2
9π
2
2
25π
2
2 A plot for 0 < t < 3 is given in Figure 4.20 on the following page. Notice that unlike the heat
equation, the solution does not become “smoother,” the “sharp edges” remain. We will see the
reason for this behavior in the next section where we derive the solution to the wave equation in a
different way.
Make sure you understand what the plot such as the one in the figure is telling you. For each
fixed t, you can think of the function u( x, t) as just a function of x. This function gives you the shape
of the string at time t. 196 CHAPTER 4. FOURIER SERIES AND PDES
0.0 0
t 1
0.5 2 x
1.0 y(x,t) 3
0.10 1.5
2.0 0.00 0.00 -0.05 -0.05 -0.10 y
0.05 0.05 y 0.10 0.110
0.088
0.066
0.044
0.022
0.000
-0.022
-0.044
-0.066
-0.088
-0.110 0.0
0.5 -0.10
0 1.0
x 1
1.5
t 2
3 2.0 Figure 4.20: Shape of the plucked string for 0 < t < 3. 4.7.1 Exercises Exercise 4.7.3: Solve
ytt = 9y xx ,
y(0, t) = y(1, t) = 0,
y( x, 0) = sin(3π x) + 1 sin(6π x)
4
yt ( x, 0) = 0 for 0 < x < 1,
for 0 < x < 1. ytt = 4y xx ,
y(0, t) = y(1, t) = 0,
y( x, 0) = sin(3π x) + 1 sin(6π x)
4
yt ( x, 0) = sin(9π x) for 0 < x < 1,
for 0 < x < 1. Exercise 4.7.4: Solve Exercise 4.7.5: Derive the solution for a general plucked string of length L, where we raise the
string some distance b at the midpoint and let go, and for any constant a (in the equation ytt = a2 y xx ). 4.7. ONE DIMENSIONAL WAVE EQUATION 197 Exercise 4.7.6: Suppose that a stringed musical instrument falls on the floor. Suppose that the
length of the string is 1 and a = 1. When the musical instrument hits the ground the string was in
rest position and hence y( x, 0) = 0. However, the string was moving at some velocity at impact
(t = 0), say yt ( x, 0) = −1. Find the solution y( x, t) for the shape of the string at time t.
Exercise 4.7.7 (challenging): Suppose that you have a vibrating string and that there is air resistance proportional to the velocity. That is, you have
ytt = a2 y xx − kyt ,
y(0, t) = y(1, t) = 0,
y( x, 0) = f ( x)
yt ( x, 0) = 0 for 0 < x < 1,
for 0 < x < 1. Suppose that 0 < k < 2πa. Derive a series solution to the problem. Any coefficients in the series
should be expressed as integrals of f ( x). 198 CHAPTER 4. FOURIER SERIES AND PDES 4.8 D’Alembert solution of the wave equation Note: 1 lecture, different from §9.6 in [EP]
We have solved the wave equation by using Fourier series. But it is often more convenient to
use the so-called d’Alembert solution to the wave equation‡ . This solution can be derived using
Fourier series as well, but it is really an awkward use of those concepts. It is much easier to derive
this solution by making a correct change of variables to get an equation that can be solved by simple
integration.
Suppose we have the wave equation
ytt = a2 y xx . (4.14) And we wish to solve the equation (4.14) given the conditions
y(0, t) = y(L, t) = 0 for all t,
y( x, 0) = f ( x)
0 < x < L,
yt ( x, 0) = g( x)
0 < x < L. 4.8.1 (4.15) Change of variables We will transform the equation into a simpler form where it can be solved by simple integration.
We change variables to ξ = x − at, η = x + at and we use the chain rule:
∂
∂ξ ∂
∂η ∂
∂
∂
=
+
=
+,
∂ x ∂ x ∂ξ ∂ x ∂η ∂ξ ∂η
∂
∂ξ ∂
∂η ∂
∂
∂
=
+
= −a + a .
∂t ∂t ∂ξ ∂t ∂η
∂ξ
∂η
We compute
∂2 y
∂
∂ ∂y ∂y
∂2 y
∂2 y
∂2 y
= 2 +2
,
y xx = 2 =
+
+
+
∂x
∂ξ ∂η ∂ξ ∂η
∂ξ
∂ξ∂η ∂η2
∂2 y
∂
∂
∂y
∂y
∂2 y
∂2 y
∂2 y
ytt = 2 = −a + a
−a + a
= a2 2 − 2a2
+ a2 2 .
∂t
∂ξ
∂η
∂ξ
∂η
∂ξ
∂ξ∂η
∂η
In the above computations, we have used the fact from calculus that
the wave equation,
∂2 y
0 = a2 y xx − ytt = 4a2
= 4a2 yξη .
∂ξ∂η
‡ ∂2 y
∂ξ∂η Named after the French mathematician Jean le Rond d’Alembert (1717 – 1783). = ∂2 y
.
∂η∂ξ Then we plug into 4.8. D’ALEMBERT SOLUTION OF THE WAVE EQUATION 199 Therefore, the wave equation (4.14) transforms into yξη = 0. It is easy to find the general solution
to this equation by integrating twice. Let us integrate with respect to η first§ and notice that the
constant of integration depends on ξ. We get yξ = C (ξ). Next, we integrate with respect to ξ and
notice that the constant of integration must depend on η. Thus, y = C (ξ) dξ + B(η). The solution
must, therefore, be of the following form for some functions A(ξ) and B(η):
y = A(ξ) + B(η) = A( x − at) + B( x + at). 4.8.2). Now define
A( x) = 1
1
F ( x) −
2
2a x G( s) ds, B( x) = 0 1
1
F ( x) +
2
2a x G( s) ds.
0 We claim this A( x) and B( x) give the solution. Explicitly, the solution is y( x, t) = A( x − at) + B( x + at)
or in other words:
x−at
1
1
1
1
F ( x − at) −
G( s) ds + F ( x + at) +
2
2a 0
2
2a
x+at
1
F ( x − at) + F ( x + at)
+
=
G( s) ds.
2
2a x−at x+at y( x, t) = G( s) ds
0 (4.16) Let us check that the d’Alembert formula really works.
1
1
y( x, 0) = F ( x) −
2
2a x
0 1
1
G( s) ds + F ( x) +
2
2a x G( s) ds = F ( x).
0 So far so good. Assume for simplicity F is differentiable. By the fundamental theorem of calculus
we have
−a
1
a
1
yt ( x, t) =
F ( x − at) + G( x − at) + F ( x + at) + G( x + at).
2
2
2
2
So
−a
1
a
1
yt ( x, 0) =
F ( x) + G( x) + F ( x) + G( x) = G( x).
2
2
2
2
Yay! We’re smoking now. OK, now the boundary conditions. Note that F ( x) and G( x) are odd.
x
Also 0 G( s) ds is an even function of x because G( x) is odd (to see this fact, do the substitution
§ We can just as well integrate with ξ first, if we wish. 200 CHAPTER 4. FOURIER SERIES AND PDES s = −v). So
1
y(0, t) = F (−at) −
2
−1
=
F (at) −
2 1
2a
1
2a −at 1
1
G( s) ds + F (at) +
2
2a
0
at
1
1
G( s) ds + F (at) +
2
2a
0 at G( s) ds
0
at G( s) ds = 0.
0 Note that F ( x) and G( x) are 2L periodic. We compute
L−at
L+at
1
1
1
1
F (L − at) −
G( s) ds + F (L + at) +
G( s) ds
2
2a 0
2
2a 0
L
−at
1
1
1
= F (−L − at) −
G( s) ds −
G( s) ds +
2
2a 0
2a 0
L
at
1
1
1
+ F (L + at) +
G( s) ds +
G( s) ds
2
2a 0
2a 0
at
at
−1
1
1
1
=
F (L + at) −
G( s) ds + F (L + at) +
G( s) ds = 0.
2
2a 0
2
2a 0 y(L, t) = And voilà, it works.
Example 4.8.1: What the d’Alembert solution says is that the solution is a superposition of two
functions (waves) moving in the opposite direction at “speed” a. To get an idea of how it works, let
us do an example. Suppose that we have the simpler setup
ytt = y xx ,
y(0, t) = y(1, t) = 0,
y( x, 0) = f ( x),
yt ( x, 0) = 0.
Here f ( x) is an impulse of height 1 centered at x = 0.5: 0 if
0≤ 20 ( x − 0.45) if 0≤ f ( x) = 20 (0.55 − x) if 0.45 ≤ 0 if 0.55 ≤ x < 0.45,
x < 0.45,
x < 0.55,
x ≤ 1. The graph of this pulse is the top left plot in Figure 4.21 on the next page.
Let F ( x) be the odd periodic extension of f ( x). Then from (4.16) we know that the solution is
given as
F ( x − t) + F ( x + t)
y( x, t) =
.
2 4.8. D’ALEMBERT SOLUTION OF THE WAVE EQUATION 201 It is not hard to compute specific values of y( x, t). For example, to compute y(0.1, 0.6) we notice
x − t = −0.5 and x + t = 0.7. Now F (−0.5) = − f (0.5) = −20 (0.55 − 0.5) = −1 and F (0.7) =
f (0.7) = 0. Hence y(0.1, 0.6) = −12+0 = −0.5. As you can see the d’Alembert solution is much easier
to actually compute and to plot than the Fourier series solution. See Figure 4.21 for plots of the
solution y for several different t. 0.25 0.50 0.75 1.00 -1.0 -1.0
0.25 0.50 0.75 1.00 Figure 4.21: Plot of the d’Alembert solution for t = 0, t = 0.2, t = 0.4, and t = 0.6. 4.8.3 Notes It is perhaps easier and more useful to memorize the procedure rather than the formula itself. The
important thing to remember is that a solution to the wave equation is a superposition of two waves
traveling in opposite directions. That is,
y( x, t) = A( x − at) + B( x + at). 202 CHAPTER 4. FOURIER SERIES AND PDES If you think about it, the exact formulas for A and B are not hard to guess once you realize what
kind of side conditions y( x, t) is supposed to satisfy. Let us give the formula again, but slightly
differently. Best approach is to do this in stages. When g( x) = 0 (and hence G( x) = 0) we have the
solution
F ( x − at) + F ( x + at)
.
2
On the other hand, when f ( x) = 0 (and hence F ( x) = 0), we let
x H ( x) = G( s) ds.
0 The solution in this case is
1
2a x+at G( s) ds = x−at −H ( x − at) + H ( x + at)
.
2a By superposition we get a solution for the general side conditions (4.15) (when neither f ( x) nor
g( x) are identically zero).
y( x, t) = F ( x − at) + F ( x + at) −H ( x − at) + H ( x + at)
+
.
2
2a (4.17) Do note the minus sign before the H .
Exercise 4.8.1: Check that the new formula (4.17) satisfies the side conditions (4.15).. 4.8.4 Exercises Exercise 4.8.2: Using the d’Alembert solution solve ytt = 4y xx , 0 < x < π, t > 0, y(0, t) = y(π, t) = 0,
y( x, 0) = sin x, and yt ( x, 0) = sin x. Hint: Note that sin x is the odd extension of y( x, 0) and yt ( x, 0).
Exercise 4.8.3: Using the d’Alembert solution solve ytt = 2y xx , 0 < x < 1, t > 0, y(0, t) = y(1, t) = 0,
y( x, 0) = sin5 (π x), and yt ( x, 0) = sin3 (π x).
Exercise 4.8.4: Take ytt = 4y xx , 0 < x < π, t > 0, y(0, t) = y(π, t) = 0, y( x, 0) = x(π − x), and
yt ( x, 0) = 0. a) Solve using the d’Alembert formula (Hint: You can use the sine series for y( x, 0).) b)
Find the solution as a function of x for a fixed t = 0.5, t = 1, and t = 2. Do not use the sine series
here.
Exercise 4.8.5: Derive the d’Alembert solution for ytt = a2 y xx , 0 < x < π, t > 0, y(0, t) = y(π, t) = 0,
y( x, 0) = f ( x), and yt ( x, 0) = 0, using the Fourier series solution of the wave equation, by applying
an appropriate trigonometric identity. 4.8. D’ALEMBERT SOLUTION OF THE WAVE EQUATION 203 Exercise 4.8.6: The d’Alembert solution still works if there are no boundary conditions and the
initial condition is defined on the whole real line. Suppose that ytt = y xx (for all x on the real line
and t ≥ 0), y( x, 0) = f ( x), and yt ( x, 0) = 0, where 0 if x < −1, x + 1 if −1 ≤ x < 0, f ( x) = − x + 1 if 0 ≤ x < 1, 0 if x > 1.
Solve using the d’Alembert solution. That is, write down a piecewise definition for the solution.
Then sketch the solution for t = 0, t = 1/2, t = 1, and t = 2. 204 CHAPTER 4. FOURIER SERIES AND PDES 4.9 Steady state temperature and the Laplacian Note: 1 lecture, §9.7 in [EP]
Suppose we have an insulated wire, a plate, or a 3-dimensional object. We apply certain fixed
temperatures on the ends of the wire, the edges of the plate or on all sides of the 3-dimensional
object. We wish to find out what is the steady state temperature distribution. That is, we wish to
know what will be the temperature after long enough period of time.
We are really looking for a solution to the heat equation that is not dependent on time. Let us
first do this in one space variable. We are looking for a function u that satisfies
ut = ku xx ,
but such that ut = 0 for all x and t. Hence, we are looking for a function of x alone that satisfies
T2 − T1
u( x) =
x + T1. variables is
ut = k(u xx + uyy ), (4.18) or more commonly written as ut = k∆u or ut = k 2 u. Here the ∆ and 2 symbols mean ∂∂x2 + ∂∂y2 .
We will use ∆ from now on. The reason for that notation is that you can define ∆ to be the right
thing for any number of space dimensions and then the heat equation is always ut = k∆u. The ∆ is
called the Laplacian.
OK, now that we have notation out of the way, let us see what does an equation for the steady
state solution look like. We are looking for a solution to (4.18) that does not depend on t. Hence we
are looking for a function u( x, y) such that
2 2 ∆u = u xx + uyy = 0.
This equation is called the Laplace equation¶ . Solutions to the Laplace equation are called harmonic
functions and have many nice properties and applications far beyond the steady state heat problem.
¶ Named after the French mathematician Pierre-Simon, marquis de Laplace (1749 – 1827). 4.9. STEADY STATE TEMPERATURE AND THE LAPLACIAN 205 Harmonic functions in two variables are no longer just linear (plane graphs). For example,
you can check that the functions x2 − y2 and xy are harmonic. However, if you remember your
multi-variable calculus we note that if u xx is positive, u is concave up in the x direction, then uyy
must be negative and u must be concave down in the y direction. Therefore, a harmonic function can
never have any “hilltop” or “valley” on the graph. This observation is consistent with our intuitive
idea of steady state heat distribution.
Commonly the Laplace equation is part of a so-called Dirichlet problem . That is, we have some
region in the xy-plane and we specify certain values along the boundaries of the region. We then try
to find a solution u defined on this region such that u agrees with the values we specified on the
boundary.
For simplicity, we will consider a rectangular region. Also for simplicity we will specify
boundary values to be zero at 3 of the four edges and only specify an arbitrary function at one
edge. As we still have the principle of superposition, you can use this simpler solution to derive the
general solution for arbitrary boundary values by solving 4 different problems, one for each edge,
and adding those solutions together. This setup is left as an exercise.
We wish to solve the following problem. Let h and w be the height and width of our rectangle,
with one corner at the origin and lying in the first quadrant.
(0, h)
∆u = 0,
u(0, y) = 0 for 0 < y < h,
u( x, h) = 0 for 0 < x < w,
u(w, y) = 0 for 0 < y < h,
u( x, 0) = f ( x) for 0 < x < w. (4.19)
(4.20)
(4.21)
(4.22)
(4.23) u=0 u=0 u=0 (0, 0) (w, h) u = f ( x) (w, 0) The method we will apply is separation of variables. Again, we will come up with enough
building-block solutions satisfying all the homogeneous boundary conditions (all conditions except
(4.23)).
− X
Y
=
.
X
Y Named after the German mathematician Johann Peter Gustav Lejeune Dirichlet (1805 – 1859). 206 CHAPTER 4. FOURIER SERIES AND PDES The left hand side only depends on x and the right hand side only depends on y. Therefore, there is
X
some constant λ such that λ = −X = YY . And we get two equations
X + λ X = 0,
Y − λ Y = 0.
Furthermore, the homogeneous boundary conditions imply that X (0) = X (w) = 0 and Y (h) = 0.
Taking the equation for X we have already seen that we have a nontrivial solution if and only if
22
λ = λn = nwπ and the solution is a multiple of
2
nπ
x.
w
For these given λn , the general solution for Y (one for each n) is
Xn ( x) = sin nπ
nπ
y + Bn sinh
y.
(4.24)
w
w
We only have one condition on Yn and hence we can pick one of An or Bn to be something convenient.
It will be useful to have Yn (0) = 1, so we let An = 1. Setting Yn (h) = 0 and solving for Bn we get that
Yn (y) = An cosh Bn = − cosh
sinh nπh
w
nπh
w . After we plug the An and Bn we into (4.24) and simplify, we find
Yn (y) = sinh
sinh nπ(h−y)
w
nπh
w . We define un ( x, y) = Xn ( x)Yn (y). And note that un satisfies (4.19)–(4.22).
Observe that
nπ
x.
un ( x, 0) = Xn ( x)Yn (0) = sin
w
Suppose
∞
nπ x
f ( x) =
bn sin
.
w
n=1
Then we get a solution of (4.19)–(4.23) of the following form. nπ(h−y)
∞
∞ nπ sinh w u( x, y) =
bn un ( x, y) =
bn sin
x w sinh nπh
n=1
n=1
w . As un satisfies (4.19)–(4.22) and any linear combination (finite or infinite) of un must also satisfy
(4.19)–(4.22), we see that u must satisfy (4.19)–(4.22). By plugging in y = 0 it is easy to see that u
satisfies (4.23) as well. 4.9. STEADY STATE TEMPERATURE AND THE LAPLACIAN 207 Example 4.9.1: Suppose that we take w = h = π and we let f ( x) = π. We compute the sine series
for the function π (we will get the square wave). We find that for 0 < x < π we have
∞ f ( x) =
n=1
n odd 4
sin(nx).
n Therefore the solution u( x, y), see Figure 4.22, to the corresponding Dirichlet problem is given as
∞ u( x, y) =
n=1
n odd 0.0 sinh n(π − y)
4
sin(nx)
.
n
sinh(nπ) 0.0
1.0 0.5
x y 0.5
1.5 1.0 2.0
2.5 1.5 3.0 u(x,y) 2.0
2.5 3.0 3.0
2.5
3.0
2.0
2.5
1.5
2.0
1.0
1.5 3.142
2.828
2.514
2.199
1.885
1.571
1.257
0.943
0.628
0.314
0.000 0.5
1.0
0.0
0.5 0.0
0.5 0.0 1.0
0.0 1.5 0.5
1.0 2.0
1.5 2.5 2.0
2.5
y 3.0 x 3.0 Figure 4.22: Steady state temperature of a square plate with three sides held at zero and one side
held at π. This scenario corresponds to the steady state temperature on a square plate of width π with 3
sides held at 0 degrees and one side held at π degrees. If we have arbitrary initial data on all sides, 208 CHAPTER 4. FOURIER SERIES AND PDES then we solve four problems, each using one piece of nonhomogeneous data. Then we use the
principle of superposition to add up all four solutions to have a solution to the original problem.
There is another way to visualize the solutions. Take a wire and bend it in just the right way so
that it corresponds to the graph of the temperature above the boundary of your region. Then dip the
wire in soapy water and let it form a soapy film stretched between the edges of the wire. It turns out
that this soap film is precisely the graph of the solution to the Laplace equation. Harmonic functions
come up frequently in problems when we are trying to minimize area of some surface or minimize
energy in some system. 4.9.1 Exercises Exercise 4.9.1: Let R be the region described by 0 < x < π and 0 < y < π. Solve the problem
∆ u = 0, u( x, 0) = sin x, u( x, π) = 0, u(0, y) = 0, u(π, y) = 0. Exercise 4.9.2: Let R be the region described by 0 < x < 1 and 0 < y < 1. Solve the problem
u xx + uyy = 0,
u( x, 0) = sin(π x) − sin(2π x),
u(0, y) = 0, u(1, y) = 0. u( x, 1) = 0, Exercise 4.9.3: Let R be the region described by 0 < x < 1 and 0 < y < 1. Solve the problem
u xx + uyy = 0,
u( x, 0) = u( x, 1) = u(0, y) = u(1, y) = C.
for some constant C. Hint: Guess, then check your intuition.
Exercise 4.9.4: Let R be the region described by 0 < x < π and 0 < y < π. Solve
∆u = 0, u( x, 0) = 0, u( x, π) = π, u(0, y) = y, u(π, y) = y. Hint: Try a solution of the form u( x, y) = X ( x) + Y (y) (different separation of variables).
Exercise 4.9.5: Use the solution of Exercise 4.9.4 to solve
∆u = 0, u( x, 0) = sin x, u( x, π) = π, u(0, y) = y, u(π, y) = y. Hint: Use superposition.
Exercise 4.9.6: Let R be the region described by 0 < x < w and 0 < y < h. Solve the problem
u xx + uyy = 0,
u( x, 0) = 0, u( x, h) = f ( x),
u(0, y) = 0, u(w, y) = 0.
The solution should be in series form using the Fourier series coefficients of f ( x). 4.9. STEADY STATE TEMPERATURE AND THE LAPLACIAN 209 Exercise 4.9.7: Let R be the region described by 0 < x < w and 0 < y < h. Solve the problem
u xx + uyy = 0,
u( x, 0) = 0, u( x, h) = 0,
u(0, y) = f (y), u(w, y) = 0.
The solution should be in series form using the Fourier series coefficients of f (y).
Exercise 4.9.8: Let R be the region described by 0 < x < w and 0 < y < h. Solve the problem
u xx + uyy = 0,
u( x, 0) = 0, u( x, h) = 0,
u(0, y) = 0, u(w, y) = f (y).
The solution should be in series form using the Fourier series coefficients of f (y).
Exercise 4.9.9: Let R be the region described by 0 < x < 1 and 0 < y < 1. Solve the problem
u xx + uyy = 0,
u( x, 0) = sin(9π x), u( x, 1) = sin(2π x),
u(0, y) = 0, u(1, y) = 0.
Hint: Use superposition.
Exercise 4.9.10: Let R be the region described by 0 < x < 1 and 0 < y < 1. Solve the problem
u xx + uyy = 0,
u( x, 0) = sin(π x),
u(0, y) = sin(πy),
Hint: Use superposition. u( x, 1) = sin(π x),
u(1, y) = sin(πy). 210 CHAPTER 4. FOURIER SERIES AND PDES Chapter 5
Eigenvalue problems
5.1 Sturm-Liouville problems Note: 2 lectures, §10.1 in [EP] 5.1.1 Boundary value problems We have encountered several different eigenvalue problems such as:
X ( x) + λ X ( x) = 0
with different boundary conditions
X (0) = 0
X (0) = 0
X (0) = 0
X (0) = 0 X ( L) = 0
X ( L) = 0
X ( L) = 0
X ( L) = 0 (Dirichlet) or,
(Neumann) or,
(Mixed) or,
(Mixed), . . . For example for the insulated wire, Dirichlet conditions correspond to applying a zero temperature
at the ends, Neumann means insulating the ends, etc. . . . Other types of endpoint conditions also
arise naturally, such as
hX (0) − X (0) = 0
hX (L) + X (L) = 0,
for some constant h.
These problems came up, for example, in the study of the heat equation ut = ku xx when we
were trying to solve the equation by the method of separation of variables. In the computation we
encountered a certain eigenvalue problem and found the eigenfunctions Xn ( x). We then found the
eigenfunction decomposition of the initial temperature f ( x) = u( x, 0) in terms of the eigenfunctions
∞ f ( x) = cn Xn ( x).
n=1 211 212 CHAPTER 5. EIGENVALUE PROBLEMS Once we had this decomposition and once we found suitable T n (t) such that T n (0) = 1, we noted
that a solution to the original problem could be written as
∞ cn T n (t)Xn ( x). u( x , t ) =
n=1 We will try to solve more general problems using this method. First, we will study second order
linear equations of the form
dy
d
p( x)
− q( x)y + λr( x)y = 0.
dx
dx (5.1) Essentially any second order linear equation of the form a( x)y + b( x)y + c( x)y + λd( x)y = 0 can
be written as (5.1) after multiplying by a proper factor.
Example 5.1.1 (Bessel):
x2 y + xy + λ x2 − n2 y = 0.
Multiply both sides by 1
x to obtain 12
d
dy
n2
n2
2
2
0=
x y + xy + λ x − n y xy + y + λ x −
y=
x
− y + λ xy.
x
x
dx dx
x
We can state the general Sturm-Liouville problem∗ . We seek nontrivial solutions to
dy
d
p( x)
− q( x)y + λr( x)y = 0,
dx
dx
α1 y(a) − α2 y (a) = 0,
β1 y(b) + β2 y (b) = 0. a < x < b,
(5.2) In particular, we seek λs that allow for nontrivial solutions. The λs for which there are nontrivial solutions are called the eigenvalues and the corresponding nontrivial solutions are called
eigenfunctions. Obviously α1 and α2 should not be both zero, same for β1 and β2 .
Theorem 5.1.1. Suppose p( x), p ( x), q( x) and r( x) are continuous on [a, b] and suppose p( x) > 0
and r( x) > 0 for all x in [a, b]. Then the Sturm-Liouville problem (5.2) has an increasing sequence
of eigenvalues
λ1 < λ2 < λ3 < · · ·
such that
lim λn = +∞ n→∞ and such that to each λn there is (up to a constant multiple) a single eigenfunction yn ( x).
Moreover, if q( x) ≥ 0 and α1 , α2 , β1 , β2 ≥ 0, then λn ≥ 0 for all n.
∗ Named after the French mathematicians Jacques Charles François Sturm (1803 – 1855) and Joseph Liouville (1809
– 1882). 5.1. STURM-LIOUVILLE PROBLEMS 213 Note: Be careful about the signs. Also be careful about the inequalities for r and p, they must be
strict for all x!) ≥ 0, and α1 , α2 , β1 , β2 ≥ 0.
When zero is an eigenvalue, we will usually start labeling the eigenvalues at 0 rather than 1 for
convenience.
Example 5.1.2: The problem y + λy, 0 < x < L, y(0) = 0, and y(L) = 0 is a regular SturmLiouville problem. p( x) = 1, q( x) = 0, r( x) = 1, and we have p( x) = 1 > 0 and r( x) = 1 > 0. The
22
π
eigenvalues are λn = nLπ and eigenfunctions are yn ( x) = sin( nL x). All eigenvalues are nonnegative
2
as predicted by the theorem.
Exercise 5.1.1: Find eigenvalues and eigenfunctions for
y + λ y = 0, y (0) = 0, y (1) = 0. Identify the p, q, r, α j , β j . Can you use the theorem to make the search for eigenvalues easier? (Hint:
Consider the condition −y (0) = 0)
Example 5.1.3: Find eigenvalues and eigenfunctions of the problem
y + λy = 0, 0 < x < 1,
hy(0) − y (0) = 0, y (1) = 0, h > 0. These equations give a regular Sturm-Liouville problem.
Exercise 5.1.2: Identify p, q, r, α j , β j in the example above.
First note that λ ≥ 0 by Theorem 5.1.1. Therefore, the general solution (without boundary
conditions) is
√
√
y( x) = A cos( λ x) + B sin( λ x)
if λ > 0,
y( x) = Ax + B
if λ = 0.
Let us see if λ = 0 is an eigenvalue: We must satisfy 0 = hB − A and A = 0, hence B = 0 (as
h > 0), therefore, 0 is not an eigenvalue (no eigenfunction).
Now let us try λ > 0. We plug in the boundary conditions.
√
0 = hA − λ B,
√
√
√
√
0 = −A λ sin( λ) + B λ cos( λ).
Note that if A = 0, then B = 0 and vice-versa, hence both are nonzero. So B =
√
√
√
√
√
0 = −A λ sin( λ) + hA λ cos( λ). As A 0 we get
λ
√
√
√
0 = − λ sin( λ) + h cos( λ), hA
√,
λ and 214 CHAPTER 5. EIGENVALUE PROBLEMS or √
h
√ = tan λ.
λ Now use a computer to find λn . There are tables available, though using a computer or a graphing
calculator will probably be far more convenient nowadays. Easiest method is to plot the functions
h/x and tan x and see for which x they intersect. There will be an infinite number of intersections. So
√
√
denote by λ1 the first intersection, by λ2 the second intersection, etc. . . . For example, when
h = 1, we get that λ1 ≈ 0.86, and λ2 ≈ 3.43. A plot for h = 1 is given in Figure 5.1. The appropriate
√
eigenfunction (let A = 1 for convenience, then B = h/ λ) is
h
yn ( x) = cos( λn x) + √ sin( λn x).
λn 0 2 4 6 4 4 2 2 0 0 -2 -2 -4 -4
0 2 4 Figure 5.1: Plot of 5.1.2 6 1
x and tan x. Orthogonality We have seen the notion of orthogonality before. For example, we have shown that sin(nx) are
orthogonal for distinct n on [0, π]. For general Sturm-Liouville problems we will need a more
general setup. Let r( x) be a weight function (any function, though generally we will assume it
is positive) on [a, b]. Then two functions f ( x), g( x) are said to be orthogonal with respect to the
weight function r( x) when
b f ( x) g( x) r( x) dx = 0.
a 5.1. STURM-LIOUVILLE PROBLEMS 215 In this setting, we define the inner product as
b def f, g = f ( x) g( x) r( x) dx,
a and then say f and g are orthogonal whenever f , g =ξ = r( x) dx.
We have the following orthogonality property of eigenfunctions of a regular Sturm-Liouville
problem.
Theorem 5.1.2. Suppose we have a regular Sturm-Liouville problem
d
dy
p( x)
− q( x)y + λr( x)y = 0,
dx
dx
α1 y(a) − α2 y (a) = 0,
β1 y(b) + β2 y (b) = 0.
Let y j and yk be two distinct eigenfunctions for two distinct eigenvalues λ j and λk . Then
b y j ( x) yk ( x) r( x) dx = 0,
a that is, y j and ykmLiouville problems. We state it here for completeness.
Theorem 5.1.3 (Fredholm alternative). Suppose that we have a regular Sturm-Liouville problem.
Then either
d
dy
p( x)
− q( x)y + λr( x)y = 0,
dx
dx
α1 y(a) − α2 y (a) = 0,
β1 y(b) + β2 y (b) = 0, 216 CHAPTER 5. EIGENVALUE PROBLEMS has a nonzero solution, or
dy
d
p( x )
− q( x)y + λr( x)y = f ( x),
dx
dx
α1 y(a) − α2 y (a) = 0,
β1 y(b) + β2 y (b) = 0,
has a unique solution for any f ( x) continuous on [a, b].
This theorem is used in much the same way as we did before in § 4.4. It is used when solving
more general nonhomogeneous boundary value problems. The theorem does not help us solve the
problem, but it tells us when a solution exists and when it exists if it is unique, so that we know
when to spend time looking for a solution.
∞ f ( x) = cn yn ( x), (5.3) n=1 where yn ( x) the eigenfunctions. We wish to find out if we can represent any function f ( x) in this way,
and if so, we wish to calculate cn (and of course we would want to know if the sum converges). OK,
so imagine we could write f ( x) as (5.3). We will assume convergence and the ability to integrate
the series term by term. Because of orthogonality we have
b f , ym = f ( x) ym ( x) r( x) dx
a
∞ = b yn ( x) ym ( x) r( x) dx cn
a n=1
b = cm ym ( x) ym ( x) r( x) dx = cm ym , ym .
a Hence,
f , ym
cm =
=
ym , ym b f ( x) ym ( x) r( x) dx a b
a 2 ym ( x) r( x) dx . (5.4) 5.1. STURM-LIOUVILLE PROBLEMS 217 Note that ym are known up to a constant multiple, so we could have picked a scalar multiple of an
eigenfunction such that ym , ym = 1 (if we had an arbitrary eigenfunction ym , divide it by ym , ym ).
˜
˜˜
In the case that ym , ym = 1 we would have the simpler form cm = f , ym as we essentially did for
the Fourier series. The following theorem holds more generally, but the statement given is enough
for our purposes.
Theorem 5.1.4. Suppose f is a piecewise smooth continuous function on [a, b]. If y1 , y2 , . . . are the
eigenfunctions of a regular Sturm-Liouville problem, then there exist real constants c1 , c2 , . . . given
by (5.4) such that (5.3) converges and holds for a < x < b.
Example 5.1.4: Take the simple Sturm-Liouville problem
y + λ y = 0, 0<x< π
,
2 π
= 0.
2
The above is a regular problem and furthermore we actually know by Theorem 5.1.1 on page 212
that λ ≥ 0.
Suppose λ = 0, then the general solution is y( x) = Ax + B, we plug in the initial conditions to
get 0 = y(0) = B, and 0 = y ( π ) = A, hence λ = 0 is not an eigenvalue.
2
The general solution, therefore, is
√
√
y( x) = A cos( λ x) + B sin( λ x).
√
√
Plugging in the boundary conditions we get 0 = y(0) = A and 0 = y π = λ B cos λ π . B
2
2
√
√
cannot be zero and hence cos λ π = 0. This means that λ π must be an odd integral multiple of
2
2
√
π
, i.e. (2n − 1) π = λn π . Hence
2
2
2
λn = (2n − 1)2 .
y(0) = 0, y We can take B = 1. And hence our eigenfunctions are
yn ( x) = sin (2n − 1) x .
We finally compute π
2 π
.
4
0
So any piecewise smooth function on [0, π ] can be written as
2
sin (2n − 1) x 2 dx = ∞ f ( x) = cn sin (2n − 1) x ,
n=1 where
f , yn
cn =
=
yn , yn π
2 0 π
2 0 π
2 f ( x) sin (2n − 1) x d x 4
=
2
π
sin (2n − 1) x dx f ( x) sin (2n − 1) x d x. 0 Note that the series converges to an odd 2π-periodic (not π-periodic!) extension of f ( x). 218 CHAPTER 5. EIGENVALUE PROBLEMS Exercise 5.1.3 (challenging): In the above example, the function is defined on 0 < x < π , yet the
2
series converges to an odd 2π-periodic extension of f ( x). Find out how is the extension defined for
π
< x < π.
2 5.1.5 Exercises Exercise 5.1.4: Find eigenvalues and eigenfunctions of
y + λy = 0, y(0) − y (0) = 0, y(1) = 0. Exercise 5.1.5: Expand the function f ( x) = x on 0 ≤ x ≤ 1 using the eigenfunctions of the system
y + λy = 0, y (0) = 0, y(1) = 0. Exercise 5.1.6: Suppose that you had a Sturm-Liouville problem on the interval [0, 1] and came up
with yn ( x) = sin(γnx), where γ > 0 is some constant. Decompose f ( x) = x, 0 < x < 1 in terms of
these eigenfunctions.
Exercise 5.1.7: Find eigenvalues and eigenfunctions of
y(4) + λy = 0, y(0) = 0, y (0) = 0, y(1) = 0, y (1) = 0. This problem is not a Sturm-Liouville problem, but the idea is the same.
Exercise 5.1.8 (more challenging): Find eigenvalues and eigenfunctions for
dx
(e y ) + λe x y = 0,
dx y(0) = 0, y(1) = 0. Hint: First write the system as a constant coefficient system to find general solutions. Do note
that Theorem 5.1.1 on page 212 guarantees λ ≥ 0. 5.2. APPLICATION OF EIGENFUNCTION SERIES 5.2 219 Application of eigenfunction series Note: 1 lecture, §10.2 in [EP]
The eigenfunction series can arise even from higher order equations. Suppose we have an elastic
beam (say made of steel). We will study the transversal vibrations of the beam. That is, assume the
beam lies along the x axis and let y( x, t) measure the displacement of the point x on the beam at
time t. See Figure 5.2.
y y
x
Figure 5.2: Transversal vibrations of a beam.
The equation that governs this setup is
a4 ∂4 y ∂2 y
+
= 0,
∂ x4 ∂t2 for some constant a > 0.
Suppose the beam is of length 1 simply supported (hinged) at the ends. Suppose the beam is
displaced by some function f ( x) at time t = 0 and then let go (initial velocity is 0). Then y satisfies:
a4 y xxxx + ytt = 0 (0 < x < 1, t > 0),
y(0, t) = y xx (0, t) = 0,
y(1, t) = y xx (1, t) = 0,
y( x, 0) = f ( x), yt ( x, 0) = 0. (5.5) Again we try y( x, t) = X ( x)T (t) and plug in to get a4 X (4) T + XT = 0 or
X (4) −T
= 4 = λ.
X
aT
We note that we want T + λa4 T = 0. Let us assume that λ > 0. We can argue that we expect
vibration and not exponential growth nor decay in the t direction (there is no friction in our model
for instance). Similarly λ = 0 will not occur.
Exercise 5.2.1: Try to justify λ > 0 just from the equations. 220 CHAPTER 5. EIGENVALUE PROBLEMS Write ω4 = λ, so that we do not need to write the fourth root all the time. For X we get the
equation X (4) − ω4 X = 0. The general solution is
X ( x) = Aeω x + Be−ω x + C sin(ω x) + D cos(ω x).
Now 0 = X (0) = A + B + D, 0 = X (0) = ω2 (A + B − D). Hence, D = 0 and A + B = 0, or B = −A.
So we have
X ( x) = Aeω x − Ae−ω x + C sin(ω x).
Also 0 = X (1) = A(eω − e−ω ) + C sin ω, and 0 = X (1) = Aω2 (eω − e−ω ) − C ω2 sin ω. This means
that C sin ω = 0 and A(eω − e−ω ) = 2A sinh ω = 0. If ω > 0, then sinh ω 0 and so A = 0. This
means that C 0 otherwise λ is not an eigenvalue. Also ω must be an integer multiple of π. Hence
ω = nπ and n ≥ 1 (as ω > 0). We can take C = 1. So the eigenvalues are λn = n4 π4 and the
eigenfunctions are sin(nπ x).
Now T + n4 π4 a4 T = 0. The general solution is T (t) = A sin(n2 π2 a2 t) + B cos(n2 π2 a2 t). But
T (0) = 0 and hence we must have A = 0 and we can take B = 1 to make T (0) = 1 for convenience.
So our solutions are T n (t) = cos(n2 π2 a2 t).
As the eigenfunctions are just sines again, we can decompose the function f ( x) on 0 < x < 1
using the sine series. We find numbers bn such that for 0 < x < 1 we have
∞ f ( x) = bn sin(nπ x).
n=1 Then the solution to (5.5) is
∞ y( x, t) = ∞ bn Xn ( x)T n (t) =
n=1 bn sin(nπ x) cos(n2 π2 a2 t).
n=1 The point is that Xn T n is a solution that satisfies all the homogeneous conditions (that is, all
conditions except the initial position). And since and T n (0) = 1, we have
∞ y( x, 0) = ∞ bn Xn ( x)T n (0) =
n=1 ∞ bn Xn ( x) =
n=1 bn sin(nπ x) = f ( x).
n=1 So y( x, t) solves (5.5).
Note that the natural (circular) frequency of the system is n2 π2 a2 . These frequencies are all
integer multiples of the fundamental frequency π2 a2 , so we will get a nice musical note. The exact
frequencies and their amplitude are what we call the timbre of the note.
The timbre of a beam is different than for a vibrating string where we will get “more” of the
smaller frequencies since we will get all integer multiples, 1, 2, 3, 4, 5, . . . For a steel beam we will
get only the square multiples 1, 4, 9, 16, 25, . . . That is why when you hit a steel beam you hear a
very pure sound. The sound of a xylophone or vibraphone is, therefore, very different from a guitar
or piano. 5.2. APPLICATION OF EIGENFUNCTION SERIES
Example 5.2.1: Let us assume that f ( x) =
by now) x( x−1)
.
10
∞ f ( x) =
n=1
n odd 221 On 0 < x < 1 we have (you know how to do this 4
sin(nπ x).
5π3 n3 Hence, the solution to (5.5) with the given initial position f ( x) is
∞ y( x , t ) =
n=1
n odd 5.2.1 4
sin(nπ x) cos(n2 π2 a2 t).
5π3 n3 Exercises Exercise 5.2.2: Suppose you have a beam of length 5 with free ends. Let y be the transverse
deviation of the beam at position x on the beam (0 < x < 5). You know that the constants are such
that this satisfies the equation ytt + 4y xxxx = 0. Suppose you know that the initial shape of the beam
is the graph of x(5 − x), and the initial velocity is uniformly equal to 2 (same for each x) in the
positive y direction. Set up the equation together with the boundary and initial conditions. Just set
up, do not solve.
Exercise 5.2.3: Suppose you have a beam of length 5 with one end free and one end fixed (the
fixed end is at x = 5). Let u be the longitudinal deviation of the beam at position x on the beam
(0 < x < 5). You know that the constants are such that this satisfies the equation utt = 4u xx . Suppose
x−
−
you know that the initial displacement of the beam is x505 , and the initial velocity is −(1005) in the
positive u direction. Set up the equation together with the boundary and initial conditions. Just set
up, do not solve.
Exercise 5.2.4: Suppose the beam is L units long, everything else kept the same as in (5.5). What
is the equation and the series solution.
Exercise 5.2.5: Suppose you have
a4 y xxxx + ytt = 0 (0 < x < 1, t > 0),
y(0, t) = y xx (0, t) = 0,
y(1, t) = y xx (1, t) = 0,
y( x, 0) = f ( x), yt ( x, 0) = g( x).
That is, you have also an initial velocity. Find a series solution. Hint: Use the same idea as we did
for the wave equation. 222 5.3 CHAPTER 5. EIGENVALUE PROBLEMS Steady periodic solutions Note: 1–2 lectures, §10.3 in [EP].
y
y
0 L x Figure 5.3: Vibrating string. The problem is governed by the equations
ytt = a2 y xx ,
y(0, t) = 0,
y(L, t) = 0,
y( x, 0) = f ( x), yt ( x, 0) = g( x). (5.6) We saw previously that the solution is of the form
∞ y= An cos
n=1 nπa
nπ
nπa
t + Bn sin
t sin
x
L
L
L where An and Bn were determined by the initial conditions. The natural frequencies of the system
π
are the (circular) frequencies nLa for integers n ≥0 cos(ωt) as force per unit mass. Then our wave equation becomes (remember
force is mass times acceleration)
ytt = a2 y xx + F0 cos(ωt).
with the same boundary conditions of course. (5.7) 5.3. STEADY PERIODIC SOLUTIONS 223 We will want to find the solution here that satisfies the above equation and
y(0, t) = 0, y(L, t) = 0, y( x, 0) = 0, yt ( x, 0) = 0. (5.8) That is, the string is initially at rest. First we find a particular solution y p of (5.7) that satisfies
y(0, t) = y(L, t) = 0. We define the functions f and g as
f ( x) = −y p ( x, 0), g( x) = − ∂y p
( x, 0).
∂t We then find solution yc of (5.6). If we add the two solutions, we find that y = yc + y p solves (5.7)
with the initial conditions.
Exercise 5.3.1: Check that y = yc + y p solves (5.7) and the side conditions (5.8).
So the big issue here is to find the particular solution y p . We look at the equation and we make
an educated guess
y p ( x, t) = X ( x) cos(ωt).
We plug in to get
−ω2 X cos(ωt) = a2 X cos(ωt) + F0 cos(ωt)
or −ω2 X = a2 X + F0 after canceling the cosine. We know how to find a general solution to
this equation (it is an nonhomogeneous constant coefficient equation) and we get that the general
solution is
ω
ω
F0
X ( x) = A cos
x + B sin
x − 2.
a
a
ω
The endpoint conditions imply that X (0) = X (L) = 0, so
0 = X (0) = A −
or A = F0
ω2 F0
ω2 and F0
ωL
ωL
F0
cos
+ B sin
− 2.
2
ω
a
a
ω
ωL
Assuming that sin( a ) is not zero we can solve for B to get
0 = X ( L) = B=
Therefore,
F0
X ( x) = 2
ω −F0 cos
ω2 sin ωL
a
ωL
a −1 . cos ωL − 1 ω
ω
a cos x−
sin
x − 1 . ωL
a
a
sin a (5.9) 224 CHAPTER 5. EIGENVALUE PROBLEMS The particular solution y p we are looking for is
F0
y p ( x, t ) = 2
ω cos ωL − 1 ω
ω
a cos x−
sin
x − 1 cos(ωt). ωL
a
a
sin a Exercise 5.3.2: Check that y p works.
Now we get to the point that we skipped. Suppose that sin( ωL ) = 0. What this means is that ω is
a
equal to one of the natural frequencies of the system, i.e. a multiple of πLa . We notice that if ω is not
equal to a multiple of the base frequency, but is very close, then the coefficient B in (5.9) seems
π
to become very large. But let us not jump to conclusions just yet. When ω = nLa for n even, then
ωL
cos( a ) = 1 and hence we really get that B = 0. So resonance occurs only when both cos( ωL ) = −1
a
π
and sin( ωL ) = 0. That is when ω = nLa for odd n.
a
We could again solve for the resonance solution if we wanted to, but it is, in the right sense, the
limit of the solutions as ω† ) 5.3.1: Let us do the computation for specific values. Suppose F0 = 1 and ω = 1 and
L = 1 and a = 1. Then
y p ( x, t) = cos( x) − cos(1) − 1
sin( x) − 1 cos(t).
sin(1) Call B = cos(1)−1 for simplicity.
sin(1)
Then plug in t = 0 to get
f ( x) = −y p ( x, 0) = − cos x + B sin x + 1,
and after differentiating in t we see that g( x) = −
† ∂y p
( x, 0)
∂t = 0. Mythbusters, episode 31, Discovery Channel, originally aired may 18th 2005. 5.3. STEADY PERIODIC SOLUTIONS 225 Hence to find yc we need to solve the problem
ytt = y xx ,
y(0, t) = 0, y(1, t) = 0,
y( x, 0) = − cos x + B sin x + 1,
yt () = F ( x + t) + F ( x − t)
cos(1) − 1
+ cos( x) −
sin( x) − 1 cos(t).
2
sin(1)
0
0.0 (5.10) t 1
2 0.2 3
4 x 5 0.5 y(x,t) 0.8
0.20
1.0
0.20 0.10 0.10 y y 0.00 0.00 -0.10 -0.10 0.240
0.148
0.099
0.049
0.000
-0.049
-0.099
-0.148
-0.197
-0.254 -0.20
0.0 -0.20
0.2
0.5 0 x 1
2 0.8
3
t Figure 5.4: Plot of y( x, t) = 4 1.0
5 F ( x+t)+F ( x−t)
2 + cos( x) − cos(1)−1
sin(1) sin( x) − 1 cos(t). It is not hard to compute specific values for an odd extension of a function and hence (5.10) is a
wonderful solution to the problem. For example it is very easy to have a computer do it, unlike a
series solution. A plot is given in Figure 5.4. 226 5.3.2 CHAPTER 5. EIGENVALUE PROBLEMS Underground temperature oscillations Let u( x, t) be the temperature at a certain location at depth x underground at time t. See Figure 5.5. depth x Figure 5.5: Underground temperature.
The temperature u satisfies the heat equation ut = ku xx , where k is the diffusivity of the soil. We
know the temperature at the surface u(0, t) from weather records. Let us assume for simplicity that
u(0, t) = T 0 + A0 cos(ωt).
For some base temperature T 0 , then t = 0 is midsummer (could put negative sign above to make it
midwinter). A0 is picked properly to make this the typical variation for the year. That is, the hottest
temperature is T 0 + A0 and the coldest is T 0 − A0 . For simplicity, we will assume that T 0 = 0. ω is
picked depending on the units of t, such that when t = 1year, then ωt = 2π.
It seems reasonable that the temperature at depth x will also oscillate with the same frequency.
And this in fact will be the steady periodic solution, independent of the initial conditions. So we are
looking for a solution of the form
u( x, t) = V ( x) cos(ωt) + W ( x) sin(ωt).
for the problem
ut = ku xx , u(0, t) = A0 cos(ωt). (5.11) We will employ the complex exponential here to make calculations simpler. Suppose we have a
complex valued function
h( x, t) = X ( x) eiωt .
We will look for an h such that Re h = u. To find an h, whose real part satisfies (5.11), we look for
an h such that
ht = kh xx ,
h(0, t) = A0 eiωt .
(5.12)
Exercise 5.3.3: Suppose h satisfies (5.12). Use Euler’s formula for the complex exponential to
check that u = Re h satisfies (5.11). 5.3. STEADY PERIODIC SOLUTIONS
Substitute h into (5.12). 227 iωXeiωt = kX eiωt . Hence,
kX − iωX = 0,
or
X − α 2 X = 0,
√
ω
√
where α = ± ik . Note that ± i = ± 1+2i so you could simplify to α = ±(1 + i)
general solution is
√ω
√ω
X ( x) = Ae−(1+i) 2k x + Be(1+i) 2k x . ω
.
2k Hence the We assume that an X ( x) that solves the problem must be bounded as x → ∞ since u( x, t) should
be bounded (we are not worrying about the earth core!). If you use Euler’s formula to expand the
complex exponentials, you will note that the second term will be unbounded (if B 0), while the
first term is always bounded. Hence B = 0.
√ω
(1+i) 2k x
Exercise 5.3.4: Use Euler’s formula to show that e
will be unbounded as x → ∞, while
√ω
−(1+i) 2k x
e
will be bounded as x → ∞.
Furthermore, X (0) = A0 since h(0, t) = A0 eiωt . Thus A = A0 . This means that
√ω
√ω
√ω
√ω
h( x, t) = A0 e−(1+i) 2k x eiωt = A0 e−(1+i) 2k x+iωt = A0 e− 2k x ei(ωt− 2k x) .
We will need to get the real part of h, so we apply Euler’s formula to get
h( x, t) = A0 e − √ω
2k x cos ωt − Then finally
u( x, t) = Re h( x, t) = A0 e− ω
x + i sin ωt −
2k
√ω
2k x cos ωt − ω
x.
2k ω
x,
2k Yay!
ω
Notice the phase is different at different depths. At depth x the phase is delayed by x 2k .
For example in cgs units (centimeters-grams-seconds) we have k = 0.005 (typical value for soil),
π
2π
ω
ω = seconds2in a year = 31,557,341 ≈ 1.99 × 10−7 . Then if we compute where the phase shift x 2k = π.
√ω
The amplitude of the temperature swings is A0 e− 2k x . This decays very quickly as x grows. Let us
again take typical parameters as above. We also will assume that our surface temperature swing is 228 CHAPTER 5. EIGENVALUE PROBLEMS ±15◦ Celsius, that is, A0 = 15. Then the maximum temperature variation at 700 centimeters is only
±0.66◦ Celsius.
You need not dig very deep to get an effective “refrigerator.”. There is also the earth core, so
temperature presumably gets higher the deeper you dig. We did not take that into account above. 5.3.3 Exercises Exercise 5.3.5: Suppose that the forcing function for the vibrating string is F0 sin(ωt). Derive the
particular solution y p .
Exercise 5.3.6: Take the forced vibrating string. Suppose that L = 1, a = 1. Suppose that the
forcing function is the square wave that is 1 on the interval 0 < x < 1 and −1 on the interval
−1 < x < 0. Find the particular solution. Hint: You may want to use result of Exercise 5.3.5.
Exercise 5.3.7: The units are cgs (centimeters-grams-seconds). For k = 0.005, ω = 1.991 × 10−7 ,
A0 = 20. Find the depth at which the temperature variation is half (±10 degrees) of what it is on the
surface.
Exercise 5.3.8: Derive the solution for underground temperature oscillation without assuming that
T 0 = 0. Chapter 6
The Laplace transform
6.1 The Laplace transform Note: 2 lectures, §10.1 in [EP] 6.1.1 The transform In this chapter we will discuss the Laplace transform is also useful in the
analysis of certain systems such as electrical circuits, NMR spectroscopy, signal processing and
others.
mx (t) + cx (t) + kx(t) = f (t).
We can think of t as time and f (t) as incoming signal. The Laplace transform will convert the
equation from a differential equation in time to an algebraic (no derivatives) equation, where the
new independent variable s is the frequency.
We can think of the Laplace transform as a black box. It eats functions and spits out functions
in a new variable. We write L{ f (t)} = F ( s). It is common to write lower case letters for functions
in the time domain and upper case letters for functions in the frequency domain. We will use the
∗ Just like the Laplace equation and the Laplacian, the Laplace transform is also named after Pierre-Simon, marquis
de Laplace (1749 – 1827). 229 230 CHAPTER 6. THE LAPLACE TRANSFORM same letter to denote that one function is the Laplace transform of the other, for example F ( s) is the
Laplace transform of f (t). Let us define the transform.
∞ def L{ f (t)} = F ( s) = e− st f (t) dt.
0 We note that we are only considering t ≥ 0 in the transform. Of course, if we think of t as time there
is no problem, we are generally interested in finding out what will happen in the future (Laplace
transform is one place where it is safe to ignore the past). Let us compute the simplest transforms.
Example 6.1.1: Suppose f (t) = 1, then
∞ L{1} = e− st dt =
0 e− st
−s ∞
t =0 1
=.
s Of course, the limit only exists if s > 0. So L{1} is only defined for s > 0.
Example 6.1.2: Suppose f (t) = e−at , then
∞ L{e } =
−at ∞
− st −at ee dt = 0 −( s+a)t e
0 e−( s+a)t
dt =
−( s + a) ∞ =
t =0 1
.
s+a Of course, the limit only exists if s + a > 0. So L{e−at } is only defined for s + a > 0.
Example 6.1.3: Suppose f (t) = t, then using integration by parts
∞ L{t} = e− st t dt
0
∞ −te− st
1
=
+
s t =0 s
∞
1 e− st
=0+
s − s t =0
1
= 2.
s ∞ e− st dt
0 Again, the limit only exists if s > 0.
Example 6.1.4: A common function is the unit step function, which is sometimes called the
Heaviside function† . This function is generally given as 0 if t < 0, u(t) = 1 if t ≥ 0. † The function is named after the English mathematician, engineer, and physicist Oliver Heaviside (1850–1925).
Only by coincidence is the function “heavy” on “one side.” 6.1. THE LAPLACE TRANSFORM 231 Let us find the Laplace transform of u(t − a), where a ≥ 0 is some constant. That is, the function
that is 0 for t < a and 1 for t ≥ a.
∞ L{u(t − a)} = ∞ e u(t − a) dt =
− st e 0 − st a e− st
dt =
−s ∞
t =a e−as
=
,
s where of course s > 0 (and a ≥ 0 as we said before).
By applying similar procedures we can compute the transforms of many elementary functions.
Many basic transforms are listed in Table 6.1.
f (t) L{ f (t)} C
t
t2
t3
tn
e−at
sin(ωt)
cos(ωt)
sinh(ωt)
cosh(ωt) C
s
1
s2
2
s3
6
s4
n!
sn+1
1
s +a
ω
s2 +ω2
s
s2 +ω2
ω
s2 −ω2
s
s2 −ω2
e−as
s u(t − a) Table 6.1: Some Laplace transforms (C , ω, and a are constants).
Exercise 6.1.1: Verify Table 6.1.
Since the transform is defined by an integral. We can use the linearity properties of the integral.
For example, suppose C is a constant, then
∞ L{C f (t)} = ∞ e− stC f (t) dt = C
0 e− st f (t) dt = C L{ f (t)}.
0 So we can “pull out” a constant out of the transform. Similarly we have linearity. Since linearity is
very important we state it as a theorem.
Theorem 6.1.1 (Linearity of the Laplace transform). Suppose that A, B, and C are constants, then
L{A f (t) + Bg(t)} = AL{ f (t)} + BL{g(t)},
and in particular
L{C f (t)} = C L{ f (t)}. 232 CHAPTER 6. THE LAPLACE TRANSFORM Exercise 6.1.2: Verify the theorem. That is, show that L{A f (t) + Bg(t)} = AL{ f (t)} + BL{g(t)}.
These rules together with Table 6.1 on the previous page make it easy to already find the Laplace
transform of a whole lot of functions already. It is a common mistake to think that Laplace transform
of a product is the product of the transforms. But in general
L{ f (t)g(t)} L{ f (t)}L{g(t)}. It must also be noted that not all functions have Laplace transform. For example, the function 1
t
2
does not have a Laplace transform as the integral diverges. Similarly tan t or et do not have Laplace
transforms. 6.1.2 Existence and uniqueness Let us consider in more detail when does the Laplace transform exist. First let us consider functions
of exponential order. f (t) is of exponential order as t goes to infinity if
| f (t)| ≤ Mect ,
for some constants M and c, for sufficiently large t (say for all t > t0 for some t0 ). The simplest way
to check this condition is to try and compute
lim t→∞ f (t)
.
ect If the limit exists and is finite (usually zero), then f (t) is of exponential order.
Exercise 6.1.3: Use L’Hopital’s rule from calculus to show that a polynomial is of exponential
order. Hint: Note that a sum of two exponential order functions is also of exponential order. Then
show that tn is of exponential order for any n.
For an exponential order function we have existence and uniqueness of the Laplace transform.
Theorem 6.1.2 (Existence). Let f (t) be continuous and of exponential order for a certain constant
c. Then F ( s) = L{ f (t)} is defined for all s > c.
You may have existence of the transform for other functions, that are not of exponential order,
but that will not relevant to us. Before dealing with uniqueness, let us also note that for exponential
order functions you also obtain that their Laplace transform decays at infinity:
lim F ( s) = 0. s→∞ Theorem 6.1.3 (Uniqueness). Let f (t) and g(t) be continuous and of exponential order. Suppose
that there exists a constant C, such that F ( s) = G( s) for all s > C. Then f (t) = g(t) for all t ≥ 0. 6.1. THE LAPLACE TRANSFORM 233 you can only conclude that f (t) = g(t) outside of discontinuities. For example,
the unit step function is sometimes defined using u(0) = 1 . This new step function, however, we
2
defined has the exact same Laplace transform as the one we defined earlier where u(0) = 1. 6.1.3 The inverse transform As we said, the Laplace transform will allow us to convert a differential equation into an algebraic
equation that we can solve. Once we do solve the algebraic equation in the frequency domain we
will want to get back to the time domain, as that is what we are really interested in. We, therefore,
need to also be able to get back. If we have a function F ( s), to be able to find f (t) such that
L{ f (t)} = F ( s), we need to first know if such a function is unique. It turns out we are in luck
by Theorem 6.1.3. So we can without fear make the following definition.
If F ( s) = L{ f (t)} for some function f (t). We define the inverse Laplace transform as
def L−1 {F ( s)} = f (t).
There is an integral formula for the inverse, but it is not as simple as the transform itself (requires
complex numbers). The best way to compute the inverse is to use the Table 6.1 on page 231.
1
Example 6.1.5: Take F ( s) = s+1 . Find the inverse Laplace transform.
We look at the table and we find L−1 1
= e−t .
s+1 We note that because the Laplace transform is linear, the inverse Laplace transform is also linear.
That is,
L−1 {AF ( s) + BG( s)} = AL−1 {F ( s)} + BL−1 {G( s)}.
We can of course also just pull out constants. Let us demonstrate how linearity is used by the
following example.
s
Example 6.1.6: Take F ( s) = s s+++1 . Find the inverse Laplace transform.
3s
First we use the method of partial fractions to write F in a form where we can use Table 6.1 on
page 231. We factor the denominator as s( s2 + 1) and write
2 s2 + s + 1 A Bs + C
= +2
.
s3 + s
s
s +1
Hence A( s2 − 1) + s( Bs + C ) = s2 + s + 1. Therefore, A + B = 1, C = 1, A = 1. In other words,
F ( s) = s2 + s + 1 1
1
= +2
.
s3 + s
s s +1 234 CHAPTER 6. THE LAPLACE TRANSFORM By linearity of Laplace transform (and thus of its inverse) we get that
−1 L 1
1
s2 + s + 1
= L −1
+ L−1 2
= 1 + sin t.
3+s
s
s
s +1 A useful property is the so-called shifting property or the first shifting property
L{e−at f (t)} = F ( s + a),
where F ( s) is the Laplace transform of f (t).
Exercise 6.1.4: Derive this property from the definition.
The shifting property can be used when the denominator is a more complicated quadratic that
may come up in the method of partial fractions. You always want to write such quadratics as
( s + a)2 + b by completing the square and then using the shifting property.
1
Example 6.1.7: Find L−1 s2 +4 s+8 .
First we complete the square to make the denominator ( s + 2)2 + 4. Next we find L−1 s2 1
1
= sin(2t).
+4
2 Putting it all together with the shifting property we find
L−1 s2 1
1
1
= L −1
= e−2t sin(2t).
2
+ 4s + 8
2
( s + 2) + 4 In general, we will want to be able to apply the Laplace transform to rational functions, that is
functions of the form
F ( s)
G ( s)
where F ( s) and G( s) are polynomials. Since normally (for functions that we are considering) the
Laplace transform goes to zero as s → ∞, it is not hard to see that the degree of F ( s) will always be
smaller than that of G( s). Such rational functions are called proper rational functions and we will
always be able to apply the method of partial fractions. Of course this means we will need to be
able to factor the denominator into linear and quadratic terms, which involves finding the roots of
the denominator. 6.1.4 Exercises Exercise 6.1.5: Find the Laplace transform of 3 + t5 + sin(πt).
Exercise 6.1.6: Find the Laplace transform of a + bt + ct2 for some constants a, b, and c. 6.1. THE LAPLACE TRANSFORM 235 Exercise 6.1.7: Find the Laplace transform of A cos(ωt) + B sin(ωt).
Exercise 6.1.8: Find the Laplace transform of cos2 (ωt).
Exercise 6.1.9: Find the inverse Laplace transform of 4
.
s2 −9 Exercise 6.1.10: Find the inverse Laplace transform of 2s
.
s 2 −1 Exercise 6.1.11: Find the inverse Laplace transform of 1
.
( s−1)2 ( s+1) t Exercise 6.1.12: Find the Laplace transform of f (t) = 0 if t ≥ 1,
if t < 1. 236 6.2 CHAPTER 6. THE LAPLACE TRANSFORM Transforms of derivatives and ODEs Note: 2 lectures, §7.2 –7.3 in [EP] 6.2.1 Transforms of derivatives Let us see how the Laplace transform is used for differential equations. First let us try to find
the Laplace transform of a function that is a derivative. That is, suppose g(t) is a continuous
differentiable function of exponential order.
∞ L {g (t)} = e− st g (t) dt = e− st g(t)
0 ∞
t =0 ∞ (− s) e− st g(t) dt = −g(0) + sL{g(t)}. −
0 We can keep doing.
f (t ) L{ f (t)} = F ( s) g (t)
g (t)
g (t) sG( s) − g(0)
s2G( s) − sg(0) − g (0)
s3G( s) − s2 g(0) − sg (0) − g (0) Table 6.2: Laplace transforms of derivatives (G( s) = L{g(t)} as usual).
Exercise 6.2.1: Verify Table 6.2. 6.2.2 Solving ODEs with the Laplace transform If you notice, the Laplace transform turns differentiation essentially into multiplication by s. Let us
see how to apply this to differential equations.
Example 6.2.1: Take the equation
x (t) + x(t) = cos(2t), x(0) = 0, x (0) = 1. We will take the Laplace transform of both sides. By X ( s) we will, as usual, denote the Laplace
transform of x(t).
L{ x (t) + x(t)} = L{cos(2t)},
s
s2 X ( s) − sx(0) − x (0) + X ( s) = 2
.
s +4 6.2. TRANSFORMS OF DERIVATIVES AND ODES 237 We can plug in the initial conditions now (this will make computations more streamlined) to obtain
s2 X ( s) − 1 + X ( s) = s2 s
.
+4 We now solve for X ( s),
X ( s) = ( s2 s
1
+2
.
2 + 4)
+ 1)( s
s +1 We use partial fractions (exercise) to write
X ( s) = 1s
1s
1
−
+2
.
2+1
2+4
3s
3s
s +1 Now take the inverse Laplace transform to obtain
x(t) = 1
1
cos(t) − cos(2t) + sin(t).
3
3 The procedure is as follows. You take an ordinary differential equation in the time variable
t. You apply the Laplace transform to transform the equation into an algebraic (non differential)
equation in the frequency domain. All the x(t), x (t), x (t), and so on, will be converted to X ( s),
sX ( s) − x(0), s2 X ( s) − sx(0) − x (0), and so on. If the differential equation we started with was
constant coefficient linear equation, it is generally pretty easy to solve for X ( s) and we will obtain
some expression for X ( s). Then taking the inverse transform if possible, we find x(t).
It should be noted that since not every function has a Laplace transform, not every equation can
be solved in this manner. 6.2.3 Using the Heaviside function Before we move on to more general functions than those we could solve before, we want to consider
the Heaviside function. See Figure 6.1 on the following page for the graph. 0 if t < 0, u(t) = 1 if t ≥ 0. This function is useful for putting together functions, or cutting functions off. Most commonly
it is used as u(t − a) for some constant a. This just shifts the graph to the right by a. That is, it is a
function that is zero when t < a and 1 when t ≥ a. Suppose for example that f (t) is a “signal” and
you started receiving the signal sin t at time t. The function f (t) should then be defined as 0 if t < π, f (t ) = sin t if t ≥ π. 238 CHAPTER 6. THE LAPLACE TRANSFORM
-1.0 -0.5 0.0 0.5 1.0 1.00 1.00 0.75 0.75 0.50 0.50 0.25 0.25 0.00 0.00 -1.0 -0.5 0.0 0.5 1.0 Figure 6.1: Plot of the Heaviside (unit step) function u(t). Using the Heaviside function, f (t) can be written as
f (t) = u(t − π) sin t.
Similarly the step function that is 1 on the interval [1, 2) and zero everywhere else can be written as
u(t − 1) − u(t − 2).
The Heaviside function is useful to define functions defined piecewise. If you want the function t on
when t is in [0, 1] and the function −t + 2 when t is in [1, 2] and zero otherwise, you can use the
expression
t u(t) − u(t − 1) + (−t + 2) u(t − 1) − u(t − 2) .
Hence it is useful to know how the Heaviside function interacts with the Laplace transform. We
have already seen that
e−as
L{u(t − a)} =
.
s
This can be generalized into a shifting property or second shifting property.
L{ f (t − a) u(t − a)} = e−as L{ f (t)}. (6.1) Example 6.2.2: Suppose that the forcing function is not periodic. For example, suppose that we
had a mass spring system
x (t) + x(t) = f (t), x(0) = 0, x (0) = 0, where f (t) = 1 if 1 ≤ t < 3 and zero otherwise. We could imagine a mass and spring system where
a rocket was fired for 2 seconds starting at t = 1. Or perhaps an RLC circuit, where the voltage was 6.2. TRANSFORMS OF DERIVATIVES AND ODES 239 being raised at a constant rate for 2 seconds starting at t = 1 and then held steady again starting at
t = 3.
We can write f (t) = u(t − 1) − u(t − 3). We transform the equation and we plug in the initial
conditions as before to obtain
e− s e−3 s
s2 X ( s) + X ( s) =
−
.
s
s
We solve for X ( s) to obtain
e− s
e−3 s
X ( s) =
−
.
s( s2 + 1) s( s2 + 1)
We leave it as an exercise to the reader to show that
1
= 1 − cos t.
+ 1) L −1
In other words L{1 − cos t} = 1
.
s( s2 +1) s( s2 So using (6.1) we find L−1 e− s
= e− s L{1 − cos t} = 1 − cos(t − 1) u(t − 1).
s( s2 + 1) L −1 e−3 s
= e−3 s L{1 − cos t} = 1 − cos(t − 3) u(t − 3).
s( s2 + 1) Similarly Hence, the solution is
x(t) = 1 − cos(t − 1) u(t − 1) − 1 − cos(t − 2) u(t − 2).
The plot of this solution is given in Figure 6.2 on the next page. 6.2.4 Transforms of integrals A feature of Laplace transforms is that it is also able to easily deal with integral equations. That is,
equations in which integrals rather than derivatives of functions appear. The basic property, which
can be proved by applying the definition and again doing integration by parts, is the following.
t f (τ) dτ = L
0 1
F ( s).
s It is sometimes useful for computing the inverse transform to write
t f (τ) dτ = L−1
0 1
F ( s) .
s 240 CHAPTER 6. THE LAPLACE TRANSFORM
0 5 10 15 20 2 2 1 1 0 0 -1 -1 -2 -2
0 5 10 15 20 Figure 6.2: Plot of x(t). Example 6.2.3: To compute the inverse transform of
integration rule.
L −1 11
=
s s2 + 1 t 1
2+1
s L−1
0 1
s( s2 +1) we could proceed by applying this
t dτ = sin τ dτ = 1 − cos t.
0 Example 6.2.4: If an equation contains an integral of the unknown function the equation is called
an integral equation. For example, take the equation
t t2 = eτ x(τ) dτ. 0 If we apply the Laplace transform we obtain (where X ( s) = L{ x(t)})
1
2
1
= L{et x(t)} = X ( s − 1).
3
s
s
s
Thus
X ( s − 1) = 2
s2 or X ( s) = 2
.
( s + 1)2 We use the shifting property
x(t) = 2e−t t.
More complicated integral equations can also be solved using the convolution that we will learn
next. 6.2. TRANSFORMS OF DERIVATIVES AND ODES 6.2.5 241 Exercises Exercise 6.2.2: Using the Heaviside function write down the piecewise function that is 0 for t < 0,
t2 for t in [0, 1] and t for t > 1.
Exercise 6.2.3: Using the Laplace transform solve
mx + cx + kx = 0, x(0) = a, x (0) = b, where m > 0, c > 0, k > 0, and c2 − 4km > 0 (system is overdamped).
Exercise 6.2.4: Using the Laplace transform solve
mx + cx + kx = 0, x(0) = a, x (0) = b, where m > 0, c > 0, k > 0, and c2 − 4km < 0 (system is underdamped).
Exercise 6.2.5: Using the Laplace transform solve
mx + cx + kx = 0, x(0) = a, x (0) = b, where m > 0, c > 0, k > 0, and c2 = 4km (system is critically damped).
Exercise 6.2.6: Solve x + x = u(t − 1) for initial conditions x(0) = 0 and x (0) = 0.
Exercise 6.2.7: Show the differentiation of the transform property. Suppose L{ f (t)} = F ( s), then
show
L{−t f (t)} = F ( s).
Hint: Differentiate under the integral sign.
Exercise 6.2.8: Solve x + x = t3 u(t − 1) for initial conditions x(0) = 1 and x (0) = 0, x (0) = 0.
Exercise 6.2.9: Show the second shifting property: L{ f (t − a) u(t − a)} = e−as L{ f (t)}. 242 6.3 CHAPTER 6. THE LAPLACE TRANSFORM Convolution Note: 1 or 1.5 lectures, §7.2 in [EP] 6.3.1 The convolution We said that the Laplace transformation of a product is not the product of the transforms. All hope
is not lost however. We simply have to use a different type of a “product.” Take two functions f (t)
and g(t) defined for t ≥ 0. Define the convolution‡ of f (t) and g(t) as
t def ( f ∗ g)(t) = f (τ)g(t − τ) dτ. (6.2) 0 As you can see, the convolution of two functions of t is another function of t.
Example 6.3.1: Take f (t) = et and g(t) = t for t ≥ 0. Then
t ( f ∗ g)(t) = eτ (t − τ) dτ = et − t − 1. 0 To solve the integral we did one integration by parts.
Example 6.3.2: Take f (t) = sin(ωt) and g(t) = cos(ωt) for t ≥ 0. Then
t ( f ∗ g)(t) = sin(ωτ) cos ω(t − τ) dτ.
0 We will apply the identity
cos(θ) sin(ψ) = 1
sin(θ + ψ) − sin(θ − ψ) .
2 Hence,
t 1
sin(ωt) − sin(ωt − 2ωτ) dτ
02
t
1
1
=
τ sin(ωt) +
cos(2ωτ − ωt)
2
4ω
τ=0
1
= t sin(ωt).
2
Of course the formula only holds for t ≥ 0. We did assume that f and g are zero (or just not defined)
for negative t.
( f ∗ g)(t) = ∞ For those that have seen convolution defined before, you may have seen it defined as ( f ∗ g)(t) = −∞ f (τ)g(t − τ) dτ.
This definition agrees with (6.2) if you define f (t) and g(t) to be zero for t < 0. When discussing the Laplace transform
the definition we gave is sufficient. Convolution does occur in many other applications, however, where you may have
to use the more general definition with infinities.
‡ 6.3. CONVOLUTION 243 The convolution has many properties that make it behave like a product. Let c be a constant and
f , g, and h be functions then
f ∗ g = g ∗ f,
(c f ) ∗ g = f ∗ (cg) = c( f ∗ g),
( f ∗ g) ∗ h = f ∗ (g ∗ h).
The most interesting property for us, and the main result of this section is the following theorem.
Theorem 6.3.1. Let f (t) and g(t) be of exponential type, then
t L {( f ∗ g)(t)} = L f (τ)g(t − τ) dτ = L{ f (t)}L{g(t)}.
0 In other words, the Laplace transform of a convolution is the product of the Laplace transforms.
The simplest way to use this result is in reverse.
Example 6.3.3: Suppose we have the function of s defined by
1
11
=
.
( s + 1) s2 s + 1 s2
We recognize the two entries of Table 6.2. That is
L −1 1
= e−t
s+1 L −1 11
=
s + 1 s2 and Therefore, t L−1 1
= t.
s2 τe−(t−τ) dτ = e−t + t − 1. 0 The calculation of the integral involved an integration by parts. 6.3.2 Solving ODEs The next example will demonstrate the full power of the convolution and Laplace transform. We
will be able to give a solution to the forced oscillation problem for any forcing function as a definite
integral.
Example 6.3.4: Find the solution to
x + ω2 x = f (t),
0
for an arbitrary function f (t). x(0) = 0, x (0) = 0, 244 CHAPTER 6. THE LAPLACE TRANSFORM We first apply the Laplace transform to the equation. Denote the transform of x(t) by X ( s) and
the transform of f (t) by F ( s) as usual.
s2 X ( s) + ω2 X ( s) = F ( s),
0
or in other words
X ( s) = F ( s)
We know
L−1 1
sin(ω0 t)
.
=
2
ω0
+ ω0 s2 Therefore, t f (τ) x(t) =
0 or if we reverse the order t x(t) =
0 1
.
s2 + ω2
0 sin ω0 (t − τ)
dτ,
ω0 sin(ω0 t)
f (t − τ) dτ.
ω0 Let us notice one more thing with this example. We can now also notice how Laplace transform
handles resonance. Suppose that f (t) = cos(ω0 t). Then
t x(t) =
0 sin(ω0 τ)
1
cos ω0 (t − τ) dτ =
ω0
ω0 t cos(ω0 τ) sin ω0 (t − τ) dτ.
0 We have already computed the convolution of sine and cosine in Example 6.3.2. Hence
x(t) = 1
ω0 1
1
t sin(ω0 t) =
t sin(ω0 t).
2
2ω0 Note the t in front of the sine. This solution will, therefore, grow without bound as t gets large,
meaning we get resonance.
Using convolution you can also find a solution as a definite integral for arbitrary forcing function
f (t) for any constant coefficient equation. A definite integral is usually enough for most practical
purposes. It is usually not hard to numerically evaluate a definite integral. 6.3.3 Volterra integral equation A common integral equation is the Volterra integral equation§
t x(t) = f (t) + g(t − τ) x(τ) dτ,
0 § Named for the Italian mathematician Vito Volterra (1860 – 1940). 6.3. CONVOLUTION 245 where f (t) and g(t) are known functions and x(t) is an unknown we wish to solve for. To find x(t),
we apply the Laplace transform to the equation to obtain
X ( s) = F ( s) + G( s)X ( s),
where X ( s), F ( s), and G( s) are the Laplace transforms of x(t), f (t), and g(t) respectively. We find
F ( s)
.
1 − G( s) X ( s) = To find x(t) we now need to find the inverse Laplace transform of X ( s).
Example 6.3.5: Solve t x(t) = e−t + sinh(t − τ) x(τ) dτ.
0 We apply Laplace transform to obtain
X ( s) =
or
X ( s) = 1
s +1 1− 1
s2 −1 1
1
+2
X ( s),
s+1 s −1
= s−1
s
1
=2
−2
.
2−2
s
s −2 s −2 It is not hard to apply Table 6.1 on page 231 to find
√
√
1
x(t) = cosh( 2 t) − √ sinh( 2 t).
2 6.3.4 Exercises Exercise 6.3.1: Let f (t) = t2 for t ≥ 0, and g(t) = u(t − 1). Compute f ∗ g.
Exercise 6.3.2: Let f (t) = t for t ≥ 0, and g(t) = sin t for t ≥ 0. Compute f ∗ g.
Exercise 6.3.3: Find the solution to
mx + cx + kx = f (t), x(0) = 0, x (0) = 0, for an arbitrary function f (t), where m > 0, c > 0, k > 0, and c2 − 4km > 0 (system is overdamped).
Write the solution as a definite integral.
Exercise 6.3.4: Find the solution to
mx + cx + kx = f (t), x(0) = 0, x (0) = 0, for an arbitrary function f (t), where m > 0, c > 0, k > 0, and c2 − 4km < 0 (system is underdamped).
Write the solution as a definite integral. 246 CHAPTER 6. THE LAPLACE TRANSFORM Exercise 6.3.5: Find the solution to
mx + cx + kx = f (t), x(0) = 0, x (0) = 0, for an arbitrary function f (t), where m > 0, c > 0, k > 0, and c2 = 4km (system is critically
damped). Write the solution as a definite integral.
Exercise 6.3.6: Solve t x(t) = e−t + cos(t − τ) x(τ) dτ.
0 Exercise 6.3.7: Solve t x(t) = cos t + cos(t − τ) x(τ) dτ.
0 Further Reading
[BM] Paul W. Berg and James L. McGregor, Elementary Partial Differential Equations, HoldenDay, San Francisco, CA, 1966.
Hill, Inc., Princeton, NJ, 1994. [I] E.L. Ince, Ordinary Differential Equations, Dover Publications, Inc., New York, NY, 1956. 247 248 FURTHER READING Index
acceleration, 16
addition of matrices, 87
algebraic multiplicity, 119
amplitude, 65
angular frequency, 65
antiderivative, 14
antidifferentiate, 14
associated homogeneous equation, 70
atan2, 66
augmented matrix, 91
autonomous equation, 36
autonomous system, 85
beating, 77
Bernoulli equation, 33
boundary conditions for a PDE, 181
boundary value problem, 143
catenary, 11
Cauchy-Euler equation, 50
center, 107
cgs units, 227, 228
characteristic equation, 52
Chebychev’s equation of order 1, 50
cofactor, 90
cofactor expansion, 90
column vector, 87
commute, 89
complementary solution, 70
complete eigenvalue, 119
complex conjugate, 102
complex number, 53
complex roots, 54
constant coefficient, 51, 96 convolution, 242
corresponding eigenfunction, 144
cosine series, 170
critical point, 36
critically damped, 67
d’Alembert solution to the wave equation, 198
damped, 66
damped motion, 62
defect, 120
defective eigenvalue, 120
deficient matrix, 120
dependent variable, 7
determinant, 89
diagonal matrix, 111
matrix exponential of, 125
diagonalization, 126
differential equation, 7
direction field, 85
Dirichlet boundary conditions, 172, 211
Dirichlet problem, 205
displacement vector, 111
distance, 16
dot product, 88, 152
dynamic damping, 118
eigenfunction, 144, 212
eigenfunction decomposition, 211, 216
eigenvalue, 99, 212
eigenvalue of a boundary value problem, 144
eigenvector, 99
eigenvector decomposition, 133, 140
ellipses (vector field), 107
elliptic PDE, 181
249 250
endpoint problem, 143
envelope curves, 68
equilibrium solution, 36
Euler’s equation, 50
Euler’s equations, 56
Euler’s formula, 53
Euler’s method, 41
even function, 155, 168
even periodic extension, 168
existence and uniqueness, 20, 48, 57
exponential growth model, 9
exponential of a matrix, 124
exponential order, 232
extend periodically, 151
first order differential equation, 7
first order linear equation, 27
first order linear system of ODEs, 95
first order method, 42
first shifting property, 234
forced motion, 62
systems, 116
Fourier series, 153
fourth order method, 43
Fredholm alternative
simple case, 148
Sturm-Liouville problems, 215
free motion, 62
free variable, 93
fundamental matrix, 96
fundamental matrix solution, 96, 125
general solution, 10
generalized eigenvectors, 120, 122
Genius software, 5
geometric multiplicity, 119
Gibbs phenomenon, 158
half period, 160
harmonic function, 204
harvesting, 38 INDEX
heat equation, 181
Heaviside function, 230
Hermite’s equation of order 2, 50
homogeneous equation, 34
homogeneous linear equation, 47
homogeneous side conditions, 182
homogeneous system, 96
Hooke’s law, 62, 110
hyperbolic PDE, 181
identity matrix, 88
imaginary part, 54
implicit solution, 24
inconsistent system, 93
indefinite integral, 14
independent variable, 7
initial condition, 10
initial conditions for a PDE, 181
inner product, 88
inner product of functions, 153, 215
integral equation, 240, 244
integrate, 14
integrating factor, 27
integrating factor method, 27
systems, 131
inverse Laplace transform, 233
invertible matrix, 89
IODE
Lab I, 18
Lab II, 41
Project I, 18
Project II, 41
Project III, 57
Project IV, 160
Project V, 160
IODE software, 5
la vie, 72
Laplace equation, 181, 204
Laplace transform, 229
Laplacian, 204 INDEX
leading entry, 93
Leibniz notation, 15, 22
linear equation, 27, 47
linear first order system, 85
linear operator, 48, 70
linear PDE, 181
linearity of the Laplace transform, 231
linearly dependent, 57
linearly independent, 49, 57
logistic equation, 37
with harvesting, 38
mass matrix, 111
mathematical model, 9
mathematical solution, 9
matrix, 87
matrix exponential, 124
matrix inverse, 89
matrix valued function, 95
method of partial fractions, 233
Mixed boundary conditions, 211
mks units, 65, 69, 176
multiplication of complex numbers, 53
multiplicity, 60
multiplicity of an eigenvalue, 119
natural (angular) frequency, 65
natural frequency, 76, 113
natural mode of oscillation, 113
Neumann boundary conditions, 172, 211
Newton’s law of cooling, 31, 36
Newton’s second law, 62, 63, 84, 110
nilpotent, 126
normal mode of oscillation, 113
odd function, 155, 168
odd periodic extension, 168
ODE, 8
one-dimensional heat equation, 181
one-dimensional wave equation, 191
operator, 48 251
ordinary differential equation, 8
orthogonal
functions, 147, 153
vectors, 151
with respect to a weight, 214
orthogonality, 147
overdamped, 67
parabolic PDE, 181
parallelogram, 90
partial differential equation, 8, 181
particular solution, 10, 70
PDE, 8, 181
period, 65
periodic, 151
phase diagram, 37
phase portrait, 37, 86
phase shift, 65
Picard’s theorem, 20
piecewise continuous, 163
piecewise smooth, 163
practical resonance, 81, 180
practical resonance amplitude, 81
practical resonance frequency, 80
product of matrices, 88
projection, 153
proper rational function, 234
pseudo-frequency, 68
pure resonance, 78, 178
quadratic formula, 52
real part, 54
real world problem, 8
reduced row echelon form, 93
reduction of order method, 50
regular Sturm-Liouville problem, 213
repeated roots, 59
resonance, 78, 117, 178, 244
RLC circuit, 62
row vector, 87 252
saddle point, 106
sawtooth, 154
scalar, 87
scalar multiplication, 87
second order differential equation, 11
second order linear differential equation, 47
second order method, 42
second shifting property, 238
separable, 22
separation of variables, 182
shifting property, 234, 238
side conditions for a PDE, 181
simple harmonic motion, 65
sine series, 170
singular matrix, 89
singular solution, 24
sink, 105
slope field, 18
solution, 7
solution curve, 86
source, 105
spiral sink, 108
spiral source, 107
square wave, 81, 156
stable critical point, 36
stable node, 105
steady periodic solution, 80, 175
steady state temperature, 190, 204
stiffness matrix, 111
Sturm-Liouville problem, 212
superposition, 47, 57, 96, 182
symmetric matrix, 147, 151
system of differential equations, 83
tedious, 72, 73, 79, 136
thermal conductivity, 181
three mass system, 110
timbre, 220
trajectory, 86
transient solution, 80
transpose, 88 INDEX
trigonometric series, 153
undamped, 64
undamped motion, 62
systems, 110
underdamped, 68
undetermined coefficients, 71
for systems, 116
second order systems, 139
systems, 136
unforced motion, 62
unit step function, 230
unstable critical point, 36
unstable node, 105
variation of parameters, 73
systems, 138
vector, 87
vector field, 85
vector valued function, 95
velocity, 16
Volterra integral equation, 244
wave equation, 181, 191, 198
weight function, 214 ...
View Full Document
- Spring '08
- Staff
- Differential Equations, Equations, Elementary algebra, Partial differential equation
Click to edit the document details | https://www.coursehero.com/file/6717664/36632417-Differential-Equations/ | CC-MAIN-2018-05 | refinedweb | 74,829 | 82.65 |
What is Windows Virtual Shields for Arduino and What Can It Do?
This post is a general overview of the Windows Virtual Shields for Arduino library, one of the technologies being used in the World’s Largest Arduino Maker Challenge. If you have not heard about the contest, we have more information at the bottom of this post.
If you’ve used an Arduino, you’re familiar with the concept of a shield. Each shield has a specialized purpose (e.g. a temperature shield, an accelerometer shield), and building a device with multiple shields can be complex, costly, and space-inefficient. Now imagine that you can use a low-cost Windows Phone as a compact set of shields. Your Arduino sketch would be able to access hundreds of dollars worth of sensors and capabilities in your Windows Phone through easy-to-use library calls.
This is exactly what the Windows Virtual Shields for Arduino library enables for developers. And that’s not the best part. This technology works for all Windows 10 devices, so you can use the sensors and capabilities on your PC and Surface as well. Also, the Arduino can offload computationally expensive tasks like speech recognition and web parsing to the Windows 10 companion device!
Now let’s take a closer look at the technology. You can find the Windows Virtual Shields for Arduino library on our GitHub page – this is the library that will be included on your Arduino sketch. You will also need to install a Universal Windows Application on your Windows 10 companion device to help surface the sensors and capabilities. This application can be downloaded from the Microsoft Store. Additionally, the open-source code for the Store application can be found here.
You can control the following sensors and capabilities from an Arduino using the Windows Virtual Shields for Arduino library:
Sensors:
- Accelerometer
- Compass
- GPS
- Gyrometer
- Light Sensor
- Orientation
Capabilities:
- Screen
- Touch
- Camera
- Microphone
- Notifications
- SMS
- Speech-to-Text
- Speech Recognition
- Vibration
- Web
Let’s take look at a simple sample
Now that you know what the Windows Virtual Shields for Arduino is, let’s talk about how to use the library.
Quick setup
The full setup instructions can be found here. Briefly, the software setup includes:
- Downloading the Windows Virtual Shields for Arduino library from the Arduino Library Manager in the Arduino IDE.
- Downloading the Windows Virtual Shields for Arduino Store application on your Windows 10 companion device from here.
- Connecting your Arduino to your Windows 10 companion device with a USB, Bluetooth, or network connection.
- Writing and deploying your sketch on the Arduino IDE.
Hello Virtual Shields
A skeleton “Hello World” application using Windows Virtual Shields for Arduino looks like this:
#include <ArduinoJson.h> #include <VirtualShield.h> #include <Text.h> VirtualShield shield; // identify the shield Text screen = Text(shield); // connect the screen void setup() { shield.begin(); // begin communication screen.clear(); // clear the screen screen.print("Hello Virtual Shields"); } void loop() { }
As you can see, using a Virtual Shield is simple. In the sketch above, we include all necessary libraries and declare a VirtualShield object. We then declare a specific shield (Screen) object to represent the screen of the Windows 10 companion device in use. The program starts a serial communication, clears the screen of the Windows 10 companion device, and prints the line “Hello Virtual Shields” on the freshly cleared screen.
A glimpse at the architecture
Now that we’ve seen a simple sample, we can take a deeper dive into the architecture at play.
The communication between the Arduino library and the Microsoft Store app is done over a USB, Bluetooth, or network connection. The protocol uses JSON by making use of the efficient open-source library ArduinoJson. This is what a simple transaction looks like across the wire (Arduino on left, Windows 10 companion device on right):
This is a simplified illustration of the basic communication enabled by Windows Virtual Shields for Arduino.
A more complex sample with sensors
Let’s take a look at a more realistic example that includes sensors. All sensors in the Windows Virtual Shields for Arduino library have the four functions listed below:
- get – This function is a one-time data request to a sensor. An example would be reading acceleration values off of an accelerometer.
- start – The start function begins a series of get calls, performed at a specified interval. The interval could be determined by time (read accelerometer data every second) or value change (report if the acceleration changes by 1 unit).
- onChange – This function is exactly like start, except it does not report a data reading the first time it is called. It will begin reporting based on a chosen time interval or change in sensor reading.
- stop – This function ends a running start or onChange
Working with GPS
With a base knowledge of how sensors work in Windows Virtual Shields for Arduino, we can take a look at something more specific. The following sample will explore how to pull GPS readings from a Windows 10 device onto an Arduino.
The code for this example is seen below:
#include <ArduinoJson.h> #include <VirtualShield.h> #include <Text.h> #include <Geolocator.h> VirtualShield shield; Text screen = Text(shield); Geolocator gps = Geolocator(shield); void gpsEvent(ShieldEvent* shieldEvent) { // If there is a sensor error (errors are negative)... display message if (shieldEvent->resultId < 0) { screen.printAt(3, "Sensor doesn't exist"); screen.printAt(4, "or isn't turned on."); screen.printAt(6, "error: " + String(shieldEvent->resultId)); return; } String lat = String("Lat: ") + String(gps.Latitude); String lon = String("Lon: ") + String(gps.Longitude); screen.printAt(3, lat); screen.printAt(4, lon); } void setup() { shield.begin(); screen.clear(); screen.printAt(1, "Basic GPS Lookup"); gps.setOnEvent(gpsEvent); // Check GPS if reading changes by ~1/6 of a mile gps.start(0, 0.01); } void loop() { shield.checkSensors(); }
In setup, we initialize the gps.setOnEvent handler to call gpsEvent whenever a response is received. Then in loop, we start the GPS and call the function checkSensors. The call to checkSensors is required to start receiving responses and processing callbacks for any sensor or capability. Finally, the gpsEvent function prints latitude and longitude readings every time the GPS senses a shift greater than our specified delta (0.01 longitudinal/latitudinal degrees).
Here you can really start to see the power of Windows Virtual Shields for Arduino – it’s simple and easy to pull data from the Windows 10 companion device, and the device unifies a large collection of sensors and actuators that would otherwise be complex and costly.
A glimpse at the architecture
In the graphic below, we explore the underlying architecture of the GPS communication sample:
An end-to-end project
Now that we’ve seen how sensors and simple screen capabilities work with Windows Virtual Shields for Arduino, we can take a look at a more complete project.
Check out this simple Hackster.io project to see the library working in action.
A quick look at more complex capabilities
So we’ve sent text to a companion screen, and we know how to get sensor readings. That’s a good start! But we’ve just scratched the surface of what Windows Virtual Shields for Arduino is capable. In this section, we’ll take a brief glimpse at some of the more advanced capabilities that your Arduino can control on your Windows 10 companion device.
Graphics
Basic graphics instructions and events are handled the same as sensors. A rectangle instruction
(id = screen.fillRectangle(80,120,70,70, YELLOW)) would produce the following communication:
And pressing and releasing the rectangle on the Windows 10 companion device would send back events tied to id.
Speech
The speech functionality of Windows Virtual Shields for Arduino includes Text-to-Speech and Speech Recognition. Here we see another huge advantage of Windows Virtual Shields for Arduino – we can leverage the computational power and APIs of the Windows 10 companion device to enable speech scenarios.
Text-to-Speech is simple and can be initiated by a command such as speech.speak(“Hello World”). This particular command will make the Windows 10 companion device speak the words “Hello World”.
The Speech Recognition functionality returns an indexed list of choices. Issuing the request recognition.listenFor(“yes,no”) would return an event with where 1=”yes”, 2=”no”, or 0=unrecognized (negative values are error indicators). The event can also account for groupings, such as recognizing a variety of words (“yes”, “yeah”, “ok”) as the single option “yes”. Recognition can also handle open-text, but is limited to 100 characters due to the memory and buffer size of an Arduino.
Web
You can also use the web capability to retrieve a web page and parse it before returning a web event to Arduino. This is really useful, as most web pages are larger than the entire Arduino onboard memory. The parsing engine uses an abbreviated instruction set to fully parse a web page.
The following code retrieves a weather dump from NOAA as a JSON blob, then parses the JSON to retrieve the current weather.
String url = ""; String parsingInstructions = "J:location.areaDescription|&^J:time.startPeriodName[0]|&^J:data.weather[0]"; web.get(url, parsingInstructions);
The event returns “Redmond WA|This Afternoon|Chance Rain”. As with speech, Windows Virtual Shields for Arduino moves expensive tasks to the companion device, allowing for more free memory on the Arduino.
Where we want to expand Windows Virtual Shields for Arduino
Windows Virtual Shields for Arduino has already come so far, but there are many ways in which we could improve the technology further. The great part is, the library is open-source – any developer interested in expanding this technology is more than welcome. All of the code is available from our GitHub page.
Let’s take a look at three areas we would want to expand upon, if time were no obstacle!
- First, we would add even more sensors and capabilities. NFC would make an excellent addition – this would enable scenarios like unlocking a door with your phone or transferring NFC payments. Others desired sensors and capabilities include: an Iris scanner (e.g. on a Lumia 950 XL); FM radio control; and device geofencing (rather than using the GPS and coding it yourself on Arduino). Also, Cortana would make an excellent addition.
- Next, we could improve existing sensors and capabilities. For example, GPS returns a latitude, longitude, and altitude, and the sensor can be triggered on a settable delta. However, that delta is singular and applies to all properties equally. If you wanted to monitor a small change altitude, but not latitude or longitude – or ignore a large change in altitude (e.g. a tall building), then the sensor system would need more than one delta to monitor.
- A third option would be to expand the scope. The Universal Windows Application currently connects to only one device at a time. We can imagine scenarios where multiple Arduinos can connect to a single app, such as in a home control systems (e.g. self-registering heating ducts opening/closing depending upon where you are).
And of course, there are countless other ways in which this technology can evolve. Explore it yourself, and see what you can build!
The World’s Largest Arduino Maker Challenge
Now that you’ve learned the ins and outs of Windows Virtual Shields for Arduino, it’s time to put your newly-learned skills to the test. The World’s Largest Arduino Maker Challenge would be a great opportunity to make use of the library.
The competition’s title is no overstatement – with more than 3,000 participants and 1,000 submitted project ideas in just the preliminary phase, this is truly the World’s Largest Arduino Maker Challenge. The contest is brought to you by Microsoft, Hackster.io, Arduino, Adafruit, and Atmel.
The parameters of the contest are simple – participants must develop a Universal Windows Application (UWA) that interfaces with an Arduino using a connection. Windows Virtual Shields for Arduino and Windows Remote Arduino are two recommended ways of establishing this connection. Check out the contest site for more details.
We hope you take this opportunity to learn more about the library and submit something great for the World’s Largest Arduino Maker Challenge! We can’t wait to see what you make!
Written by Devin Valenciano (Program Manager) and Jim Gale (Principal Software Engineering Lead) from Windows and Devices Connected Everyday Things team
Updated June 28, 2018 7:45 am | https://blogs.windows.com/buildingapps/2016/01/27/what-is-windows-virtual-shields-for-arduino-and-what-can-it-do/ | CC-MAIN-2019-22 | refinedweb | 2,072 | 55.74 |
To expose custom data in a format that can be easily consumed by a .NET application, you can take any of the following routes:
Develop a made-to-measure XML schema for the data and build a .NET class around it.
Write a COM–based OLE DB provider.
Write a simple .NET data provider.
Architect and develop a full-fledged .NET data provider.
Where should you concentrate your efforts? Your answer depends on the nature of the data you are providing and the audience you expect to reach. Each approach has pros and cons, and choosing the one that best fits your data is—guess what—up to you!
XML lets you reach the same level of universality as OLE DB. In addition, XML is free from the problems that prevented OLE DB from becoming a recognized and widely accepted technology for data access and data sharing. XML is terrifically simple, capable of being read and authored by anyone and, last but not least, ubiquitous (that is, available on all platforms).
In .NET, you have at your disposal many classes and facilities for manipulating XML documents, from XmlReader to XmlDataDocument, and from XmlWriter to XPathNavigator. When you publish a basic XML schema, prospective clients can easily understand it, but bear in mind that using more advanced XML-related technologies could limit your potential audience. For example, the parser used to process your documents on a certain platform might not be updated to support XML schemas, namespaces, XPath, and so on.
In addition to using XML, your .NET applications have other ways to make data accessible and consumable. For example, you can use the classes in the System.Data namespace as a kind of super-array data structure. These classes include the DataTable class and the DataSet class. Serializing a DataSet object to XML output is particularly suitable in situations where interoperability is critical. It does not matter whether you persist data as XML to a file or remote it as a string in a SOAP packet. What does matter is that you serialize your data to XML, as discussed in Chapter 8. When the target of your data is another .NET application, what could be better than using a native .NET data structure such as DataTable?
To verify the practicality of this approach, let’s see it in action and write a class that grabs some directory information and then exposes it as XML. We’ll make available a DirectoryListing class that returns information about directories in a variety of formats including an XML string, an XML file, and a DataTable class.
The DirectoryListing class works like an in-memory version of the old faithful MS-DOS dir command. It collects most of the typical directory information including name, size, type, attributes, date and time of the last access, and user comments. The class considers all the files and subdirectories of a given path. The output is obtained in tabular format by using a DataTable object as well as by using an XML string or an XML file.
Like many other classes in the .NET Framework, the DirectoryListing class has two constructors, one of which is the default.
// Default class constructor public DirectoryListing() {
} // Ad-hoc class constructor public DirectoryListing(String path) { // Stores the path to work on m_path = path;} // Ad-hoc class constructor public DirectoryListing(String path) { // Stores the path to work on m_path = path;
}}
Aside from the constructors, the class has one property named Path and one method named Fill. The Fill method has several overloads so that it can deal with the various outputs. The Path property represents the file system path to the directory for which you are running the query. The class stores the path name into a private data member, which is read and written by using the property’s get and set accessors. The property defaults to the root of the C: drive.
private String m_path = "c:\\"; public String Path { get {return m_path;} set {m_path = value;} }
The Fill method triggers the process that retrieves directory and file information and serializes it into the specified output format. The method has four overloads, as shown here:
public String Fill() public String Fill(String path) public int Fill(String path, String filename) public int Fill(String path, DataTable dt)
The first two overloads return an XML string that represents the directory information. If no path is explicitly indicated, the method works for the path currently stored in the Path property. In terms of practical implementation, the first overload works as a special case of the second:
public String Fill() { return Fill(m_path); }
After the class ascertains that the specified path exists, it creates and populates two distinct DataTable objects, one for directory information and one for file information. Next, the two tables are added to a temporary DataSet object, and the corresponding XML representation is returned. This final step is necessary to automatically save the DataTable objects into a single XML stream. You can decide whether to use a temporary DataSet object; you can write down your own XML schema and your own serializer without resorting to the ADO.NET schema for DataSet objects.
public String Fill(String path) { // Make sure the path is correct if (!_VerifyPath(path)) return ""; //)); // Serialize to XML via a temporary DataSet object DataSet ds = new DataSet("DirectoryListing"); ds.Tables.Add(dt1); ds.Tables.Add(dt2); return ds.GetXml(); }
In the implementation of the DirectoryListing class, located in the DirectoryListing.cs sample file on the companion CD, the third overload of the Fill method writes the XML representation of the contents to a disk file:
public int Fill(String path, String filename) { // Make sure the path is correct if (!_VerifyPath(path)) return -1; //)); // Add the table to a temporary DataSet object DataSet ds = new DataSet("DirectoryListing"); ds.Tables.Add(dt1); ds.Tables.Add(dt2); // Serialize the DataSet to an XML stream StreamWriter sw = new StreamWriter(filename); ds.WriteXml(sw); sw.Close(); // Return the table row count return dt1.Rows.Count + dt2.Rows.Count; }
The Fill method returns the total number of rows added to the temporary DataSet object, including those representing a subdirectory and those representing a file. The layout of the final XML code looks like the following sample script:
<DirectoryListing> <Folder> <Name>My Apps</Name> <Size>0</Size> <Created>2001-09-05T11:28:18.8048560+02:00</Created> <Attributes>ReadOnly, Directory</Attributes> <Type><DIR></Type> <Comment>My favorite handcrafted applications</Comment> </Folder> <Folder> <Name>My Clients</Name> <Size>0</Size> <Created>2001-09-05T11:28:35.9795520+02:00</Created> <Attributes>ReadOnly, Directory</Attributes> <Type><DIR></Type> <Comment>Projects I'm taking over for some of my clients</Comment> </Folder> <Folder> <Name>My Lab</Name> <Size>0</Size> <Created>2001-09-05T11:28:44.8222672+02:00</Created> <Attributes>ReadOnly, Directory</Attributes> <Type><DIR></Type> <Comment>Results of genetic manipulation of source code</Comment> </Folder> <File> <Name>ToDo.txt</Name> <Size>449</Size> <Created>2001-11-07T17:07:09.6498992+01:00</Created> <Attributes>Archive</Attributes> <Type>Text Document</Type> <Comment /> </File> </DirectoryListing>
As you might have noticed, the XML schema uses a distinct tag name for information representing a directory and for information representing a file. The <Folder> tag is used for directories, and the <File> tag wraps file information. Using two tag names is based on the idea of using two separate tables, one named Folder and one named File. To keep the XML code as simple as possible, I deliberately did not return schema information. When you want to include schema information, modify the Fill method to make the DataSet object send out XML with the schema embedded:
StreamWriter sw = new StreamWriter(filename); ds.WriteXml(sw, XmlWriteMode.WriteSchema); sw.Close();
When the Fill method of the DirectoryListing class is used to get a unique DataTable object, the distinction between folders and files ceases to make sense. The following code shows how to implement the Fill method to retrieve a unique DataTable object:
public int Fill(String path, DataTable dt) { if (!_VerifyPath(path)) return -1; _PrepareDataTable("FolderItem", dt); DirectoryInfo dir = new DirectoryInfo(path); _FillDataTableDirectoryInfo(dt, dir); _FillDataTableFileInfo(dt, dir); return dt.Rows.Count; }
File and folder information are written to a new or existing DataTable object whose name is set as FolderItem. In our example, the method returns the number of rows found in the table at the end of the operation.
Now you have an example of the programming interface for a data container class. Let’s see how to create and manipulate data in memory using ADO.NET container objects.
A DataTable object is a sort of heterogeneous, multidimensional array with extra methods that facilitate data access and retrieval. Although you will likely use it to store data originating from a database, the DataTable object (and the DataSet object) is a general-purpose data container that simply holds data, no matter where that data originates. Like a database, the DataTable object knows how to index, filter, select, and sort its child rows. These functionalities are built into the code of the DataTable class and in no way rely on a back-end data source. (It is no accident that objects such as DataSet, DataTable, DataColumn, DataRow, and DataRelation belong to a super namespace such as System.Data and are not part of a provider-specific namespace such as System.Data.SqlClient and System.Data.OleDb.) The DataTable object is just a .NET class good at storing in memory any data that can be described as a table by using a collection of rows and columns, so don’t be too scared to use it to expose proprietary data or volatile information.
You create a new DataTable object by using one of its two constructors:
DataTable dt = new DataTable(); DataTable dt = new DataTable("NameOfTheTable");
At this point you have only an empty object with no columns or rows. Prior to adding rows, you must define the columns. The next listing demonstrates how to add the columns needed to properly represent directory and file information:
private void _AddColumnsToTable(DataTable dt) { DataColumn dc1 = new DataColumn(); dc1.DataType = typeof(String); dc1.ColumnName = "Name"; dt.Columns.Add(dc1); dc1 = new DataColumn(); dc1.DataType = typeof(int); dc1.ColumnName = "Size"; dt.Columns.Add(dc1); dc1 = new DataColumn(); dc1.DataType = typeof(DateTime); dc1.ColumnName = "Created"; dt.Columns.Add(dc1); dc1 = new DataColumn(); dc1.DataType = typeof(String); dc1.ColumnName = "Attributes"; dt.Columns.Add(dc1); dc1 = new DataColumn(); dc1.DataType = typeof(String); dc1.ColumnName = "Type"; dt.Columns.Add(dc1); dc1 = new DataColumn(); dc1.DataType = typeof(String); dc1.ColumnName = "Comment"; dt.Columns.Add(dc1); }
To add a column, you need to create a new instance of a DataColumn object and give it at least a data type and a name. You must also add the column object to the Columns collection of the DataTable object. During this process, all data pertaining to the column gets stored internally in the DataTable object. After the object is added, you can blissfully null it out or reassign to it a new instance of the DataColumn class.
A defined set of columns enables a table to accept and store rows of data. Rows are stored using the Rows collection. A DataRow object does not have a public constructor that clients can directly call. You must create rows by using the NewRow method of the DataTable object. The NewRow method takes care of mirroring the columns’ metadata into the newly created row object.
The following listing shows how to populate a given row with directory-specific information. The work is not adding and filling out the row but getting file system information for the specified directory name.
private void _FillDataTableDirectoryInfo(DataTable dt, DirectoryInfo dir) { // Loops through subdirectories foreach (DirectoryInfo d in dir.GetDirectories()) { DataRow dr = dt.NewRow(); dr["Name"] = d.Name; dr["Size"] = 0; dr["Comment"] = _ReadDirComment(d.FullName); dr["Created"] = d.CreationTime; dr["Type"] = "<DIR>"; dr["Attributes"] = d.Attributes.ToString(); dt.Rows.Add(dr); } }
The .NET Framework provides two powerful classes for identifying files and directories: DirectoryInfo and FileInfo. You find them in the System.IO namespace. The DirectoryInfo structure for the directory being searched is passed on to the helper method shown in the preceding code. This helper method loops internally through the array of subdirectories returned by the GetDirectories method. Each element in this array is another DirectoryInfo object. Accessing the standard properties of a directory is straightforward. The directory attributes are rendered by using an object of type FileAttributes, which is exposed via the Attributes property. Note that when you call a member of the FileAttributes class, the ToString method nicely translates bitwise enumeration values into readable and comma-separated strings such as "ReadOnly, System, Archive".
In the schema we designed for the table, some columns represent information that, although pertinent to the directory, is not natively exposed by the DirectoryInfo class. This information includes the size of the directory (intended as the recursive sum of the size of child files and subdirectories), the user comment, and the item type. Size and item type are specific to each file, so let’s set them to static text for directories. The user comment is directory-specific. It is not part of the DirectoryInfo interface because it originates from a local file named desktop.ini, which is not supported on all platforms where the .NET Framework is available.
The desktop.ini file is a configuration file that is resident in the folder to which its contents are applied. The desktop.ini file is not supported on all versions of Microsoft Windows 95 and Microsoft Windows NT 4. Nothing prevents you from creating a desktop.ini file in any folder on a Windows NT 4 machine, but the operating system won’t be giving the file the special meaning it has on machines running Microsoft Windows 98, Microsoft Windows 2000, or Microsoft Windows XP.
A desktop.ini file is a short text file that can contain a comment about the contents of the folder. It can also indicate a nonstandard icon for Microsoft Windows Explorer to use when rendering the contents of the folder. The Web-like shell available on Windows 98 and later systems attributes a special meaning to this file when the containing folder is marked read-only. When the folder is read-only, Explorer draws the folder with a custom icon. In addition, it uses the comment to display a tooltip when the mouse hovers over the folder in the shell view. (See Figure 10-1.)
The typical contents of a desktop.ini file are shown here:
[.ShellClassInfo] Infotip=Results of genetic manipulation of source codeIconFileChemistry.ico IconIndex=0
This file feature is broadly used in the Windows XP shell, which also provides a system dialog box for creating user comments without resorting to modifying desktop.ini files. Incidentally, in Windows XP, desktop.ini files are marked as system files. No method in the .NET Framework or in the Microsoft Win32 and Windows XP SDKs provides a function for extracting the description of a folder. Nevertheless, both in Windows 2000 and in Windows XP, you can display the Comment column in the shell view and know at a glance about the contents of a given folder. (See Figure 10-2.)
Desktop.ini is a plain old .INI file, and the entry we’re mainly interested in is Infotip. Getting at that information is as easy as reading some bytes from a text file: you use the private method _ReadDirComment. (The complete source code for DirectoryListing class is in DirectoryListing.cs, available on the companion CD.)
The .NET class that returns system information about a particular file is FileInfo. All files contained in a folder can be accessed by using the GetFiles method on the DirectoryInfo object, which represents the parent directory. The following code shows how to populate a table row associated with a file in the folder:
private void _FillDataTableFileInfo(DataTable dt, DirectoryInfo dir) { // Loops through files foreach (FileInfo f in dir.GetFiles()) { DataRow dr = dt.NewRow(); dr["Name"] = f.Name; dr["Size"] = f.Length; dr["Comment"] = ""; dr["Created"] = f.CreationTime; dr["Type"] = _ReadItemType(f.Extension); dr["Attributes"] = f.Attributes.ToString(); dt.Rows.Add(dr); } }
User comments are not supported for files through the desktop.ini interface. However, as long as you use an NTFS file system, you can associate extra streams with each file in the system and store comments and other normally invisible information there.
Both files and directories can have an extension, but the Windows shell uses file extensions to catalog files into classes. For example, all files with a .BMP extension belong to the same logical group and share the same shell settings such as the icon, context menu, tooltip, and Properties dialog box. Each class of files has a name and a description. Windows Explorer displays the description in the Type column. Can you get this setting information programmatically? You can when you access the system registry.
To get hold of the string displayed in the Type column, you first need to read the default value of the following key:
HKEY_CLASSES_ROOT\.bmp
Next you use that string to gain further access to the registry. Typically, the string you read is Paint.Picture. (This name is machine-specific.) The next access attempt reads the default value from the following:
HKEY_CLASSES_ROOT\Paint.Picture
The next code listing shows how to read the default value by using the .NET Registry class. You must import the namespace Microsoft.Win32.
private String _ReadItemType(String sFileExtension) { String strType = "File"; if (sFileExtension == "") return strType; // Open the .EXT key (i.e., .BMP) RegistryKey reg = Registry.ClassesRoot.OpenSubKey(sFileExtension); try { // Read the indexer key (i.e., Paint.Picture) String indexerKey = reg.GetValue(null).ToString(); reg.Close(); // Access the indexer key and read the value reg = Registry.ClassesRoot.OpenSubKey(indexerKey); strType = reg.GetValue(null).ToString(); reg.Close(); } catch {} return strType; }
At this point in the code, all pieces of the DirectoryListing jigsaw puzzle are in the right place. Now let’s see how DirectoryListing actually works.
You use the DirectoryListing class whenever you need to process or display groups of files. Let’s consider a Windows Forms application that selects and displays all files under a certain root folder. Figure 10-3 shows the final result.
When the Go button is clicked, the following code runs:
private void btnGo_Click(object sender, System.EventArgs e) { DirectoryListing dir = new DirectoryListing(); DataTable dt = new DataTable(); // Fill the table status.Text = String.Format("Loading from {0} ...", textBox1.Text); int nItems = dir.Fill(textBox1.Text, dt); if (nItems <0) { status.Text = String.Format("An error occurred accessing the path: {0}.", textBox1.Text); return; } status.Text = String.Format("{0} item(s) found.", nItems); // Shows the XML text textBox2.Text = dir.Fill(textBox1.Text); // Take care of the UI Form1.ActiveForm.Text = String.Format("DIR - {0}", dir.Path); dataGrid1.DataSource = dt.DefaultView; }
The Fill method takes the path name and populates a newly created DataTable object with the structure described in the preceding code. In addition to having a sophisticated programmable interface, a DataTable object is a valid source for data bound controls. The following line of code is all you need to populate the grid of Figure 10-3:
grid.DataSource = dt;
You can apply a mask to the rows and filter them based, say, on the file extension. To do that, you simply create a DataView object on top of the table. Any data bound application that builds views of working data is better off using DataView objects throughout, even when no row filter is actually needed. In light of this, the preceding line of code should be rewritten like this:
grid.DataSource = dt.DefaultView;
Creating a view based on the file extension is as easy as writing the following code. The strFilter variable contains any file spec string with wildcards (e.g., *.exe). Figure 10-4 shows how the sample application handles filtered views.
// Casting requires that you always use DataView objects to bind data DataView dv = (DataView) grid.DataSource; dv.RowFilter = "Name Like '" + strFilter + "'";
In ADO.NET, the DataSet object is the only object that can save file contents to XML. To render to XML only the subset of rows included in a given view, you have to create a temporary DataSet object filled with only the rows in the view. The following code demonstrates how to do this:
private String _DataViewToXml(DataView dv) { DataSet ds = new DataSet("DirectoryListing"); DataTable dt = dv.Table.Clone(); ds.Tables.Add(dt); foreach(DataRowView drv in dv) dt.ImportRow(drv.Row); return ds.GetXml(); }
You first clone the structure of the table behind the DataView object. You then add the new DataTable object to the DataSet object and fill it with all rows in the current view. The ImportRow method automatically creates a duplicate of the DataRow object.
The DirectoryListing class works as an extremely simple data adapter object and is independent of any database. Since the class exposes its data through either XML or a DataTable object, nothing prevents the data from being used over the Web in the context of an ASP.NET application. Figure 10-5 shows the class at work in an ASP.NET page.
You link the class to the page using the @ Assembly page directive and then use it as follows:
<%@ Assembly Src="DirectoryListing.cs" %>
public DataView CreateDataSource(String strDir) { DirectoryListing dir = new DirectoryListing(); DataTable dt = new DataTable(); dir.Fill(strDir, dt); return dt.DefaultView; }public DataView CreateDataSource(String strDir) { DirectoryListing dir = new DirectoryListing(); DataTable dt = new DataTable(); dir.Fill(strDir, dt); return dt.DefaultView; }
The full source code for the Windows Forms and Web Forms applications using the DirectoryListing class is available on the companion CD in the WinDirList and WebDirList folders, respectively.
Creating an ad-hoc .NET class and/or a customized XML schema is definitely the first and probably the simplest option to consider when you want to expose proprietary data to .NET applications. Depending on your target audience, a .NET-to-.NET solution might not be optimal, even when you base it on XML.
OLE DB providers are fully supported in .NET by the generic managed provider for OLE DB data sources. The managed provider works for .NET applications in much the same way ADO works for COM applications. The common model is shown in Figure 10-6.
The OLE DB .NET Data Provider is made of all data access classes having the OleDb prefix and defined in the System.Data.OleDb namespace. This managed provider takes advantage of COM Interop Services to connect to the specified OLE DB provider for a given data source. Any interaction between a .NET application and an OLE DB provider takes place outside the CLR because such an interaction is actually between a .NET module and a COM module.
The OLE DB .NET Data Provider provides a bridge that enables a .NET application to access data through the same channels as a Win32 COM application. It gives you immediate access to all the existing OLE DB providers and saves your current investments so that applications can continue to successfully call into existing OLE DB providers.
If you have to design a software mechanism to make proprietary data available to the widest possible audience, writing an OLE DB provider is a valuable approach. Although its overall design is fairly complex and it is strictly COM-based, the OLE DB provider still represents your only option for writing a single module to make the wrapped data accessible to all.
In terms of interoperability and overall simplicity, only XML can surpass OLE DB. OLE DB has in its favor, however, a more thorough representation of the capabilities of the data source than any you could design using XML data structures. XML is only about data description, whereas OLE DB is about a common API for accessing data. To write OLE DB providers, you can use the ATL classes available from Microsoft Visual Studio 6.
Although supported by .NET, OLE DB providers are no longer the preferred way to access data in the .NET platform. A different breed of components natively integrated in the .NET universe has taken their place: .NET data providers. | http://etutorials.org/Programming/Web+Solutions+based+on+ASP.NET+and+ADO.NET/Part+III+Interoperability/Exposing+Data+to+.NET+Applications/Exposing+Proprietary+Data/ | CC-MAIN-2017-22 | refinedweb | 4,015 | 57.67 |
A delegate in C# is simillar to a FUNCTION POINTER in C or C++. Delgate can be defind as an Object which contains the address of a method. Delegate is a reference type used to encapsulate a method with a speciific
- Type safe
- Object Oriented
- Secure..
Delegate have following properties
- Delegates are simillar to c++ function pointer but it is type safe in nature.
- Delegate allow method to pass as an argument.
- Delegate can be chained together.
- Multiple methods can be called on a single event.
Delegate is a type which safely encapsulates a method. The type of the delegate is defined by name of the delegate. Delegate does not care about class of the object that it references. Any object will do, only matters is objcet of that.Main Advantage Delegate is effective use of delegate increase performance of application.
Synatx of delegate
Step 1: Decleration
Delgate is getting declared here.
Modifer delegate return_type delegate_name ( [Parameter….])
Step 2: Instantitation
Object of delgate is getting created as passing method as argument
Delegate_name delg_object_name = new Delegate_name( method_name);
Here method_name signature must be same as of signature of delegate.
Step 3: Invocation
Delegate is getting called here.
Delg_object_name([parameter….]);
Delegate Example 1
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 namespace DelgateForNotes
6 {
7 class Program
8 {
9
10 public delegate int AddDelegate(int num1, int num2);
11 static void Main(string[] args)
12 {
13 AddDelegate funct1= new AddDelegate(Add);
14 int k=funct1(7,2);
15 Console.WriteLine(” Sumation = {0}”,k);
16 Console.Read();
17 }
18 public static int Add(int num1, int num2)
19 {
20 Console.WriteLine(“I am called by Delegate”);
21 int sumation;
22 sumation= num1+ num2;
23 return sumation;
24 }
25 }
26 }
Output:
I am called by Delegate
Sumation =9
Purpose of above code is to calculate sum of two numbers . Add is a static function to compute sum of two integers. Signature of Add function is same as of signature of delegate. Here delegate is AddDelegate.
On Breaking the above code in steps
Step1:
1 using System;
2
3 using System.Collections.Generic;
4
5 using System.Linq;
6
7 using System.Text;
8
9 namespace MulticastDelegate1
10
11 {
12
13 class Program
14 {
15
16 public delegate void showDelegate(string s);
17 static void Main(string[] args)
18 {
19
20 showDelegate s = Display;
21 s += Show;
22 s(“Hello”);
23 s(“Scott”);
24 Console.Read();
25 }
26
27 public static void Display(string title)
28 {
29 Console.WriteLine(title);
30 }
31
32 public static void Show(string title)
33 {
34 Console.WriteLine(title);
35 }
36 }
37 }
Hello
Hello
Scott
Scott
In above example showDelegate is a delegate , which can refer any method having return type void and one string as parameter. There are two static user defind functions called Display and Show .
Multicast Delegate Example 2
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace MulticastDelegate
7 {
8 class MathOperation
9
10 {
11 public static void MultiplyByTwo(double d)
12 {
13
14 double res = d*2;
15 Console.WriteLine(“Multiply: “+res.ToString());
16 }
17
18 public static void Squre(double e)
19 {
20 double res = e * e;
21 Console.WriteLine(“Square”+res.ToString());
22 }
23 }
24 class NewProgram
25 {
26 public delegate void del(double Qr);
27 static void Main()
28 {
29
30
31 del d = MathOperation.MultiplyByTwo;
32
33 d += MathOperation.Squre;
34
35 Display(d, 2.00);
36
37 Display(d, 9.9);
38
39
40 Console.ReadLine();
41
42
43 }
44
45
46 static void Display(del action, double value)
47
48 {
49
50 Console.WriteLine(“Result = “+ value);
51 action(value);
52 }
53 }
54
The above code is implementing multicast delegate . In above code , there is a MathOperationClass , this class is containing two methods . one to double the input parameter and other to make squre of that.
public delegate void del(double Qr);
This is delegate decelaration . It will refer method having one double parameter and will return void.
Display function is taking delegate and double as parameter. This function is displaying the result and calling the delegate.
Happy Coding | https://debugmode.net/2009/12/04/delegate-in-c/ | CC-MAIN-2022-40 | refinedweb | 697 | 50.53 |
We’re running a developer contest this week centered around Twilio’s conference calling features, so I thought it would be helpful if I did a quick run through of the <Conference> verb.
Have Your People Call My People
The most straight-forward way of setting up conference calling is to drop all incoming calls into a conference using the <Conference> verb:
The name of the conference is namespaced to your account, so you can name it anything you like. Anyone dialing into “MyConference” for your account will be put in a conference room together.
We can spice up our conference room a bit using the waitUrl attribute. Set waitUrl to an audio file (like an MP3), and you can give your conference participants some music to listen to while they wait for the conference to start.
If you wanted to route incoming phone calls to different conference rooms based on something like their phone number, you would do:
If you wanted to mimic the popular conference calling solutions, you might want to ask that your participants enter a PIN before they’re allowed to join.
Reach Out and Call Somebody
Up until now, we’ve been handling incoming phone calls only. That is, people are only in a conference room if they dial into your Twilio phone number. Most conference systems you’ve worked with have been that model. Using Twilio’s REST API, having the conference call you is simple.
If you’ve got multiple conference calls going on, you can get a list of all the active ones:
If you wanted to get the call SIDs of the pariticpants you would add:
With the call SID of a participant, you can take fine-grained control and mute specific participants.
With all that under your belt, you’re all set to roll your own conference calling solution, or build something completely different. If you do, be sure to enter it into this week’s developer contest. You could win yourself an Amazon Kindle 3G, $100 in Twilio credit, and some awesome Twilio swag. Happy hacking! | https://www.twilio.com/blog/2011/07/easy-conference-calling-twilio.html | CC-MAIN-2018-22 | refinedweb | 347 | 55.58 |
java.lang.Object
java.lang.Threadjava.lang.Thread
PIRL.Conductor.Stream_LoggerPIRL.Conductor.Stream_Logger
public class Stream_Logger
A Stream_Logger is a Thread that is used to forward the lines read from an InputStream to one or more Writers.
Once started a Stream_Logger reads a line of input from its InputStream and then writes the line to each Writer in its list. Writers may be added or removed from the list at any time, before or after the start of the Stream_Logger. If no Writer has been bound to the Stream_Logger the input stream is still read and buffered.
Lines read are stored in a buffer up to an amount that may be changed at any time.
A Stream_Logger stops when an end of file or IOException has been encountered on its InputStream. However, it may be notified to end before reading the next line. It may also be notified to close if no input has arrived, but continue to the normal end of file (or IOException) if data has already arrived.
Thread
public static final String ID
public static final int DEFAULT_POLLING_INTERVAL
polling interval.
public static final int MINIMUM_BUFFER_SIZE
buffer size.
public static final int DEFAULT_BUFFER_SIZE
buffer size.
public Stream_Logger(String stream_name, InputStream input_stream, Writer writer)
The InputStream is wrapped in an InputStreamReader and a BufferedReader. The Writer, if not null, is the first entry in the Vector of log Writers.
Note: This Thread is marked as a
daemon so it does not need to finish before the user application
can exit.
stream_name- The name of the stream to prefix to each line logged along with a ": " separator. If null no line prefix is added.
input_stream- The InputStream to be read.
writer- A Writer to use for logging lines. If null, the Stream_Logger will not have any initial Writer.
IllegalArgumentException- If the input_stream is null.
public Stream_Logger(String stream_name, InputStream input_stream)
stream_name- The name of the stream to prepend to each line logged. This may be null.
input_stream- The InputStream to be read.
IllegalArgumentException- If the input_stream is null.
Stream_Logger(String, InputStream, Writer)
public boolean Add(Writer writer)
If the Writer is already in the list it is not added.
writer- The Writer to add.
Remove(Writer)
public boolean Remove(Writer writer)
writer- The Writer to remove.
Add(Writer)
public StringBuffer Buffer()
If the Stream_Logger is
running the contents of the
buffer will change if a new line arrives. Obviously, the buffer
returned should not be modified while the Stream_Logger is running.
N.B.: Synchronize on the buffer if necessary, though this will
block reading of further lines until the lock is released.
public Stream_Logger Buffer_Size(int size)
Note: The buffer size is never allowed to be less than the
MINIMUM_BUFFER_SIZE.
Warning: Do not call this method while sychronized on the buffer as this will result in a deadlock.
size- The maximum number of characters allowed in the buffer. If the buffer is currently larger than this amount whole lines will be removed from the front of the buffer to bring the content amount below the size.
public int Buffer_Size()
Buffer_Size(int)
public void Clear_Buffer()
Warning: Do not call this method while sychronized on the buffer as this will result in a deadlock.
public Stream_Logger Polling_Interval(long interval)
The polling interval is only used while waiting for data to arrive on the input stream. After that point blocking reads are used.
A short polling interval has the disadvantage of consuming more CPU cycles while waiting for data to arrive. This can have an adverse affect on system performance, especially if no data arrives for a long time.
A long polling interval has the disadvantage of introducing a delay up to the interval time between when data first arrives and input actually begins. This is generally not a problem if the delay is not so long as to interfere with data delivery downstream or cause data loss due to buffer overflow upstream.
interval- The amount of time to wait, in milliseconds, between tests to see if data has arrived. The minimum time is one millisecond. This initial default is
DEFAULT_POLLING_INTERVALmilliseconds.
public long Polling_Interval()
Polling_Interval(long)
public void run()
Each line of input
read from the
InputStream is written to each Writer in the Vector of Writers. Each
line written is prepended with the stream name followed by ": ",
unless no stream name was provided. The system's line ending
sequence, from the "line.separator" property, is appended to each
line written.
Each line read is also appended to the last-lines-read buffer. Only entire lines are buffered; lines that are too big to fit in the buffer are dropped. Lines, and only entire lines, are removed from the front of the buffer as needed to make room for new lines to be added at the end.
Logging continues until an end-of-file or IOException is encountered
on the InputStream, or the logger is told to
.
End
N.B.: If a Writer throws an IOException it is removed from the list of Writers.
runin interface
Runnable
runin class
Thread
public void End()
Logging ends before the next line is read, but after the current line has finished logging.
N.B.: Logging stops even if there may be more input available from the InputStream after the current line.
public void Close()
The input stream is initially polled for a ready condition (characters are available) before begining to read lines. This prevents the Stream_Logger from becoming blocked on input which will never arrive, thus allowing it to be externally halted. However, it may not be known if input has arrived or not.
If input has not arrived then the Stream_Logger is to stop polling
and
. If input has arrived then the
Stream_Logger is to continue reading until EOF or an IOException
occurs.
End | https://pirlwww.lpl.arizona.edu/software/PIRL_Java_Packages/PIRL/Conductor/Stream_Logger.html | CC-MAIN-2019-04 | refinedweb | 959 | 64.2 |
Thank you for your question. Please permit me to assist you with your concerns.To answer directly, you personally cannot change the locks until she formally abandons the premises, takes her things, and leaves. That is because she has as much right to be on the premises as you do, you can only take sole control of the premises once she has demonstrated intent to to return (which requires her to leave first). If you change the locks first, she could claim that you violated her rights to the premises, and she could sue you for damages (or use this against you in courts). Your property manager would not be the one who could be sued, so he has less of a right here than she would.As for your children, this is a bit more complicated. Legally the parents have exactly co-equal rights. Both have the right and the ability to make decisions but because rights are co-equal, neither parent compel or force the other parent to give up the children or grant visitation. That means that if she ends up blocking you from seeing your children, your only legitimate recourse would be to go to court and seek emergency sole custody or visitation rights because otherwise she can withhold them from you without violating the law. Hope that helps.
So on the locks what if she is already out but is moving her big stuff Wednesday does this matter?
On the kids does the same action apply to myself as the father? For example I picked them up from daycare and have them as we speak. Can she demand them and take them from our home or call the police on me and get me in trouble?
Mark,Thank you for your follow-up. In terms of the locks, if you can show that she intended to move (she took her personal items such as toiletries or her tooth brush), and she took her clothes but left the larger items, it can be argued that she constructively moved out. Then you could justify changing the locks, but it would be wiser to wait until she moves out completely.As for the kids, the same rights apply to you. If you want to withhold the kids from her and not give them to her, then you could do so as well. Then she would need to obtain an emergency order against you to obtain access or to take the kids from you. She can demand them but without a court order she has nothing. Furthermore, you aren't abducting the children so this isn't a criminal issue and the police would not help her.Good luck.
one last question on her moving out and changing the locks. Is she liable for any of the costs that she just up and left and we signed a 18 month lease just 3 weeks ago that both of us are on and responsible for? Thank you for your time.
Mark,Thank you for your follow-up. Regardless of whether or not she is on premises, if she is on the lease she remains liable to the landlord for the rents. In other words if you both signed, you both remains 'jointly and separately liable'. To make her laible to you for your share, you would need to go to court and request that the courts make her honor this agreement even if she no longer resides there.Good luck and). | http://www.justanswer.com/law/7szsz-wife-told-wants-divorce-just-tuesday.html | CC-MAIN-2015-35 | refinedweb | 581 | 78.28 |
Data Modeling
Introduction
Before diving into the document schemas, let’s take a look again at the mobile app. When you ran the mobile app in the previous lesson, you may remember two different options were presented on the login screen:
Sync mode: with the user credentials provided, this user can synchronize documents with Couchbase Server and, in turn, with other users.
Guest / Non Sync mode: no user credentials are required for this option. This is a local only mode. Documents created in the local database are not synchornized to the Sync Gateway.
Throughout the next lessons, you will be switching between those two modes to test different functionalities. It’s worth noting that the data model is slightly different between those two modes. Let’s review the data model for each one.
Sync mode
Here, the application communicates with Couchbase Server (via Sync Gateway). The documents stored in the Couchbase Server bucket have the following types:
airline
airport
hotel
route
user
Except for the user document (right on the diagram below), the rest of documents are static/semi-static in nature. In the demo app,
The
hoteland
airportdocuments are bundled into a prebuilt Couchbase Lite database and loaded when the app launches. We will discuss more about locating and using prebuilt databases in the Pre-built Database section of the tutorial.
The
airline,
airport,
hotel`and `routedocuments are NOT synchronized to the mobile app. Instead, they are fetched by the app via the REST webservices API exposed by the Travel Sample Web backend.
Guest / Non Sync mode
In guest mode, the mobile app creates a new database for the anonymous user. It is an empty database for storing the list of bookmarked hotels locally.
It is conceivable that in a real-world application, a user of the Travel Sample Mobile app may be interested in browsing for hotels in specific locations meeting specific search criteria without having to actually sign up. They could bookmark these hotels and later add them to their trip reservations. These bookmarked hotels could also be shared with other users, for instance with the user making the trip bookings.
In guest mode, the Couchbase Lite database hosts the following types of documents:
bookmarkedhotels
hotel
Document Types
Unlike tables, in Couchbase, all the documents are stored in the same namespace.
So you typically use an additional property to differentiate between each entity.
Let’s call it "type".
Try it out
Log into the "Admin Console" of Couchbase Server with same Administrator credentials you used during installation
Select the "buckets" option from menu on left
Click on "Documents" under the travel-sample bucket
Verify that the "type" property of the document is "hotel"
Document Key/ID
Every document in Couchbase is associated with a unique key that must be provided by the user when the document is created.
The key is the unique identifier of the document and can take any format.
However, it is recommended that you give it a value that provides some context about the contents of the document.
For instance, in the travel app data set, the document Key/ID is of the format
{doc.type}_{alphanumeric_string}.
Here
{doc.type} provides some context of the purpose of the document and in combination with the
{alphanumeric_string}, it uniquely identifies the string.
The document Key will be listed as “ID” on Couchbase Server admin console.
The key is also referred to as the Document ID.
Try it out
Log into the "Admin Console" of Couchbase Server with appropriate Administrator credentials you created during installation
Select the "buckets" option from the menu on the left
Click on "Documents" under the travel-sample bucket
Verify that the "callsign" property of the document is "AIRFRANS"
Document _id
When Sync Gateway processes a document, it adds relevant metadata to the document. The metadata includes an "_id" property that corresponds to the document ID. You will see this property if you query for the document via the Sync Gateway REST API.
{ "_id": "airline_137", "_rev": "1-b4e60280a1a0e3d46efad7bfd0e2068c", "callsign": "AIRFRANS", "country": "France", "iata": "AF", "icao": "AFR", "id": 137, "name": "Air France", "type": "airline" }
Mobile App Developers using Couchbase Lite should typically never have to directly read or write the
_id property.
You would query the
meta().id field to fetch the document ID.
We will learn more about this in the Query lesson. | https://docs.couchbase.com/tutorials/mobile-travel-sample/android/design/data-modeling.html | CC-MAIN-2020-40 | refinedweb | 722 | 51.68 |
Ever since Linq came out over 3? years ago (Earliest post about it that i have was from June 25 2008) I’ve been madly using it as much as I possibly could. I didn’t find it to be just some kind of syntactical sugar, or at least I learned it wasn’t eventually. Which? I don’t remember and really it doesn’t matter. Point is I’ve been a huge proponent of it and the various fun that came with. (Func, Action, anonymous types, ect) Now I had heard that it was based on functional programming but I had no real idea what that meant. It was just some kind of programming cultists and people with tin foil hats use. Let’s be honest, in the “Beer league” of programming, there was no respect for it.
Now flash forward a couple months ago when I went on a painful trek as I tried to find a language that could do more then what C# could handle. Far as I was concerned, I had out grown it. Like VGER (And Spock for that matter) I had outgrown the world of C# and needed something more even though I wasn’t sure what that something was. “It knows only that it needs, Commander. But, like so many of us… it does not know what.”
I thought I could find satisfaction in a new language even though I had failed before at that. I looked into Ruby, Scala, Python (Again), Boo, but something just didn’t take. It wasn’t long before I realized that they are ultimately like C#. Sure some are dynamic, some are intelligently typed, but in the end they were the same. It was just a question of how I liked the language to look, but not how things were done. Meet the new boss, same as the old boss.
It was at that point I decided to just put my shoulder down and start running toward the unknown. Toward a functional language. My first stop was F# and it was surprisingly amazing. I finally found a language that would make me keep up and not the other way around. I put a ton of time into it for 3 months, but stopped. It wasn’t the language itself, the functional design, or performance. It really came down to the half —ed implementation that The good professor Microsoft decided to eh… implement. File structure (Or literally lack thereof) was painful. It’s inability to use the built in MSTest UI was even worse. To add to that, the only way I could get a nice debug enabled testing framework was through Resharper and even then I’d have to run every test in an assembly before it would add it to the suite. Add in it’s failure to work with Entity Framework without a third party library, Power Pack and well FFFFFFFFFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU…
Ok… So I think you might get that I am a little bit mad about the situation. The reason isn’t that I’m trying to be an -ss but I REALLY LIKED F# AND THINK IT DESERVES BETTER THAN JUST TO BE SOME LAME -SS SIDE PROJECT.
I’ve learned this lesson before though and I just stopped bothering… at least three times until last Tuesday when I really, for really, not joking this time, quit F# for good. Yeah I’m not good at giving up on things.
Annoyed and looking for something to fill my need for functional languages, I decided to go all out. If I’m going to be functional (Programming functional not as in functional alcoholic) I’m doing it the full way. That’s right, I have turned to Lisp… just kidding. I am going full Haskell. Yes that language that is never talked about in name lest it release some demon or some weird looking dude when said three times in front of a mirror. That Haskell. Even before I knew what a functional language was, I had heard of it and was told to never look it in the eye and to keep on walking. I’m not sure why there is so much fear and secrecy around Haskell. I realize that, as the old cliche goes, people fear what they don’t understand, but the fear/hate people had for it seemed irrational. Like it was some kind of invading army hell bent on instilling some sort of dictatorship. I know I’m being a bit hyperbolic but the point is that people treated like it was a personal attack on programming. Like it’s existence was purely for insult and nothing else. Good thing I’m too dumb for my own good and ignored the warnings… it just took me four years to do so. (But in my defense, I hate quitting to a fault so I thought I should ride out the .Net stack.)
Now with this move it caused two problems: I had to take off the .Net training wheels and figure out how to even get Haskell to compile. The other was… How the –ck do I handle database oriented persistence? I mean for C# you have NHibernate, LLBLGEN, Subsonic, that entity thing… you get the point. There’s no shortage of ORMs for the .Net world. Tried to see if there was one for Haskell, but I started really thinking about this. One of the issues I had pondered with functional languages is how do you relate a database to objects if you aren’t really using an object oriented model. It’s quite a conundrum. (I spelled that right the first time.) I mean I’m sure you can force out some kind of object like model if given enough time, but was it really needed? To this I say no! (I think)
One of the concepts I’ve had to learn early on with functional programming is Tuples. Essentially a tuple is stuff bound together.
Could be a key value pair:
(“firstName”,”Sean”)
Could be a list of various strings grouped together:
[(“Sean”,”111 Cool Lane”,34),(“Andre”,”111 Stupid Street”,33)]
Point is, it’s stuff grouped in a like way. In fact, it has to be grouped in the same way. Take the one above for instance. It is a “list” of (string, string, integer). As long as anything added to it has the same signature, everything is great. If they don’t:
[(“Sean”, “111 Cool Lane”, 34), (1, “111 Stupid Street”, 33)]
Well… Kaboom. Now here’s the interesting part (One of many I hope): If you have a list of tuples and you squint real hard, you might mistake them for classes. After all, isn’t that what a class is? A bunch of stuff forced to be represented in a set way? If you think about it, this is basically how dynamic languages like Python or Javascript work. The “class” is just a bunch of key value pairs. You can call a property on an object like this:
something.DoStuff
Or you can do it like this:
something[“DoStuff”]
Yes it’s psuedo code and probably not 100% correctly represented, but that’s not the point. The point is that an object can be made of from key value pairs… Basically like the tuples above… and that’s where it gets really interesting.
I started to think about what would it take to represent a user. Say you have a plain user with Id, FirstName, and LastName. Well you could have a class:
public class User
{
public int Id {get; set;}
public string FirstName {get;set;}
public string LastName {get;set;}
}
Or you can have a tuple:
[(("FirstName","Sean"),("LastName","Isawesome"), ("Id", 1))]
Now here’s the funny part: I originally didn’t think the tuple representation was possible due to a possible type conflict. But sometimes in our most idiotic times there can emerge a real idea. The idea is simple:
WHY THE –CK DO WE SPEND SO MUCH TIME FORCING TYPES IF MOST OF THE TIME WE JUST NEED STRINGS!?!!
I know, it sounds odd at first but if you really think about it, does it matter if an Id is an integer? Sure in the database, but outside of it? Here’s a typical MVC round trip:
You take in a json string and turn part of it into an integer. You push that integer to a class (Model or other wise) and then use the class to transport that Id to be used as a string in a sql query or it gets converted to some other database happy type. It then is pulled back out of that database friendly type and pushed into an integer so it can hydrate a user class. Then the id is passed into a model so it can be turned into a string for html or json.
This begs the question:
WHY THE –CK DO WE SPEND SO MUCH TIME FORCING TYPES IF MOST OF THE TIME WE JUST NEED STRINGS!?!!
Think about and I mean really think about it. How often do things typed as integers (Or decimal or date or whatever the –ck you want) get used for anything but to be aimlessly typed and retyped? How often do any numbers get used for anything number related? In the world o’ web development there is very little use for numbers. Sure you might have to sum them up, but doesn’t it seem more logically to start as a string and only type when it’s needed as opposed to type something to anything but a string when all it ever will be used as is a string? It makes no –cking sense. None.
But maybe somewhere you might have to validate that the number falls within a certain range… GREAT! Convert to an integer and check!.
But maybe it has to be a proper date. –CKING GREAT CONVERT AND CHECK!
But, but what about when persisting to a database… THIS IS A GOOD REASON… eh to convert.
If there’s anything I’ve learned from the newfangled ideas of lean and such; it’s that you build only what you need. Don’t over complicate. Don’t over think. Don’t pass go and collect 200$. If there is no reason to type something as an integer, then why would you? Join the revolution. We can win this one or look like complete –sses while trying. I can’t promise which, but I can promise one will happen.
This is just the begining… | http://byatool.com/2011/12/ | CC-MAIN-2019-13 | refinedweb | 1,765 | 80.41 |
I'm trying to delay a part of my pipeline tool (which runs during the startup of Maya) to run after VRay has been registered.
I'm currently delaying the initialization of the tool in a userSetup.py like so:
def run_my_tool():
import my_tool
reload(my_tool)
mc.evalDeferred("run_my_tool()")
Uiron over at tech-artists.com showed me how to do this properly. Here's a link to the thread
Here's the post by uiron:
"don't pass the python code as string unless you have to. Wherever a python callback is accepted (that's not everywhere in Maya's api, but mostly everywhere), try one of these:
# notice that we're passing a function, not function call mc.scriptJob(runOnce=True, e=["idle", myObject.myMethod], permanent=True) mc.scriptJob(runOnce=True, e=["idle", myGlobalFunction], permanent=True) # when in doubt, wrap into temporary function; remember that in Python you can # declare functions anywhere in the code, even inside other functions open_file_path = '...' def idle_handler(*args): # here's where you solve the 'how to pass the argument into the handler' problem - # use variable from outer scope file_manip_open_fn(open_file_path) mc.scriptJob(runOnce=True, e=["idle", idle_handler], permanent=True)
" | https://codedump.io/share/ksxapQG2J7ww/1/maya-defer-a-script-until-after-vray-is-registered | CC-MAIN-2017-09 | refinedweb | 195 | 57.77 |
Creating Sum for a Group with Recursion in SSRS
Sum with scopeA colleague of mine from work was creating a report with Reporting Services 2005. He had a matrix report like the following:
=Sum(aggregate, “GroupName”)
The GroupName can be taken with a right click on your data region and then going to the Groups tab (and there also to the Details Grouping if you’re using a table).
The entire formula for the needed calculation would be:
= Sum(aggregate) / Sum(aggregate, “GroupName”)
Because, if otherwise specified, sum will calculates for the cell it’s in.
Scope exists, as the MSDN page states, for quite a few functions.
Sum with RecursionStill, I saw that there’s also a third option for Sum, and this one also included a recursive aggregation. Unfortunately enough, MSDN does not address recursion in its documentation for Reporting Services 2005 (though it already exists there), but only for Reporting Services 2008. So I thought maybe I should try and study it more thoroughly and see how it would work out in Reporting Services 2005 and 2008.
Sum Recursive Reporting Services 2005
I created a simple report with a table, based on Adventure Works DW with Employee dimension (which is a Parent Child Dimension). For the measure I’m going to summarize I used OrderQuantity from FactResellerSales. I’ve put the name of the employee on the details rows. I entered the definition of the table and under groups, entered “DetailsGroup”:
I gave the Parent Group the value of the ParentEmployeeKey and the EmployeeKey as the basic value to group on:
Now, as each employee has his own Order Quantity we can sum for each employee with the scope part of the sum, meaning: =Sum(Fields!OrderQuantity.Value, “table1_Details_Group”)
For each employee, if we want to see the sum for himself and all of those working under him, we use the recursive part of the sum function:For each employee, if we want to see the sum for himself and all of those working under him, we use the recursive part of the sum function:
= Sum(Fields!OrderQuantity.Value, “table1_Details_Group”, recursive)
I have also used right padding of: =level()*20 & “pt”
For the table’s Details Group I defined in it’s visibility:
Which all in all gives us:
Sum Recursive in Reporting Services 2008
I created the same report in SSRS 2008 with just a few alterations:
In the Tablix, you don’t go into the Tablix properties and define the Details group properties for them, as they are kept outside:
You define the grouping for the EmployeeKey in the general properties of the details group:
And the rest in the advanced tab for the recursive parent:
And for the group visibility I defined:
Also I had defined that the Indent property of the Full Name textbox will be again: =level()*20 & “pt”
The result obviously looks similar:
And that is how you can use Scope and recursion in Reporting Services functions.
Update January 20th 2010: I’m attaching my report in SSRS 2005 for your viewing pleasure: Sum Recursive
can put the sum in the bottom of the group insted of the top
Hi,
Well if we’re speaking in general, then I would say that you can add a total to a group before or after it in SSRS 2008. In SSRS 2005 I only saw the ability to add subtotals after the group.
Hope that helped,
Ella
Thanks for replay,
but I mean in the recursive grouping not normal grouping, because it seems that recursive grouping is forced on certain order
I need to make a recursive group that shows deepest levels in the group before the top level.
Hi,
Sorry for the late reply, I was sure I had already answered before…
In any case, as you are opening your parent to show his children (and not the other way around), I don’t think it’s possible for you to show the sum for a group at the bottom and not the top.
All the best,
Ella
Hi
Thanks for the explaining recurssion in reports so beautifully…It was very helpful…. But I have a small doubt suppose we have two table in a report having amount defined in one column,with the same recurssion behaviour. Is it possbile that we can do some calculations on the parent group amount that we get in both the tables and display it in a textbox or table…..
Thankyou…..
Hi Anup,
I’m terribly sorry, but I admit I didn’t manage to fully follow your question. In any case, I don’t see how we could show recursion in a textbox and not in a table.
All the best,
Ella
Thank you Ella, you solved my problem
Glad I could help 🙂
It’s a gud artical but i m facing problem to implement this technique in my report.so plz send me the steps if possible.
thnx in advance
Hi Ella,
your explanation for SSRS 2008 worked great. Thank you! I have only a (probably) simple design question:
Is it possible to move toggle buttons (those with + and -) to any other position then the one on far left?
Thanks,
Alexander
Hi Alexander,
I admit I don’t know that you can move the position of the toggle buttons through the UI for editing the group properties.
Perhaps (I’m not sure), you can do so through Report > Report Properties > Code Tab, if you’re interested in writing code for the subject.
All the best,
Ella
I’m trying to sum the grouped total in a tablix. Can you tell me how that is done? So for in your example, how would you sum the Total_Order_Quantity column in the tablix footer?
Thanks~
Hi Jason,
If you’d like to add a Total after all the rows, right click the detail part of that column, chose “Add Total” > “After”. That should do the job for you. You can check a webcast I did on how to build a basic report in Report Builder 2.0 .
Hope that helped,
Ella
Thanks for the tip and great webcast. I think my problem may be a group scope issue. I’m trying to get the sum of a groups value, which is not a sum of the column of the inner group. It’ just a value that is on every detail record called Total_Charges.
Total_Charges comes back with every detail record and I have two groups leading down to the details. I can show that single value in the total row of the first group, but for some reason it adds all the Total_Charges for the top group. So it’s adding it way too many times. I’ll keep messing with it, I’m sure I’ll get it.
Sorry I couldn’t help Jason…< ?xml:namespace prefix = oLast try though – maybe it’s a matter of a recursive sum in a matrix?
I’m sure we’ll all be happy to hear your end solution, so please come visit us again.
This is great. But, What if I wanted to include the details row where the visibility could be toggled to reveal the individual records that make up the sum? Is that possible?
Hi Matt,
I did try to do the same thing with a recursive sum and also detailed information which built that number, but didn’t succeed much. I have to admit, it also didn’t appeal to me as it made the report too detailed and long. Maybe instead you should give your users the report as I have described it above, and if they want the detail rows, you can send them with a click to a subreport which details the workers sales that made up the totals.
Hope that helped.
All the best,
Ella
Hi Ella;
Thanks for the greate post.
but i was wondering if i can aggregate Stephan orders and all of Stephen children orders.
this way you’ve posted only shows Stephen ordery himself. not with the sub-employees.
thanks a lot
Amin
Hi Amin,
If you review the post, you’ll see that though “Order Quantity Per Employee” gives just the total per employee, “Order Quantity Total” gives the total for the worker and all the employees that work under him.
All the best,
Ella
Hi Ella
Thanks for reply.
I dont know what is the expression for “Order Quantity Total”. could you please tell me what to do?
And may I have the whole Hierarchy from root to end?
We have only employees that have order themselves.
For Example:
-Root 0 1,000,000
-Employee1 0 100,000
+Employee1_1 1000 90,000
+Employee1_2 2000 10,000
-Employee2 500 1,500,000
-Employee2_1 1000 1,000,000
+Employee2_11 500,000 900,000
and so on…
Hi Amin,
I’ve attached my SSRS 2005 Recursive Sum Report.
Create a Reporting Services Project in the BIDS and give it a data source that connects to the Adventure Works DW DB.
Download my file an add it to the SSRS project. Give it the data source you created and then give the groups and formulas (Order Quantity Total) a look, according to what I wrote in the post.
Hope that helps.
All the best,
Ella
Hi Ella,
My requirement is to show the some of the data as normal and remaining data in drill down.
Example: I have a list of 50 suppliers and i have to show first 10 suppliers as normal and for remaining 40 supplier i have to show under drill down.
Please help
Regards,
Krishna
Hi Krishna,
I’m terribly sorry, but I don’t know of a way to do that in SSRS 2005.
Ella
Hi,
If you have already answered this question then i applogies.
I have created a report with a recursive group using a locations with a sub group which is an asset.
When the sub group is defined the recursive totals for location do not display, when the sub group is removed they display.
I was wondering (hoping) you have any thoughts or input.
Regards
Matt
Hi Matthew,
Recursion can only work on one attribute which is summed within itself.
For recursion to work, there should be only one parent child dimension with locations connected assets (in one attribute in one table).
If you’d like to have two nested totals for two different attributes, use the usual subtotal.
Hope that helped,
Ella
I have clints and parent clients, for every client there is an amount, I defined a group based on parentclient. I want to display groups sorted by total and clients in the group sorted as well by amount. it worked in rs2000: sort expresion containing sum recursive. but it does not work in rs2005.
Hi Djeff,
I’ve answered you under the same comment you posted at
All the best,
Ella
Hi Ella,
Could you please check above link and I think you could help me to do that.
Thanks.
Best Regards,
zombie
I tried to check the question, but didn’t understnd your code.
Hi Ella,
Good Post. I am running a problem here.
I want to add a sub group “Products” under the Sales.
But I couldn’t get the sum on sales and sale manager
For Example:
-Sale Manager1 3000 100,000
-Sales1 1000 90,000
-Sales2 2000 10,000
– Products1 1000 5,000
– Products2 500 5,000
As you see the I add a sub group under the Sales/Sales Manager Recursive Group. But I couldn’t get the total $ in Manager level.
Could you give me some advices
Hi Simon,
Did you define the parent of Product1 and Product2 to be Sales Manager1?
Otherwise, I can’t see the problem.
Hope that helped,
Ella
Hi Ella,
Sorry, I was on vacation last month.
No. the products only relate to Sales. You can think it is a sub group of sales.
Thanks,
Simon
Hi Simon,
I’m not completely following you. Try posting your question on:
All the best,
Ella
Simon,
I’m not following you. try posting a question on:
All the best,
Ella
Great article, very helpful for an SSRS n00b 🙂
One question: how can I get a recursive sum that only counts the children but not the parent?
You showed above how to get the sum for a manager AND all of those working under him, but how can I get it for only those working under him? Would I need to do some sort of subtotal?
Thanks!
Hi Adam,
I tried to think about it, if you can use perhaps “scope” to define what you want. Unfortunately enough, I don’t think you can create a sum just for the workers level. RS can only identify a jump in the level (and then a different sort of sum) when it identifies a parent. This is the only sort of sum available for this scenario. If you don’t want to use recursion and just a regular grouping, you need some sort of flag to show the change in the level of the group.
All the best,
Ella | http://blogs.microsoft.co.il/barbaro/2008/12/01/creating-sum-for-a-group-with-recursion-in-ssrs/ | CC-MAIN-2017-39 | refinedweb | 2,187 | 67.89 |
am i correct in assuming that when a computer behind a router with port forwarding opens a port (port 1337, when i run my server), that the router automatically notices and sets itself up to send all port 1337 traffic to that computer?
i've got two simple applications, a client and a server. Bound to 127.0.0.1, the client finds the server just fine, but bind the server to the local network address (172.16.0.2) and aim the outgoing connection at the router (public) ip (from whatismyip.com), and the router denies the connection.
i suspect i just need to somehow tell the router that my computer is using port 1337, and that it should forward incoming traffic instead of denying it... or of course i could be hopelessly wrong. anyone, ideas?
#server
import socket
myip = socket.gethostbyname(socket.gethostname())
port = 1337
sock = socket.socket()
sock.bind((myip, port))
sock.listen(5)
print sock.accept()[1]
and
#client
import socket
server = "71.62.9.147"
port = 5132
sock = socket.socket()
sock.connect((server, port))
print "connected" | https://www.daniweb.com/programming/software-development/threads/174664/python-server-port-forwarding-problem | CC-MAIN-2017-26 | refinedweb | 181 | 60.82 |
Hi all,
I am really a new with Python programming but managed so far. I am trying to update an image with Tkinter & Python. I found a program that does this but only after pressing the enter button. Now I am looking for a solution that not the enter key (line 9) must be pressed but that the program wait for 3 seconds and then update the image.
I tried to place the 'self.change.Img' without the button commands but that gives an error. I hope that someone can point me in the right directions.
Thanks for any help.
from tkinter import *
class Testi():
def __init__(self):
self.canvas = Canvas(root, width = 300, height = 100)
self.img = PhotoImage(file="2.png")
self.imgArea = self.canvas.create_image(0, 0, anchor = NW, image = self.img)
self.canvas.pack()
self.but1 = Button(root, text="press me", command=lambda: self.changeImg())
self.but1.place(x=10, y=500)
def changeImg(self):
self.img = PhotoImage(file="2.png")
self.canvas.itemconfig(self.imgArea, image = self.img)
root = Tk()
root.geometry("800x600")
app = Testi()
root.mainloop() | https://www.raspberrypi.org/forums/viewtopic.php?f=31&p=1272327&sid=76ca23285e966b86200047a60a51da28 | CC-MAIN-2018-43 | refinedweb | 181 | 62.44 |
Azure Event Hubs is a real-time, highly scalable, and fully managed data-stream ingestion service that can ingress millions of events per second and stream them through multiple applications. This lets you process and analyze massive amounts of data produced by your connected devices and applications.
Included in the many key scenarios for Event Hubs are long-term data archival and downstream micro-batch processing. Customers typically use compute or other homegrown solutions for archival or to prepare for batch processing tasks. These custom solutions involve significant overhead with regards to creating, scheduling and managing batch jobs. Why not have something out-of-the-box that solves this problem? Well, look no further – there’s now a great new feature called Event Hubs Archive!
Event Hubs Archive addresses these important requirements by archiving the data directly from Event Hubs to Azure storage as blobs. ‘Archive’ will manage all the compute and downstream processing required to pull data into Azure blob storage. This reduces your total cost of ownership, setup overhead, and management of custom jobs to do the same task, and lets you focus on your apps!
Benefits of Event Hub Archive
Simple setup
Extremely straightforward to configure your Event Hubs to take advantage of this feature.
Reduced total cost of ownership
Since Event Hubs handles all the management, there is minimal overhead involved in setting up your custom job processing mechanisms and tracking them.
Cohesive with your Azure Storage
By just choosing your Azure Storage account, Archive pulls the data from Event Hubs to your containers.
Near-Real time batch analytics
Archive data is available within minutes of ingress into Event Hubs. This enables most common scenarios of near-real time analytics without having to construct separate data pipelines.
A peek inside the Event Hubs Archive
Event Hubs Archive can be enabled in one of the following ways:
With just a click on the new Azure portal on an Event Hub in your namespace
Azure Resource Manager templates
Once the Archive is enabled for the Event Hub, you need to define the time and size windows for archiving.
The time window allows you to set the frequency with which the archival to Azure Blobs will happen. The frequency range is configurable from 60 – 900 seconds (1 - 15 minutes), both inclusive, with a granularity of 1 second. The default setting is 300 seconds (5 minutes).
The size window defines the amount of data built up in your Event Hub before an archival operation. The size range is configurable between 10MB – 500MB (10485760 – 524288000 bytes), both inclusive, at byte level granularity.
The archive operation will kick in when either the time or size window is exceeded. After time and size settings are set, the next step is configuring the destination which will be the storage account of your choosing.
That’s it! You’ll soon see blobs being created in the specified Azure Storage account’s container.
The blobs are created with the following naming convention:
<Namespace>/<EventHub>/<Partition>/<YYYY>/<MM>/<DD>/<HH>/<mm>/<ss>
For example: Myehns/myhub/0/2016/07/20/09/02/15 and are in standard Avro format.
If there is no event data in the specified time and size window, empty blobs will be created by Archive.
Archive will be an option when creating an Event Hub in a namespace and will be limited to one per Event Hub. This will be added to the Throughput Unit charge and thus will be based on the number of throughput units selected for the Event Hub.
Opting Archive will involve 100% egress of ingested data and the cost of storage is not included. This implies that cost is primarily for compute (hey, we are handling all this for you!).
Next Steps?
Learn all about this new feature here, Event Hubs Archive
Use templates to enable the feature on your Event Hub, Enable Archive using Azure Resource Manager
Let us know what you think about newer sinks an newer serialization formats.
Start enjoying this feature, available today.
If you have any questions or suggestions, leave us a comment below. | https://azure.microsoft.com/de-de/blog/azure-event-hubs-archive-in-public-preview/ | CC-MAIN-2017-43 | refinedweb | 681 | 59.84 |
implement clock using the functions provided by xpal_async32khz.c . More...
#include <avr/power.h>
#include <util/atomic.h>
#include <avr/sleep.h>
#include "config.h"
#include "rtc.h"
#include "xpal_async32khz.h"
implement clock using the functions provided by xpal_async32khz.c .
We provide functions to query a counter incremented once per second, and additionaly sub-second precision (1/256 s) using the current value of the timer register.
usage example (startup):
hl_rtc_init_osc (); // do something which does _not_ need the timer hl_rtc_init (); // now the clock functions give meaningful results
initialize low-frequency timer
hl_rtc_init() blocks as long as timer1 indicates that the necessary time for oscillator start-up has not elapsed.
{ hl_asyn_Register1sTimer (hl_rtc_1s, NULL); /* (); hl_asyn_init_timer(); }.
{ hl_asyn_init_osc(); /* prepare for 1 second wait until oscillator is ready */ /* */ } | http://doc.explorerspal.org/xpal__rtc_8c.html | CC-MAIN-2022-27 | refinedweb | 123 | 53.07 |
Over the last couple of weeks we’ve looked at working with blocks and Procs.
A block is a chunk of code that can be passed to a method. This makes it really easy to write flexible methods that can be used in a number of different ways. If you are already familiar with other programming languages, this concept is probably already familiar to you.
Last week we looked at Procs. A Proc is basically just a block, but it is saved to a variable so you can use it like an object. This means you can make reusable procedures out of Procs that can be passed to methods. You can also use multiple Procs in a method call, whereas you can only use a single block.
Ruby also has a third similar concept to blocks and Procs known as lambdas. In today’s tutorial we’ll be looking at lambdas and how they differ from Procs.
What are lambdas?
If you already have a background in programming, you might have already come across the word lambda. A lambda is also commonly referred to as an anonymous function.
To create a lambda in Ruby, you can use the following syntax:
lambda = lambda {}
Alternatively you can use this syntax:
lambda = ->() {}
However, if you create a new lambda in IRB using either of these two syntaxes, you might have noticed something a bit weird:
=> #<Proc:0x007f933a429fd0@(irb):4 (lambda)>
If you call the
class method you will see that a lambda is actually an instance of the
Proc class:
lamba.class => Proc
What is the difference between a lambda and a Proc?
So if a lambda is also an instance of the
Proc class, what is the difference between a lambda and a regular Proc and why is there a distinction?
Well, a lambda will behave like a method, whereas a Proc will behave like a block. Let’s dig into this so we understand what’s going on under the hood.
How arguments are handled
The first difference between Procs and lambdas is how arguments are handled.
For example, we might have the following lambda and Proc that do exactly the same thing, in this case, accept a
name and
puts a string to the screen:
lambda = -> (name) { puts "Hello #{name}" } proc = Proc.new { |name| puts "Hello #{name}" }
We can call each of these by using the
call method and passing a name as the argument:
lambda.call("Philip") => Hello Philip proc.call("Philip") => Hello Philip
All good so far, both the lambda and the Proc behave in exactly the same way.
However, what happens if me don’t pass an argument?
lambda.call() => ArgumentError: wrong number of arguments (0 for 1) proc.call() => Hello
When a lambda expects an argument, you need to pass those arguments or an Exception will be thrown. However, in the case of the Proc, if the argument is not passed it automatically defaults to
nil.
This is because a lambda will act like a method and expect you to pass each of the defined arguments, whereas a Proc will act like a block and will not require strict argument checking.
The use of the return statement
A second difference between a lambda and a Proc is how the
return statement is handled.
To illustrate this, lets take a look at a code example:
def lambda_method -> () { return "I was called from inside the lambda"}.call return "I was called from after the lambda" end
Here we have a method that contains a lambda and an
return statement. When the lambda is called it will return a string of text to the method.
When we call this method and
puts the return value to the screen, what would you expect to see?
puts lambda_method => "I was called from after the lambda"
So when the method is called, the lambda is called from inside the method, then the return statement returns the string of text after the lambda.
However, imagine we also had a proc version of this method:
def proc_method Proc.new { return "I was called from inside the proc"}.call return "I was called from after the proc" end
This is basically the same method but instead of using a lambda we are using a Proc.
Now if we run this method, what would you expect to see?
puts proc_method => "I was called from inside the proc"
When a lambda encounters a
return statement it will return execution to the enclosing method.
However, when a Proc encounters a
return statement it will jump out of itself, as well as the enclosing method.
To further illustrate this behaviour, take a look at this example:
-> () { return } => #<Proc:0x007f9d1182d100@(irb):2 (lambda)>
When you create a lambda in irb and use a
return statement everything is fine.
However if you try to do the same thing with a Proc, you will get an Exception:
Proc.new { return }.call LocalJumpError: unexpected return
This is basically the same as what we saw whilst wrapping the lambda and the Proc in a method, however in this case, the Proc has nothing to jump back to.
Conclusion
Blocks, Procs and Lambdas are all pretty similar. Each has their own characters, place and purpose within the Ruby language.
It is important to understand the characteristics of things like blocks, Procs and lambdas because it will make it a lot easier to understand other people’s code.
When you learn a new idea it often feels tempting to jump right in and start using it all the time. This usually leads you to using the new technique in the wrong situations.
Don’t worry about using new ideas straightaway. Instead, start reading other people’s code to see how they have implemented the same idea.
Once you can understand and recognise how and why another developer has written a certain piece of code, you will be much better equipped to make your own design decisions. | https://www.culttt.com/2015/05/13/what-are-lambdas-in-ruby/ | CC-MAIN-2018-51 | refinedweb | 990 | 69.21 |
Type information. More...
#include <opencv2/core/types_c.h>
Type information.
The structure contains information about one of the standard or user-defined types. Instances of the type may or may not contain a pointer to the corresponding CvTypeInfo structure. In any case, there is a way to find the type info structure for a given object using the cvTypeOf function. Alternatively, type info can be found by type name using cvFindType, which is used when an object is read from file storage. The user can register a new type with cvRegisterType that adds the type information structure into the beginning of the type list. Thus, it is possible to create specialized types from generic standard types and override the basic methods.
creates a copy of the object
not used
sizeof(CvTypeInfo)
checks if the passed object belongs to the type
next registered type in the list
previous registered type in the list
reads object from file storage
releases object (memory etc.)
type name, written to file storage
writes object to file storage | https://docs.opencv.org/3.4.7/d7/d7c/structCvTypeInfo.html | CC-MAIN-2022-33 | refinedweb | 172 | 52.6 |
# Redwood Router
This is the built-in router for Redwood apps. It takes inspiration from Ruby on Rails, React Router, and Reach Router, but is very opinionated in its own way.
WARNING: RedwoodJS software has not reached a stable version 1.0 and should not be considered suitable for production use. In the "make it work; make it right; make it fast" paradigm, Redwood is in the later stages of the "make it work" phase.
Redwood Router (RR from now on) is designed to list all routes in a single file, with limited nesting. We prefer this design, as it makes it very easy to track which routes map to which pages.
# Router and Route
The first thing you need is a
Router. It will contain all of your routes. RR will attempt to match the current URL to each route in turn, and only render those with a matching
path. The only exception to this is the
notfound route, which can be placed anywhere in the list and only matches when no other routes do.
Each route is specified with a
Route. Our first route will tell RR what to render when no other route matches:
// Routes.js import { Router, Route } from '@redwoodjs/router' const Routes = () => ( <Router> <Route notfound page={NotFoundPage} /> </Router> ) export default Routes
RR expects a single
Route with a
notfound prop. When no other route is found to match, the component in the
page prop will be rendered.
To create a route to a normal Page, you'll pass three props:
path,
page, and
name:
// Routes.js <Route path="/" page={HomePage}
The
path prop specifies the URL path to match, starting with the beginning slash. The
page prop specifies the Page component to render when the path is matched. The
name prop is used to specify the name of the named route function.
# Private Routes
Some pages should only be visible to authenticated users.
All
Routes nested in
<Private> require authentication.
When a user is not authenticated and attempts to visit this route,
they will be redirected to the route passed as the
unauthenticated prop and the originally requested route's path will be added to the querystring in a
redirectTo param. This lets you send the user to the originally requested once logged in.
// Routes.js <Router> <Route path="/" page={HomePage} <Private unauthenticated="home"> <Route path="/admin" page={AdminPage} </Private> </Router>
Redwood uses the
useAuth hook under the hood to determine if the user is authenticated.
Read more about authentication in redwood here.
# Sets of Routes
You can group Routes into sets using the
Set component.
Set allows you to wrap a set of Routes in another component or array of components—usually a Context, a Layout, or both:
// Routes.js import { Router, Route, Set } from '@redwoodjs/router' import BlogContext from 'src/contexts/BlogContext' import BlogLayout from 'src/layouts/BlogLayout' const Routes = () => { return ( <Router> <Set wrap={[BlogContext, BlogLayout]}> <Route path="/" page={HomePage} <Route path="/about" page={AboutPage} <Route path="/contact" page={ContactPage} <Route path="/blog-post/{id:Int}" page={BlogPostPage} </Set> </Router> ) } export default Routes
The
wrap prop accepts a single component or an array of components. Components are rendered in the same order they're passed, so in the exmaple above, Set expands to:
<BlogContext> <BlogLayout> <Route path="/" page={HomePage} // ... </BlogLayout> </BlogContext>
Conceptually, this fits with how we think about Context and Layouts as things that wrap Pages and contain content that’s outside the scope of the Pages themselves. Crucially, since they're higher in the tree,
BlogContext and
BlogLayout won't rerender across Pages in the same Set.
There's a lot of flexibility here. You can even nest
Sets to great effect:
// Routes.js import { Router, Route, Set, Private } from '@redwoodjs/router' import BlogContext from 'src/contexts/BlogContext' import BlogLayout from 'src/layouts/BlogLayout' import BlogNavLayout from 'src/layouts/BlogNavLayout' const Routes = () => { return ( <Router> <Set wrap={[BlogContext, BlogLayout]}> <Route path="/" page={HomePage} <Route path="/about" page={AboutPage} <Route path="/contact" page={ContactPage} <Set wrap={BlogNavLayout}> <Route path="/blog-post/{id:Int}" page={BlogPostPage} </Set> </Set> </Router> ) }
# Link and named route functions
When it comes to routing, matching URLs to Pages is only half the equation. The other half is generating links to your pages. RR makes this really simple without having to hardcode URL paths. In a Page component, you can do this (only relevant bits are shown in code samples from now on):
// SomePage.js import { Link, routes } from '@redwoodjs/router' // Given the route in the last section, this produces: <a href="/"> const SomePage = () => <Link to={routes.home()} />
You use a
Link to generate a link to one of your routes and can access URL generators for any of your routes from the
routes object. We call the functions on the
routes object named route functions and they are named after whatever you specify in the
name prop of the
Route.
Named route functions simply return a string, so you can still pass in hardcoded strings to the
to prop of the
Link component, but using the proper named route function is easier and safer. Plus, if you ever decide to change the
path of a route, you don't need to change any of the
Links to it (as long as you keep the
name the same)!
# Active links
NavLink is a special version of
Link that will add an
activeClassName to the rendered element when it matches the current URL.
// MainMenu.js import { NavLink, routes } from '@redwoodjs/router' // Will render <a href="/" className="link activeLink"> when on the home page const MainMenu = () => <NavLink className="link" activeClassName="activeLink" to={routes.home()} >Home</NavLink>
You can
useMatch to create your own component with active styles.
NavLink uses it internally!
import { Link, routes, useMatch } from '@redwoodjs/router' const CustomLink = ({to, ...rest}) => { const matchInfo = useMatch(to) return <SomeStyledComponent as={Link} to={to} isActive={matchInfo.match} /> } const MainMenu = () => { return <CustomLink to={routes.about()} /> }
# Route parameters
To match variable data in a path, you can use route parameters, which are specified by a parameter name surrounded by curly braces:
// Routes.js <Route path="/user/{id}>" page={UserPage}
This route will match URLs like
/user/7 or
/user/mojombo. You can have as many route parameters as you like:
// Routes.js <Route path="/blog/{year}/{month}/{day}/{slug}" page={PostPage}
By default, route parameters will match up to the next slash or end-of-string. Once extracted, the route parameters are sent as props to the Page component. In the 2nd example above, you can receive them like so:
// PostPage.js const PostPage = ({ year, month, day, slug }) => { ... }
# Named route functions with parameters
If a route has route parameters, then its named route function will take an object of those same parameters as an argument:
// SomePage.js <Link to={routes.user({ id: 7 })}>...</Link>
All parameters will be converted to strings before being inserted into the generated URL. If you don't like the default JavaScript behavior of how this conversion happens, make sure to convert to a string before passing it into the named route function.
If you specify parameters to the named route function that do not correspond to parameters defined on the route, they will be appended to the end of the generated URL as search params in
key=val format:
// SomePage.js <Link to={routes.users({ sort: 'desc', filter: 'all' })}>...</Link> // => "/users?sort=desc&filter=all"
# Route parameter types
Route parameters are extracted as strings by default, but they will often represent typed data. RR offers a convenient way to auto-convert certain types right in the
path specification:
// Routes.js <Route path="/user/{id:Int}" page={UserPage}
By adding
:Int onto the route parameter, you are telling RR to only match
/\d+/ and then use
Number() to convert the parameter into a number. Now, instead of a string being sent to the Page, a number will be sent! This means you could have both a route that matches numeric user IDs and a route that matches string IDs:
// Routes.js <Route path="/user/{id:Int}" page={UserIntPage} <Route path="/user/{id}" page={UserStringPage}
Now, if a request for
/user/mojombo comes in, it will fail to match the first route, but will succeed in matching the second.
# Core route parameter types
We call built-in parameter types core parameter types. All core parameter types begin with a capital letter. Here are the types:
Int- Matches and converts an integer.
# User route parameter types
RR goes even further, allowing you to define your own route parameter types. Your custom types must begin with a lowercase letter. You can specify them like so:
// Routes.js const userRouteParamTypes = { slug: { constraint: /\w+-\w+/, transform: (param) => param.split('-'), } } <Router paramTypes={userRouteParamTypes}> <Route path="/post/{name:slug}" page={PostPage} name={post} /> </Router>
Here we've created a custom
slug route parameter type. It is defined by a
constraint and a
transform. Both are optional; the default constraint is
/[^/]+/ and the default transform is
(param) => param.
In the route we've specified a route parameter of
{name:slug} which will invoke our custom route parameter type and if we have a request for
/post/redwood-router, the resulting
name prop delivered to
PostPage will be
['redwood', 'router'].
# useParams
Sometimes it's convenient to receive route parameters as the props to the Page, but in the case where a deeply nested component needs access to the route parameters, it quickly becomes tedious to pass those props through every intervening component. RR solves this with the
useParams hook:
// SomeDeeplyNestedComponent.js import { useParams } from '@redwoodjs/router' const SomeDeeplyNestedComponent = () => { const { id } = useParams() ... }
In the above example, we've pulled in the
id route parameter without needing to have it passed in to us from anywhere.
# useLocation
If you'd like to get access to the current URL,
useLocation returns a read-only location object representing it. The location object has three properties, pathname, search, and hash, that update when the URL changes. This makes it easy to fire off navigation side effects or use the URL as if it were state:
import { useLocation } from '@redwoodjs/router' const App = () => { const { pathname, search, hash } = useLocation() // log the URL when the pathname changes React.useEffect(() => { myLogger(pathname) }, [pathname]) // initiate a query state with the search val const [query, setQuery] = React.useState(search) // conditionally render based on hash if ( hash === "#ping" ) { return <Pong /> } return ( <>...</> ) }
# navigate
If you'd like to programmatically navigate to a different page, you can simply use the
navigate function:
// SomePage.js import { navigate, routes } from '@redwoodjs/router' const SomePage = () => { const onSomeAction = () => { navigate(routes.home()) } ... }
# Redirect
If you want to declaratively redirect to a different page, use the
<Redirect> component.
In the example below, SomePage will redirect to the home page.
// SomePage.js import { Redirect, routes } from '@redwoodjs/router' const SomePage = () => { <Redirect to={routes.home()}/> }
# Code-splitting
By default, RR will code-split on every Page, creating a separate lazy-loaded webpack bundle for each. When navigating from page to page, RR will wait until the new Page module is loaded before re-rendering, thus preventing the "white-flash" effect.
# Not code splitting
If you'd like to override the default lazy-loading behavior and include certain Pages in the main webpack bundle, you can simply add the import statement to the
Routes.js file:
// Routes.js import HomePage from 'src/pages/HomePage'
Redwood will detect your explicit import and refrain from splitting that page into a separate bundle. Be careful with this feature, as you can easily bloat the size of your main bundle to the point where your initial page load time becomes unacceptable.
# PageLoadingContext
VIDEO: If you'd prefer to watch a video, there's one accompanying this section:
Because lazily-loaded pages can take a non-negligible amount of time to load (depending on bundle size and network connection), you may want to show a loading indicator to signal to the user that something is happening after they click a link. RR makes this really easy with
usePageLoadingContext:
// SomeLayout.js import { usePageLoadingContext } from '@redwoodjs/router' const SomeLayout = (props) => { const { loading } = usePageLoadingContext() return ( <div> {loading && <div>Loading...</div>} <main>{props.children}</main> </div> ) }
When the lazy-loaded page is loading,
PageLoadingContext.Consumer will pass
{ loading: true } to the render function, or false otherwise. You can use this context wherever you like in your application!
After adding this to your app you will probably not see it when navigating between pages. This is because having a loading indicator is nice, but can get annoying when it shows up every single time you navigate to a new page. In fact, this behavior makes it feel like your pages take even longer to load than they actually do! RR takes this into account and, by default, will only show the loader when it takes more than 1000 milliseconds for the page to load. You can change this to whatever you like with the
pageLoadingDelay prop on
Router:
// Routes.js <Router pageLoadingDelay={500}>...</Router>
Now the loader will show up after 500ms of load time. To see your loading indicator, you can set this value to 0 or, even better, change the network speed in developer tools to "Slow 3G" or another agonizingly slow connection speed. | https://redwoodjs.com/docs/redwood-router | CC-MAIN-2021-17 | refinedweb | 2,192 | 62.17 |
In the previous lesson, we talked about C-style strings, and the dangers of using them. C-style strings are fast, but they’re not as easy to use and as safe as std::string.
std::string
But std::string (which we covered in lesson 8.1 -- An introduction to std::string), has some of its own downsides, particularly when it comes to const strings.
Consider the following example:
As expected, this prints
hello hello hello
Internally, main copies the string “hello” 3 times, resulting in 4 copies. First, there is the string literal “hello”, which is known at compile-time and stored in the binary. One copy is created when we create the char[]. The following two std::string objects create one copy of the string each. Because std::string is designed to be modifiable, each std::string must contain its own copy of the string, so that a given std::string can be modified without affecting any other std::string object.
main
char[]
This holds true for const std::string, even though they can’t be modified.
Introducing std::string_view
Consider a window in your house, looking at a car sitting on the street. You can look through the window and see the car, but you can’t touch or move the car. Your window just provides a view to the car, which is a completely separate object.
C++17 introduces another way of using strings, std::string_view, which lives in the <string_view> header.
std::string_view
Unlike std::string, which keeps its own copy of the string, std::string_view provides a view of a string that is defined elsewhere.
We can re-write the above code to use std::string_view by replacing every std::string with std::string_view.
The output is the same, but no more copies of the string “hello” are created. The string “hello” is stored in the binary and is not allocated at run-time. text is only a view onto the string “hello”, so no copy has to be created. When we copy a std::string_view, the new std::string_view observes the same string as the copied-from std::string_view is observing. This means that neither str nor more create any copies. They are views onto the existing string “hello”.
text
str
more
std::string_view is not only fast, but has many of the functions that we know from std::string.
Because std::string_view doesn’t create a copy of the string, if we change the viewed string, the changes are reflected in the std::string_view.
We modified arr, but str appears to be changing as well. That’s because arr and str share their string. When you use a std::string_view, it’s best to avoid modifications to the underlying string for the remainder of the std::string_view‘s life to prevent confusion and errors.
arr
Best practice
Prefer std::string_view over std::string for read-only strings, unless you already have a std::string.
View modification functions
Back to our window analogy, consider a window with curtains. We can close either the left or right curtain to reduce what we can see. We don’t change what’s outside, we just reduce the visible area.
Similarly, std::string_view contains functions that let us manipulate the view of the string. This allows us to change the view without modifying the viewed string.
The functions for this are remove_prefix, which removes characters from the left side of the view, and remove_suffix, which removes characters from the right side of the view.
remove_prefix
remove_suffix
This program produces the following output:
Peach
each
ea
Unlike real curtains, a std::string_view cannot be opened back up. Once you change the visible area, you can’t go back (There are tricks which we won’t go into).
std::string_view works with non-null-terminated strings
Unlike C-style strings and std::string, std::string_view doesn’t use null terminators to mark the end of the string. Rather, it knows where the string ends because it keeps track of its length.
This program prints:
aeiou
Ownership issues
Being only a view, a std::string_view‘s lifetime is independent of that of the string it is viewing. If the viewed string goes out of scope, std::string_view has nothing to observe and accessing it causes undefined behavior. The string that a std::string_view is viewing has to have been created somewhere else. It might be a string literal that lives as long as the program does or it was created by a std::string, in which case the string lives until the std::string decides to destroy it or the std::string dies. std::string_view can’t create any strings on its own, because it’s just a view.
What's your name?
nascardriver
Hello nascardriver
Your name is �P@�P@
When we created str and filled it with std::cin, it created its internal string in dynamic memory. When str goes out of scope at the end of askForName, the internal string dies along with str. The std::string_view doesn’t know that the string no longer exists and allows us to access it. Accessing the released string through view in main causes undefined behavior, which on the author’s machine produced weird characters.
std::cin
askForName
view
The same can happen when we create a std::string_view from a std::string and modify the std::string. Modifying a std::string can cause its internal string to die and be replaced with a new one in a different place. The std::string_view will still look at where the old string was, but it’s not there anymore.
Warning
Make sure that the underlying string viewed with a std::string_view does not go out of scope and isn’t modified while using the std::string_view.
Converting a std::string_view to a std::string
An std::string_view will not implicitly convert to a std::string, but can be explicitly converted:
This prints:
ball
ball
Converting a std::string_view to a C-style string
Some old functions (such as the old strlen function) still expect C-style strings. To convert a std::string_view to a C-style string, we can do so by first converting to a std::string:
ball has 4 letter(s)
However, creating a std::string every time we want to pass a std::string_view as a C-style string is expensive, so this should be avoided if possible.
Opening the window (kinda) via the data() function
The string being viewed by a std::string_view can be accessed by using the data() function, which returns a C-style string. This provides fast access to the string being viewed (as a C-string). But it should also only be used if the std::string_view‘s view hasn’t been modified (e.g. by remove_prefix or remove_suffix) and the string being viewed is null-terminated.
data()
In the following example, std::strlen doesn’t know what a std::string_view is, so we need to pass it str.data():
std::strlen
str.data()
balloon
7
When a std::string_view has been modified, data() doesn’t always do what we’d like it to. The following example demonstrates what happens when we access data() after modifying the view:
all has 6 letter(s)
str.data() is alloon
str is all
Clearly this isn’t what we’d intended, and is a consequence of trying to access the data() of a std::string_view that has been modified. The length information about the string is lost when we access data(). std::strlen and std::cout keep reading characters from the underlying string until they find the null-terminator, which is at the end of “balloon”.
std::cout
Only use std::string_view::data() if the std::string_view‘s view hasn’t been modified and the string being viewed is null-terminated. Using std::string_view::data() of a non-null-terminated string can cause undefined behavior.
std::string_view::data()
Incomplete implementation
Being a relatively recent feature, std::string_view isn’t implemented as well as it could be.
There’s no reason why line 5 and 6 shouldn’t work. They will probably be supported in a future C++ version.
why is the call syntax std::string_view.data() but in the warning box the scope resolution operator std::string_view::data() is used? Or is it covered later somewhere?
`::` is used to refer to members of a namespace or type.
`.` is used to access members of an instantiated type (A variable).
Hello, just a short question regarding one of the statements.
Statement given above in tutorial:
"Unlike C-style strings and std::string, std::string_view doesn’t use null terminators to mark the end of the string. Rather, it knows where the string ends because it keeps track of its length."
For C-style string I agree, but from what I know, there is no null terminator in std::string and in this way std::string and std::string_view are the same.
Below example is extended example from your tutorial to prove my point
#include <iostream>
#include <iterator> // For std::size
#include <string_view>
#include <string>
int main()
{
// No null-terminator.
char vowels[]{ 'a', 'e', 'i', 'o', 'u' };
// vowels isn't null-terminated. We need to pass the length manually.
// Because vowels is an array, we can use std::size to get its length.
std::string_view strView{ vowels, std::size(vowels) };
std::string str{ vowels, std::size(vowels) };
std::cout << strView << " lenght: " << strView.length() << '\n'; // This is safe. std::cout knows how to print std::string_views.
std::cout << str << " lenght: " << str.length() << '\n';
return 0;
}
What I understood from your statement is that, unlike std::string, std::string_view doesn’t use null terminators to mark the end of the string because it tracks the length, but std::string also does the same as can be seen in the above example.
Sorry if I misunderstood something.
Thanks in advance for the help
`std::string` owns the string. Whatever you initialize a `std::string` with, the `std::string` copies it. When you initialize a `std::string` with a non-null terminated char array, the `std::string` copies it.
There is no way to access a `std::string` such that it does not appear like a null-terminated string. While it is possible (At least I can't find a contradiction) for a standard library implementation not to use a null-terminated string internally, doing so wouldn't make sense.
When you initialize the `std::string` with a non-null terminated char array, the `std::string` appends the null-terminator to its internal string. Additionally `std::string` has to track the length.
Hello,
Thank you for this great tutorial. There is a statement:
"Modifying a std::string can cause its internal string to die and be replaced with a new one in a different place"
output:
adasdasdas
adas
Here, the address of the std::string is not changed. The new std::string is allocated at the same place in memory. This conflicts with your statement. Does your statement depend on compiler?
Regards,
Your assignment to `t` may or may not cause a reallocation. The new allocation may or may not happen at the same address the old string was placed it. Accessing `v` after the assignment to `t` causes undefined behavior.
Name (required)
Website
Save my name, email, and website in this browser for the next time I comment. | https://www.learncpp.com/cpp-tutorial/an-introduction-to-stdstring_view/ | CC-MAIN-2021-04 | refinedweb | 1,896 | 63.49 |
Investors in Raytheon Co. (Symbol: RTN) saw new options begin trading today, for the December 6th expiration. At Stock Options Channel, our YieldBoost formula has looked up and down the RTN options chain for the new December 6th contracts and identified one put and one call contract of particular interest.
The put contract at the $202.50 strike price has a current bid of $2.74. If an investor was to sell-to-open that put contract, they are committing to purchase the stock at $202.50, but will also collect the premium, putting the cost basis of the shares at $199.76 (before broker commissions). To an investor already interested in purchasing shares of RTN, that could represent an attractive alternative to paying $207.65/share today.
Because the $202.35% return on the cash commitment, or 11.47% annualized — at Stock Options Channel we call this the YieldBoost.
Below is a chart showing the trailing twelve month trading history for Raytheon Co., and highlighting in green where the $202.50 strike is located relative to that history:
Turning to the calls side of the option chain, the call contract at the $210.00 strike price has a current bid of $5.05. If an investor was to purchase shares of RTN stock at the current price level of $207.65/share, and then sell-to-open that call contract as a "covered call," they are committing to sell the stock at $210.00. Considering the call seller will also collect the premium, that would drive a total return (excluding dividends, if any) of 3.56% if the stock gets called away at the December 6th expiration (before broker commissions). Of course, a lot of upside could potentially be left on the table if RTN shares really soar, which is why looking at the trailing twelve month trading history for Raytheon Co., as well as studying the business fundamentals becomes important. Below is a chart showing RTN's trailing twelve month trading history, with the $210.00 strike highlighted in red:
Considering the fact that the $210.43% boost of extra return to the investor, or 20.62% annualized, which we refer to as the YieldBoost.
The implied volatility in the put contract example is 29%, while the implied volatility in the call contract example is 28%.
Meanwhile, we calculate the actual trailing twelve month volatility (considering the last 251 trading day closing values as well as today's price of $207.65). | https://www.nasdaq.com/articles/rtn-december-6th-options-begin-trading-2019-10-24 | CC-MAIN-2022-40 | refinedweb | 414 | 65.83 |
With the same GPS reciever I get this on the hyper terminal on the computer.
I investigated for quite sometime now (at least 2 months) and I think I do not have a clue of what do next anymore.I tried to change the parity, stop bit and data lenght and different stuff with no avail.
Code: [Select]#include <NewSoftSerial.h>NewSoftSerial nss (0,1);
#include <NewSoftSerial.h>NewSoftSerial nss (0,1);
in fact when I connect to the hyper terminal it does not do through the arduino and the result is great
Your symptom looks like a baud rate mismatch
I am using the max232 with the GPS S1315R
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=57289.0 | CC-MAIN-2015-48 | refinedweb | 145 | 62.58 |
Subject: Re: [OMPI users] Addendum to: Assembler instruction errors for push and pop during make
From: Richard Haney (rfhaney_at_[hidden])
Date: 2013-08-21 22:53:00
Hmmm...
Thanks, Jeremiah, for the suggestion.
File win_compat.h is in directory opal/win32 , a directory which by its
name is supposedly concerned only with producing a 32-bit target, and so,
because we are doing a build for a 64-bit target, it seems make should not
be having anything to do with files in that directory.
What seems a more likely approach is to consider what happens in asm.c ,
which appears to be where make has problems. I gather that either some
command is executed to create asm.lo earlier in the make processing
(although make output does not show any earlier command to do that) or
else, which seems more likely, gcc (in command " CC asm.lo " ) knows
how to interpret the file name asm.lo so as to look at asm.c for build
purposes.
So what does asm.c do??? After a bunch of initial #include statements in
asm.c there is next the statement
#if OPAL_ASSEMBLY_ARCH == OMPI_SPARC
But note that directory opal/asm/base has a bunch of files whose names
suggest that SPARC is an alternative architecture to AMD64 . So it seems
the preprocessor #if condition should evaluate to false. The other end of
this #if statement is
#endif /* OPAL_ASSEMBLY_ARCH == OMPI_SPARC32 */
at the very end of the file. So it seems the result is that there is no
code in asm.c to compile (or assemble); the resulting preprocessed file
consists only of included headers.
So I'm thinking that the thing to do is to gut asm.c and replace it with a
dummy routine so that at least an object file will be produced so that make
will not get confused for lack of an object file.
But this assumes that asm.c is not supposed to produce any entry points or
other loader variables to link to other modules in Open MPI.
That is a big question. One possibility is to find some equivalent 32-bit
file alternative to the supposed 64-bit asm.c and to try to manually
re-interpret and modify that code so as to become an equivalent 64-bit code.
So maybe I should do a 32-bit build and somehow adjust the relevant
Makefileso that a file of 32-bit preprocessed C or assembly code is
produced from
asm.c But I suppose this would require knowing what the command "CC
asm.lo"
is actually supposed to do even in the 32-bit case.
I am wondering whether such a 32-bit "build" for preprocessed output from
asm.c can be done as a quick, stand-alone run without having to rerun
configure and make for context.
---
Note also the OMPI_SPARC32 in the comment for #endif . That suggests the
author may have been vacillating as to whether SPARC is a 32-bit
architecture.
There is likely lots of guessing in this approach; so unless someone can
suggest a more direct and definitive solution to resolve this issue fairly
soon, I think I may take a little vacation and perhaps come back to this
question later.
Richard Haney
On Tue, Aug 20, 2013 at 7:41 PM, Jeremiah Willcock <jewillco_at_[hidden]>wrote:
> The file win_compat.h seems to be very strange (many #defines of function
> names, #defines of type names rather than typedefs, etc.). It might make
> sense to avoid including it entirely for MinGW (it is included from
> opal/include/opal_config_**bottom.h), or edit it to be correct for 64-bit
> systems. You might want to try commenting out the entire body of
> win_compat.h and re-enabling only those parts that are truly necessary (and
> don't have MinGW headers that should be used instead, such as for ssize_t).
>
> -- Jeremiah Willcock
>
> | http://www.open-mpi.org/community/lists/users/2013/08/22538.php | CC-MAIN-2015-14 | refinedweb | 647 | 72.36 |
Build a CRUD Web App With Python and Flask – Part Three
Create custom error pages, write tests, and deploy your app to PythonAnywhere
JavaScript is the language on fire. Build an app for any platform you want including website, server, mobile, and desktop.
This is the last part of a three-part tutorial to build an employee management web app, named Project Dream Team. In Part Two of the tutorial, we built out the CRUD functionality of the app.
We created forms, views, and templates to list, add, edit and delete departments and roles. By the end of Part Two, we could assign (and re-assign) departments and roles to employees.
In Part Three, we will cover:
- Custom error pages
- Unit tests
- Deployment on PythonAnywhere
Custom Error Pages
Web applications make use of HTTP errors to let users know that something has gone wrong. Default error pages are usually quite plain, so we will create our own custom ones for the following common HTTP errors:
- 403 Forbidden: this occurs when a user is logged in (authenticated), but does not have sufficient permissions to access the resource. This is the error we have been throwing when non-admins attempt to access an admin view.
- 404 Not Found: this occurs when a user attempts to access a non-existent resource such as an invalid URL, e.g.
- 500 Internal Server Error: this is a general error thrown when a more specific error cannot be determined. It means that for some reason, the server cannot process the request.
We'll start by writing the views for the custom error pages. In your
app/__init__.py file, add the following code:
# app/__init__.py # update imports from flask import Flask, render_template # existing code remains def create_app(config_name): # existing code remains @app.errorhandler(403) def forbidden(error): return render_template('errors/403.html', title='Forbidden'), 403 @app.errorhandler(404) def page_not_found(error): return render_template('errors/404.html', title='Page Not Found'), 404 @app.errorhandler(500) def internal_server_error(error): return render_template('errors/500.html', title='Server Error'), 500 return app
We make use of Flask's
@app.errorhandler decorator to define the error page views, where we pass in the status code as a parameter.
Next, we'll create the template files. Create a
app/templates/errors directory, and in it, create
403.html,
404.html, and
500.html.
<!-- app/templates/errors/403.html --> {% extends "base.html" %} {% block title %}Forbidden{% endblock %} {% block body %} <div class="content-section"> <div class="outer"> <div class="middle"> <div class="inner"> <div style="text-align: center"> <h1> 403 Error </h1> <h3> You do not have sufficient permissions to access this page. </h3> <hr class="intro-divider"> <a href="{{ url_for('home.homepage') }}" class="btn btn-default btn-lg"> <i class="fa fa-home"></i> Home </a> </div> </div> </div> </div> </div> {% endblock %}
<!-- app/templates/errors/404.html --> {% extends "base.html" %} {% block title %}Page Not Found{% endblock %} {% block body %} <div class="content-section"> <div class="outer"> <div class="middle"> <div class="inner"> <div style="text-align: center"> <h1> 404 Error </h1> <h3> The page you're looking for doesn't exist. </h3> <hr class="intro-divider"> <a href="{{ url_for('home.homepage') }}" class="btn btn-default btn-lg"> <i class="fa fa-home"></i> Home </a> </div> </div> </div> </div> </div> {% endblock %}
<!-- app/templates/errors/500.html --> {% extends "base.html" %} {% block title %}Internal Server Error{% endblock %} {% block body %} <div class="content-section"> <div class="outer"> <div class="middle"> <div class="inner"> <div style="text-align: center"> <h1> 500 Error </h1> <h3> The server encountered an internal error. That's all we know. </h3> <hr class="intro-divider"> <a href="{{ url_for('home.homepage') }}" class="btn btn-default btn-lg"> <i class="fa fa-home"></i> Home </a> </div> </div> </div> </div> </div> {% endblock %}
All the templates give a brief description of the error, and a button that links to the homepage.
Run the app and log in as a non-admin user, then attempt to access. You should get the following page:
Now attempt to access this non-existent page:. You should see:
To view the internal server error page, we'll create a temporary route where we'll use Flask's
abort() function to raise a 500 error. In the
app/__init__.py file, add the following:
# app/__init__.py # update imports from flask import abort, Flask, render_template # existing code remains def create_app(config_name): # existing code remains @app.route('/500') def error(): abort(500) return app
Go to; you should see the following page:
Now you can remove the temporary route we just created for the internal server error.
Tests
Now, let's write some tests for the app. The importance of testing software can't be overstated. Tests help ensure that your app is working as expected, without the need for you to manually test all of your app's functionality.
We'll begin by creating a test database, and give the database user we created in Part One all privileges on it:
$ mysql -u root mysql> CREATE DATABASE dreamteam_test; Query OK, 1 row affected (0.00 sec) mysql> GRANT ALL PRIVILEGES ON dreamteam_test . * TO 'dt_admin'@'localhost'; Query OK, 0 rows affected (0.00 sec)
Now we need to edit the
config.py file to add configurations for testing. Delete the current contents and replace them with the following code:
# config.py class Config(object): """ Common configurations """ DEBUG = True class DevelopmentConfig(Config): """ Development configurations """ SQLALCHEMY_ECHO = True class ProductionConfig(Config): """ Production configurations """ DEBUG = False class TestingConfig(Config): """ Testing configurations """ TESTING = True app_config = { 'development': DevelopmentConfig, 'production': ProductionConfig, 'testing': TestingConfig }
We have put
DEBUG = True in the base class,
Config, so that it is the default setting. We override this in the
ProductionConfig class. In the
TestingConfig class, we set the
TESTING configuration variable to
True.
We will be writing unit tests. Unit tests are written to test small, individual, and fairly isolated units of code, such as functions. We will make use of Flask-Testing, an extension that provides unit testing utilities for Flask.
$ pip install Flask-Testing
Next, create a
tests.py file in the root directory of your app. In it, add the following code:
# tests.py import unittest from flask_testing import TestCase from app import create_app, db from app.models import Employee class TestBase(TestCase): def create_app(self): # pass in test configurations config_name = 'testing' app = create_app(config_name) app.config.update( SQLALCHEMY_DATABASE_URI='mysql://dt_admin:dt2016@localhost/dreamteam_test' ) return app def setUp(self): """ Will be called before every test """ db.create_all() # create test admin user admin = Employee(username="admin", password="admin2016", is_admin=True) # create test non-admin user employee = Employee(username="test_user", password="test2016") # save users to database db.session.add(admin) db.session.add(employee) db.session.commit() def tearDown(self): """ Will be called after every test """ db.session.remove() db.drop_all() if __name__ == '__main__': unittest.main()
In the base class above,
TestBase, we have a
create_app method, where we pass in the configurations for testing.
We also have two other methods:
setUp and
tearDown. The
setUp method will be called automatically before every test we run. In it, we create two test users, one admin and one non-admin, and save them to the database. The
tearDown method will be called automatically after every test. In it, we remove the database session and drop all database tables.
To run the tests, we will run the
tests.py file:
$ python tests.py ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK
The output above lets us know that our test setup is OK. Now let's write some tests.
# tests.py # update imports import os from flask import abort, url_for from app.models import Department, Employee, Role # add the following after the TestBase class class TestModels(TestBase): def test_employee_model(self): """ Test number of records in Employee table """ self.assertEqual(Employee.query.count(), 2) def test_department_model(self): """ Test number of records in Department table """ # create test department department = Department(name="IT", description="The IT Department") # save department to database db.session.add(department) db.session.commit() self.assertEqual(Department.query.count(), 1) def test_role_model(self): """ Test number of records in Role table """ # create test role role = Role(name="CEO", description="Run the whole company") # save role to database db.session.add(role) db.session.commit() self.assertEqual(Role.query.count(), 1) class TestViews(TestBase): def test_homepage_view(self): """ Test that homepage is accessible without login """ response = self.client.get(url_for('home.homepage')) self.assertEqual(response.status_code, 200) def test_login_view(self): """ Test that login page is accessible without login """ response = self.client.get(url_for('auth.login')) self.assertEqual(response.status_code, 200) def test_logout_view(self): """ Test that logout link is inaccessible without login and redirects to login page then to logout """ target_url = url_for('auth.logout') redirect_url = url_for('auth.login', next=target_url) response = self.client.get(target_url) self.assertEqual(response.status_code, 302) self.assertRedirects(response, redirect_url) def test_dashboard_view(self): """ Test that dashboard is inaccessible without login and redirects to login page then to dashboard """ target_url = url_for('home.dashboard') redirect_url = url_for('auth.login', next=target_url) response = self.client.get(target_url) self.assertEqual(response.status_code, 302) self.assertRedirects(response, redirect_url) def test_admin_dashboard_view(self): """ Test that dashboard is inaccessible without login and redirects to login page then to dashboard """ target_url = url_for('home.admin_dashboard') redirect_url = url_for('auth.login', next=target_url) response = self.client.get(target_url) self.assertEqual(response.status_code, 302) self.assertRedirects(response, redirect_url) def test_departments_view(self): """ Test that departments page is inaccessible without login and redirects to login page then to departments page """ target_url = url_for('admin.list_departments') redirect_url = url_for('auth.login', next=target_url) response = self.client.get(target_url) self.assertEqual(response.status_code, 302) self.assertRedirects(response, redirect_url) def test_roles_view(self): """ Test that roles page is inaccessible without login and redirects to login page then to roles page """ target_url = url_for('admin.list_roles') redirect_url = url_for('auth.login', next=target_url) response = self.client.get(target_url) self.assertEqual(response.status_code, 302) self.assertRedirects(response, redirect_url) def test_employees_view(self): """ Test that employees page is inaccessible without login and redirects to login page then to employees page """ target_url = url_for('admin.list_employees') redirect_url = url_for('auth.login', next=target_url) response = self.client.get(target_url) self.assertEqual(response.status_code, 302) self.assertRedirects(response, redirect_url) class TestErrorPages(TestBase): def test_403_forbidden(self): # create route to abort the request with the 403 Error @self.app.route('/403') def forbidden_error(): abort(403) response = self.client.get('/403') self.assertEqual(response.status_code, 403) self.assertTrue("403 Error" in response.data) def test_404_not_found(self): response = self.client.get('/nothinghere') self.assertEqual(response.status_code, 404) self.assertTrue("404 Error" in response.data) def test_500_internal_server_error(self): # create route to abort the request with the 500 Error @self.app.route('/500') def internal_server_error(): abort(500) response = self.client.get('/500') self.assertEqual(response.status_code, 500) self.assertTrue("500 Error" in response.data) if __name__ == '__main__': unittest.main()
We've added three classes:
TestModels,
TestViews and
TestErrorPages.
The first class has methods to test that each of the models in the app are working as expected. This is done by querying the database to check that the correct number of records exist in each table.
The second class has methods that test the views in the app to ensure the expected status code is returned. For non-restricted views, such as the homepage and the login page, the
200 OK code should be returned; this means that everything is OK and the request has succeeded. For restricted views that require authenticated access, a
302 Found code is returned. This means that the page is redirected to an existing resource, in this case, the login page. We test both that the
302 Found code is returned and that the page redirects to the login page.
The third class has methods to ensure that the error pages we created earlier are shown when the respective error occurs.
Note that each test method begins with
test. This is deliberate, because
unittest, the Python unit testing framework, uses the
test prefix to automatically identify test methods. Also note that we have not written tests for the front-end to ensure users can register and login, and to ensure administrators can create departments and roles and assign them to employees. This can be done using a tool like Selenium Webdriver; however this is outside the scope of this tutorial.
Run the tests again:
$ python tests.py .............. ---------------------------------------------------------------------- Ran 14 tests in 2.313s OK
Success! The tests are passing.
Deploy!
Now for the final part of the tutorial: deployment. So far, we've been running the app locally. In this stage, we will publish the application on the internet so that other people can use it. We will use PythonAnywhere, a Platform as a Service (PaaS) that is easy to set up, secure, and scalable, not to mention free for basic accounts!
PythonAnywhere Set-Up
Create a free PythonAnywhere account here if you don't already have one. Be sure to select your username carefully since the app will be accessible at
your-username.pythonanywhere.com.
Once you've signed up,
your-username.pythonanywhere.com should show this page:
We will use git to upload the app to PythonAnywhere. If you've been pushing your code to cloud repository management systems like Bitbucket, Gitlab or Github, that's great! If not, now's the time to do it. Remember that we won't be pushing the
instance directory, so be sure to include it in your
.gitignore file, like so:
# .gitignore *.pyc instance/
Also, ensure that your
requirements.txt file is up to date using the
pip freeze command before pushing your code:
$ pip freeze > requirements.txt
Now, log in to your PythonAnywhere account. In your dashboard, there's a
Consoles tab; use it to start a new Bash console.
In the PythonAnywhere Bash console, clone your repository.
$ git clone
Next we will create a virtualenv, then install the dependencies from the
requirements.txt file. Because PythonAnywhere installs virtualenvwrapper for all users by default, we can use its commands:
$ mkvirtualenv dream-team $ cd project-dream-team-three $ pip install -r requirements.txt
We've created a virtualenv called
dream-team. The virtualenv is automatically activated. We then entered the project directory and installed the dependencies.
Now, in the Web tab on your dashboard, create a new web app.
Select the Manual Configuration option (not the Flask option), and choose Python 2.7 as your Python version. Once the web app is created, its configurations will be loaded. Scroll down to the Virtualenv section, and enter the name of the virtualenv you just created:
Database Configuration
Next, we will set up the MySQL production database. In the Databases tab of your PythonAnywhere dashboard, set a new password and then initialize a MySQL server:
The password above will be your database user password. Next, create a new database if you wish. PythonAnywhere already has a default database which you can use.
By default, the database user is your username, and has all privileges granted on any databases created. Now, we need to migrate the database and populate it with the tables. In a Bash console on PythonAnywhere, we will run the
flask db upgrade command, since we already have the migrations directory that we created locally. Before running the commands, ensure you are in your virtualenv as well as in the project directory.
$ export FLASK_CONFIG=production $ export FLASK_APP=run.py $ export SQLALCHEMY_DATABASE_URI='mysql://your-username:your-password@your-host-address/your-database-name' $ flask db upgrade
When setting the
SQLALCHEMY_DATABASE_URI environment variable, remember to replace
your-username,
your-host-address and
your-database-name with their correct values. The username, host address and database name can be found in the MySQL settings in the Databases tab on your dashboard. For example, using the information below, my database URI is:
mysql://projectdreamteam:password@projectdreamteam.mysql.pythonanywhere-services.com/projectdreamteam$dreamteam_db
WSGI File
Now we will edit the WSGI file, which PythonAnywhere uses to serve the app. Remember that we are not pushing the
instance directory to version control. We therefore need to configure the environment variables for production, which we will do in the WSGI file.
In the Code section of the Web tab on your dashboard, click on the link to the WSGI configuration file.
Delete all the current contents of the file, and replace them with the following:
import os import sys path = '/home/your-username/your-project-directory-name' if path not in sys.path: sys.path.append(path) os.environ['FLASK_CONFIG'] = 'production' os.environ['SECRET_KEY'] = 'p9Bv<3Eid9%$i01' os.environ['SQLALCHEMY_DATABASE_URI'] = 'mysql://your-username:your-password@your-host-address/your-database-name' from run import app as application
In the file above, we tell PythonAnywhere to get the variable
app from the
run.py file, and serve it as the application. We also set the
FLASK_CONFIG,
SECRET_KEY and
SQLALCHEMY_DATABASE_URI environment variables. Feel free to alter the secret key. Note that the
path variable should contain your username and project directory name, so be sure to replace it with the correct values. The same applies for the database URI environment variable.
We also need to edit our local
app/__init__py file to prevent it from loading the
instance/config.py file in production, as well as to load the configuration variables we've set:
# app/__init__.py # update imports import os # existing code remains def create_app(config_name): if os.getenv('FLASK_CONFIG') == "production": app = Flask(__name__) app.config.update( SECRET_KEY=os.getenv('SECRET_KEY'), SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI') ) else: app = Flask(__name__, instance_relative_config=True) app.config.from_object(app_config[config_name]) app.config.from_pyfile('config.py') # existing code remains
Push your changes to version control, and pull them on the PythonAnywhere Bash console:
$ git pull origin master
Now let's try loading the app on PythonAnywhere. First, we need to reload the app on the Web tab in the dashboard:
Now go to your app URL:
Great, it works! Try registering a new user and logging in. This should work just as it did locally.
Admin User
We will now create an admin user the same way we did locally. Open the Bash console, and run the following commands:
$ flask shell >>> from app.models import Employee >>> from app import db >>> admin = Employee(email="admin@admin.com",username="admin",password="admin2016",is_admin=True) >>> db.session.add(admin) >>> db.session.commit()
Now you can login as an admin user and add departments and roles, and assign them to employees.
Conclusion
Congratulations on successfully deploying your first Flask CRUD web app! From setting up a MySQL database, to creating models, blueprints (with forms and views), templates, custom error pages, tests, and finally deploying the app on PythonAnywhere, you now have a strong foundation in web development with Flask. I hope this has been as fun and educational for you as it has for me! I'm looking forward to hearing about your experiences in the comments below. | https://scotch.io/tutorials/build-a-crud-web-app-with-python-and-flask-part-three | CC-MAIN-2017-13 | refinedweb | 3,121 | 50.12 |
69224/hyperledger-getting-invalid-connection-profile-configuration
Hey, @Harinishree,
With error "Invalid network configuration due to missing configuration data" --> as I know from fabric-samples/balance-transfer project you need set config setting for client instant before you can call method loadFromConfig
when i create channel it showing error READ MORE
You need to map ~/.composer/cards of your Docker host ...READ MORE
Hi, the command you are using to ...READ MORE
You can get the value from the ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
To read and add data you can ...READ MORE
Hey, @Harinishree,
You can also do one thing, ...READ MORE
Hey, @Piyusha,
Looks like the network did not ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/69224/hyperledger-getting-invalid-connection-profile-configuration | CC-MAIN-2020-50 | refinedweb | 142 | 59.8 |
ncpy - copy part of a string
#include <string.h>
char *strncpy(char *restrict s1, const char *restrict s2, size_t n);
The strncpy() function shall copy not more than n bytes (bytes that follow a null byte are not copied) from the array pointed to by s2 to the array pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.
If the array pointed to by s2 is a string that is shorter than n bytes, null bytes shall be appended to the copy in the array pointed to by s1, until n bytes in all are written.() , . | http://manpages.sgvulcan.com/strncpy.3p.php | CC-MAIN-2017-26 | refinedweb | 103 | 71.18 |
SOAP interview questions
SOAP developers are in great demand as the platform has multiple benefits to offer. Facing an interview can tough especially if the field is updated continuously. Therefore I have gathered here a few frequently asked questions that can be asked during an interview. These questions answer most of the topics under SOAP and are popular among the interviewee.
Q1- Explain what is SOAP?
Ans- SOAP (Simple Object Access Protocol) is a communication protocol that facilitates the exchange of data over different networks. It is based on XML language that enables communication over different applications of Windows, Linux, etc. via the Internet. SOAP defines XML and HTTP messaging protocols and also uses the range of other protocols like FTP (File transfer protocol), SMTP (Simple Mail Transfer Protocol), POP3 (Post office protocol 3), etc. SOAP provides data transportation between web services and is used for broadcasting a message. It is a way to structure data prior to transmitting it.
Q2- Mention the differences between SOAP and other remote access techniques?
Ans- The following are the differences between SOAP and other remote web services such as DCOM, COBRA –
Q3- State the syntax rule for SOAP message?
Ans- Following is the syntax rule for SOAP message-
- A SOAP message should use XML that is encoded.
- A SOAP message MUST use the SOAP Envelope namespace.
- A SOAP message must NOT contain DTD reference.
- A SOAP message must NOT have an XML processing instruction.
Q4- Mention the advantages of SOAP web services?
Ans- SOAP is messaging based Web service that has been around for a while and enjoys almost all the benefits of long-term use. The following are few notable advantages of using SOAP web services-
- It is a language independent platform.
- It works well in a distributed runtime environment.
- SOAP payload can be received or obtained by web services and the platform information is entirely unrecognizable.
- SOAP uses XML structures for data transmission.
- It is very simple as compared with the COBRA, RMI, etc.
- It eliminates firewall problems as it uses HTTP.
- SOAP can also be used in combination with other protocols as well.
- It is the vendor neutral.
Q5- List out the important characteristics of SOAP envelop element.
Ans- The SOAP envelope indicates the start and end of the message so that the receiver knows when the entire message has been received. The important characteristics of SOAP envelop are-
- It has a root Envelop element, which is a mandatory part of the SOAP.
- SOAP element should not contain more than one header. Also, it should appear as the first part of the envelope.
- Envelop version changes with the upgradations in SOAP version.
- We add ENV as a prefix and envelop element to SOAP envelops.
- The optional SOAP encoding is also specified using a namespace.
Q6- What are the disadvantages of SOAP web services?
Ans- As every good thing comes with some cost, SOAP also has few disadvantages attached to it. Below are few disadvantages –
- SOAP only uses XML. It doesn’t take other formats like JSON into consideration.
- There is a high possibility of coupling between client and server as SOAP is based on contract.
- Since it uses XML format, SOAP is considered to be a slow platform because the payload is large for a simple string message.
- Any change in server contract is reflected in client stub classes.
- SOAP is hard to test in browsers.
- SOAP clients do not hold any stateful references to remote objects.
Q7- what is the difference between top down and bottom up approach in SOAP web services?
Ans- Top down SOAP web services involves creating WSDL document to a build a contract between web service and client. You can then add the required code. This is also known as contract first approach. The top-down approach is hard to implement because classes need to be written to confirm the contract established in WSDL. One of the advantages of using this approach is that it allows both client and server code to be written in parallel.
Bottom up SOAP web services require the code to be written first and then WSDL is created. It is also known as contract the last approach. Since WSDL is generated based on the code, bottom-up approach is easy to implement. Client codes have to wait for WSDL from the server side to start the work.
Q8- Enlist few frameworks in Java to implement SOAP web services.
Ans- SOAP web services are usually created using JAX-WS API. However, there are some other frameworks available in Java that can be used to implement SOAP web services. These are Apache Axis, Apache CXF, Jersey, CodeIgniter, etc. These frameworks are totally different from JAX-WS API and work on Servlet model to highlight the business logic as SOAP web services.
Q9- what are the differences between RPC Style and Document style SOAP web services?
Ans- RPC Style – In RPC Style, WSDL documents are generated based on method name and its parameters. In WSDL document, no type definitions are present. Under this, WSDL is difficult to validate against the schema. RPC styled messages are tightly coupled.
Document style web services can be validated against a predefined schema and content type. In document style, parameters are sent in XML formats. Here, the messages are loosely coupled.
Q10- Explain the utilities of SOAP web services to its users?
Ans- The following are the facilities that are offered by SOAP to its users-
- PutAddress() : This function is used for putting address in web pages. It carries address instance on SOAP call.
- PutListing() : It facilitates insertion of XML file into the webpage. This function reads the XML file, which is received as an argument and transports it to XML parser liaison. It then puts it as a parameter in the SOAP call.
- GetAddress(): It is a form of string text which determines a query name and sends the result that is synonymous with the query. The name is then sent to the SOAP call.
- GetAllListing() : This function transfers the complete list in XML format and then returns the same.
Thus, every interview panel wants to hire the best candidate for its firm. A technical topic demands practical knowledge. If an interviewer puts up a question, a candidate can answer it by referring to some of the examples he did earlier while using the platform showcasing his talent. It will give an upper edge to him. Thus, it’s important that one must know all the essentials of a topic before appearing for an interview. | https://www.onlineinterviewquestions.com/soap-interview-questions/ | CC-MAIN-2018-26 | refinedweb | 1,088 | 66.44 |
Important: Please read the Qt Code of Conduct -
Can't resize window
I've got a window but I can't drag to resize it. Also, the usual 'X' close button is not there so I have to close the application through the debugger. I think these are probably related.
I think I have used the correct Window flags but seems to have no effect.
import QtQuick 2.9 import QtQuick.Window 2.2 import QtQuick.Controls 2.2 import QtQuick.Layouts 1.3 import QtQuick.Controls.Styles 1.4 Window { id: window visible: true width: 900 height: 900 flags: Qt.Window | Qt.WindowTitleHint | Qt.WindowCloseButtonHint title: qsTr("SLD Quick")
Can anyone help?
- raven-worx Moderators last edited by raven-worx
@fraz
how exactly are you displaying this QML code? Meaning how does your main() look like?
flags: Qt.Window | Qt.WindowTitleHint | Qt.WindowCloseButtonHint
Also those extra provided flags are already contained in the Qt.Window flag, so actually you can leave the whole property definition out. Or do you have anything special in mind?
The current program is very barebones at the moment as I'm just starting to learn how to use Qt Quick. Here's what main.cpp looks like:
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQuickStyle> int main(int argc, char *argv[]) { #if defined(Q_OS_WIN) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QGuiApplication app(argc, argv); QQmlApplicationEngine engine; QQuickStyle::setStyle("Fusion"); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); } | https://forum.qt.io/topic/86956/can-t-resize-window | CC-MAIN-2020-40 | refinedweb | 248 | 53.07 |
I am playing with android ndk. I am using Window Vista with cygwin (latest version). I compiled and launched the hello world jni sample on my phone. It is working. The code is (is a .cpp file):
#include <string.h>
#include <jni.h>
extern "C" {
JNIEXPORT jstring JNICALL Java_org_android_helloworld_HelloworldActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis);
};
jstring Java_org_android_helloworld_HelloworldActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis)
{
return env->NewStringUTF("Hello from native code!");
}
I wanted to add some modifications, just to play with it a bit:
#include <algorithm>
and then, in the function above, i added:
int a;
a=std::min<int>(10, 5);
but the compiler says that it cannot find the file 'algorithm' and that min() is not part of std.
After a bit of searching, i have found that the android ndk has a gnu-libstdc++ directory with all the std files needed. Reading the NDK docs, i have learned that usint std::* should work without any modification to the code (if one include the proper header files). But it seems that gcc on cygwin is not able to find the needed files.
What are the steps to do in order to be able to use std and stl within a .cpp file in an android ndk app?
Thx | http://www.anddev.org/ndk-problems-f56/cygwin-gcc-cannot-find-the-stdlibc-files-t55118.html | CC-MAIN-2014-42 | refinedweb | 205 | 65.83 |
Original text by Chris Moberly
In January 2019, I discovered a privilege escalation vulnerability in default installations of Ubuntu Linux. This was due to a bug in the snapd API, a default service. Any local user could exploit this vulnerability to obtain immediate root access to the system.
Two working exploits are provided in the dirty_sock repository:
- dirty_sockv1: Uses the ‘create-user’ API to create a local user based on details queried from the Ubuntu SSO.
- dirty_sockv2: Sideloads a snap that contains an install-hook that generates a new local user.
Both are effective on default installations of Ubuntu. Testing was mostly completed on 18.10, but older verions are vulnerable as well.
The snapd team’s response to disclosure was swift and appropriate. Working with them directly was incredibly pleasant, and I am very thankful for their hard work and kindness. Really, this type of interaction makes me feel very good about being an Ubuntu user myself.
TL;DR exploits linked above demonstrate two possibilities.
Background — What is Snap?” where developers can contribute and maintain ready-to-go packages.
Management of locally installed snaps and communication with this online store are partially handled by a systemd service called “snapd”. This service is installed automatically in Ubuntu and runs under the context of the “root” user. Snapd is evolving into a vital component of the Ubuntu OS, particularly in the leaner spins like “Snappy Ubuntu Core” for cloud and IoT.
Vulnerability Overview
Interesting Linux OS Information
Linux uses a type of UNIX domain socket called “AF_UNIX” which is used to communicate between processes on the same machine. This is in contrast to “AF_INET” and “AF_INET6” sockets, which are used for processes to communicate over a network connection.
The lines shown above tell us that two socket files are being created. The ‘0666’ mode is setting the file permissions to read and write for all, which is required to allow any process to connect and communicate with the socket.
We can see the filesystem representation of these sockets here:
$.
This is enough information now to know that we have a good target for exploitation — a hidden HTTP service that is likely not widely tested as it is not readily apparent using most automated privilege escalation checks.
NOTE: Check out my work-in-progress privilege escalation tool uptux that would identify this as interesting.
Vulnerable Code
Being an open-source project, we can now move on to static analysis via source code. The developers have put together excellent documentation on this REST API available here.
The API function that stands out as highly desirable for exploitation is “POST /v2/create-user”, which is described simply as “Create a local user”. The documentation tells us that this call requires root level access to execute.
But how exactly does the daemon determine if the user accessing the API already has root?
Reviewing the trail of code brings us to this file (I’ve linked the historically vulnerable version).
Let’s look at this line:
ucred, err := getUcred(int(f.Fd()), sys.SOL_SOCKET, sys.SO_PEERCRED)
This is calling one of golang’s standard libraries to gather user information related to the socket connection.
Basically, the AF_UNIX socket family has an option to enable receiving of the credentials of the sending process in ancillary data (see
man unix from the Linux command line).
This is a fairly rock solid way of determining the permissions of the process accessing the API.
Using a golang debugger called delve, we can see exactly what this returns while executing the “nc” command from above. Below is the output from the debugger when we set a breakpoint at this function and then use delve’s “print” command to show what the variable “ucred” currently holds:
> github.com/snapcore/snapd/daemon.(*ucrednetListener).Accept() ... 109: ucred, err := getUcred(int(f.Fd()), sys.SOL_SOCKET, sys.SO_PEERC, where connection info is added to a new object along with the values discovered above:
func (wc *ucrednetConn) RemoteAddr() net.Addr { return &ucrednetAddr{wc.Conn.RemoteAddr(), wc.pid, wc.uid, wc.socket} }
…and then a bit more in this one, where all of these values are concatenated into a single string variable:
func (wa *ucrednetAddr) String() string { return fmt.Sprintf("pid=%s;uid=%s;socket=%s;%s", wa.pid, wa.uid, wa.socket, wa.Addr) }
..and is finally parsed by this function, where that combined string is broken up again into individual parts:
func ucrednetGet(remoteAddr string) (pid uint32, uid uint32, socket string, err error) { ... for _, token := range strings.Split(remoteAddr, ";") { var v uint64 ... } else if strings.HasPrefix(token, "uid=") { if v, err = strconv.ParseUint(token[4:], 10, 32); err == nil {.com/snapcore/snapd/daemon.ucrednetGet() ... => 41: for _, token := range strings.Split(remoteAddr, ";") { ... (dlv) print remoteAddr "pid=5127;uid=1000;socket=/run/snapd.socket;@"
Now, instead of an object containing individual properties for things like the uid and pid, we have a single string variable with everything concatenated together. This string contains four unique elements. The second element “uid=1000” is what is currently controlling permissions.
If we imagine the function splitting this string up by “;” and iterating through, we see that there are two sections that (if containing the string “uid=”) could potentially overwrite the first “uid=”, if only we could influence them.
The first (“socket=/run/snapd.socket”) is the local “network address” of the listening socket — the file path the service is defined to bind to. We do not have permissions to modify snapd to run on another socket name, so it seems unlikely that we can modify this.).LocalAddr() /usr/lib/go-1.10/src/net/net.go:210 (PC: 0x77f65f) ... => 210: func (c *conn) LocalAddr() Addr { ... (dlv) print c.fd ... laddr: net.Addr(*net.UnixAddr) *{ Name: "/run/snapd.socket", Net: "unix",}, raddr: net.Addr(*net.UnixAddr) *{Name: "@", Net: "unix"},}
The remote address is set to that mysterious “@” sign. Further reading the
man unix help pages provides information on what is called the “abstract namespace”. This is used to bind sockets which are independent of the filesystem. Sockets in the abstract namespace begin with a null-byte character, which is often displayed as “@” in terminal output.
Instead of relying on the abstract socket namespace leveraged by netcat, we can create our own socket bound to a file name that we control. This should allow us to affect the final portion of that string variable that we want to modify, which will land in the “raddr” variable shown above..socket(socket.AF_UNIX, socket.SOCK_STREAM) client_sock.bind(sockfile) ## Connect to the snap daemon client_sock.connect('/run/snapd.socket')
Now watch what happens in the debugger when we look at the remoteAddr variable again:
> github.com/snapcore/snapd/daemon.ucrednetGet() ... => 41: for _, token := range strings.Split(remoteAddr, ";") { ... (dlv) print remoteAddr "pid=5275;uid=1000;socket=/run/snapd.socket;/tmp/sock;uid=0;".com/snapcore/snapd/daemon.ucrednetGet() ... => 65: return pid, uid, socket, err ... (dlv) print uid 0
Weaponizing
Version One
dirty_sockv1 leverages the ‘POST /v2/create-user’ API function. To use this exploit, simply create an account on the Ubuntu SSO and upload an SSH public key to your profile. Then, run the exploit like this (using the email address you registered and the associated SSH private key):
$ dirty_sockv1.py -u you@email.com -k id_rsa
This is fairly reliable and seems safe to execute. You can probably stop reading here and go get root.
Still reading? Well, the requirement for an Internet connection and an SSH service bothered me, and I wanted to see if I could exploit in more restricted environments. This leads us to…
Version Two
dirty_sockv2 instead uses the ‘POST /v2/snaps’ API to sideload a snap containing a bash script that will add a local user. This works on systems that do not have the SSH service running. It also works on newer Ubuntu versions with no Internet connection at all. HOWEVER, sideloading does require some core snap pieces to be there. If they are not there, this exploit may trigger an update of the snapd service. My testing shows that this will still work, but it will only work ONCE in this scenario.
Snaps themselves run in sandboxes and require digital signatures matching public keys that machines already trust. However, it is possible to lower these restrictions by indicating that a snap is in development (called “devmode”). This will give the snap access to the host Operating System just as any other application would have.
Additionally, snaps have something called “hooks”. One such hook, the “install hook” is run at the time of snap installation and can be a simple shell script. If the snap is configured in “devmode”, then this hook will be run in the context of root.
I created a snap from scratch that is essentially empty and has no functionality. What it does have, however, is a bash script that is executed at install time. That bash script runs the following commands:
That encrypted string is simply the text
dirty_sock created with Python’s
crypt.crypt() function.
The commands below show the process of creating this snap in detail. This is all done from a development machine, not the target. One the snap is created, it is converted to base64 text to be included in the full python exploit.
## Install necessary tools sudo apt install snapcraft -y ## Make an empty directory to work with cd /tmp mkdir dirty_snap cd dirty_snap ## Initialize the directory as a snap project snapcraft init ## Set up the install hook mkdir snap/hooks touch snap/hooks/install chmod a+x snap/hooks/install ## Write the script we want to execute as root cat > snap/hooks/install << "EOF" #!/bin/bash EOF ## Configure the snap yaml file cat > snap/snapcraft.yaml << "EOF" name: dirty-sock version: '0.1' summary: Empty snap, used for exploit description: | See grade: devel confinement: devmode parts: my-part: plugin: nil EOF ## Build the snap snapcraft
If you don’t trust the blob I’ve put into the exploit, you can manually create your own with the method above.
Once we have the snap file, we can use bash to convert it to base64 as follows:
$ base64 <snap-filename.snap>
That base64-encoded text can go into the global variable “TROJAN_SNAP” at the beginning of the dirty_sock.py exploit.
The exploit itself is writen in python and does the following:
-
Protection / Remediation
Patch your system! The snapd team fixed this right away after my disclosure.
Special Thanks
- So many StackOverflow posts I lost track…
- The great resources put together by the snap team
Author
Chris Moberly (@init_string) from The Missing Link.
Thanks for reading!!! | https://movaxbx.ru/2019/02/13/privilege-escalation-in-ubuntu-linux-dirty_sock-exploit/ | CC-MAIN-2019-26 | refinedweb | 1,766 | 56.05 |
My Journey
JavaScript’s built in Array map, reduce, filter, every, and some iterator functions are second nature to me. But recently, I needed to build some functionality that required asynchronous callback functions. Let’s see how we can accomplish this.
Map
map iterates through the array, calculates the result for each element using the provided callback function, and returns a new array of results.
[1, 2, 3].map(i => i * 2); // [2, 4, 6]
If the provided function returns a promise, map unfortunately will not resolve the promise.
[1, 2, 3].map(async i => i * 2); // [Promise, Promise, Promise]
But resolving this is quite simple. Promise provides a built-in Promise.all function that will resolve all the promises in an array — the exact output we expected from map.
await Promise.all([1, 2, 3].map(async i => i * 2)); // [2, 4, 6]
Reduce
reduce iterates through the array and aggregates a single value based on the provided callback reducer function.
[1, 2, 3].map((acc, i) => acc + i, 0) // 6
If the provided function returns a promise, reduce will error.
[1, 2, 3].reduce(async (acc, i) => { return acc + i; }, 0); // Error
Why? Because acc is the response of the previous iteration, it is a promise itself — and you can’t aggregate on a promise. You will need to resolve acc first before aggregating.
[1, 2, 3].reduce(async (acc, i) => { return (await acc) + i; }, 0); // 6
Filter
filter iterates through the array and returns a new array with only elements that pass the provided callback test function.
[1, 2, 3].filter(i => i < 3); // [1, 2]
If the provided filter function returns a promise, filter will not work as expected and instead, will return the entire array. This is because the async function returns a promise but the filter function does not resolve the promise. Instead it directly uses the promise, which evaluates to true, causing the filter function include the element in the result.
[1, 2, 3].filter(async i => i < 3); // [1, 2, 3]
Unfortunately, filter cannot support promises but you can indirectly achieve the result using map.
const array = [1, 2, 3]; const mapResult = await Promise.all(array.map(async i => i < 3)); array.filter((_, idx) => mapResult[idx]); // [1, 2]
First, using the the asynchronous map method as mentioned before, we calculate whether the element passes the filter function test and resolve all the promises. This yields an array of booleans which can then be used to determine which elements in the original array should be included in the result.
Every / Some
every checks that all elements in an array passes the provided callback test function and some checks that at least one element in an array passes.
[1, 2, 3].every(i => i < 3); // false [1, 2, 3].some(i => i < 3); // true
Just like with filter, if the provided test function returns a promise, every and some will not work as expected. Instead, they will always return true, because the unresolved promise will evaluate to true.
[1, 2, 3].every(async i => i < 3); // true [1, 2, 3].some(async i => i < 3); // true
The solution is similar to that of filter’s — by using asynchronous map to evaluate the test and iterating through the results.
const array = [1, 2, 3]; const mapResult = await Promise.all(array.map(async i => i < 3)); array.every((_, idx) => mapResult[idx]); // false array.some((_, idx) => mapResult[idx]); // true
The downside to this approach is that every element in the iteration will have their promise resolved. every and some can short-circuit and exist as soon as the first false and true result, respectively, is calculated, saving on computation time. To match this behavior, you have to iterate through the array and run the test function one at a time with a regular for loop.
const asyncFunction = async i => i < 3; let everyResult = true; for (let i of [1, 2, 3]) { if (!(await asyncFunction(i))) { everyResult = false; break; } } // everyResult = false let someResult = false; for (let i of [1, 2, 3]) { if (await asyncFunction(i)) { someResult = true; break; } } // someResult = true
Final Thoughts
map, reduce, filter, every, and some can all handle async callback functions with just a little bit of tweaking. While not covered here, other built in Array methods such as find, findIndex, forEach, and reduceRight can also handle async callback functions using the same methodology. Can you figure out how? | https://plainenglish.io/blog/a-guide-to-asynchronous-array-iterator-functions | CC-MAIN-2022-40 | refinedweb | 737 | 65.42 |
When I attended my coding boot camp late last year we learned Ruby and started with Sinatra before we moved onto Ruby on Rails. I remember not liking it too much but maybe that's because I was mentally exhausted from everything we were learning!
Now that I have graduated, I've been looking into Python a lot. I consider Python and Ruby to be very similar backend languages, however, Python is undoubtedly more popular. I remember searching for help for Sinatra but the blog posts that would show up in Google Search were from years ago! This is the main reason I switched from Ruby to Python: a stronger, more active community.
With that being said, Sinatra and Flask are two very similar web frameworks. They are the bare-bones counterparts to Ruby on Rails and Django — frameworks you've probably heard more about. While Flask can get you up and running for a small app, you have to do everything yourself. This may sound bad but it allows you, the developer, to have complete customization and control of your framework. I actually wrote Ninny Code! using Flask!
In this blog post, I'm going to show you how to create a very basic Flask app that returns "Hello World" when you visit it in your browser. Let's get started!
Python uses virtual environments to encapsulate your project. Instead of accessing anything and everything located in your computer, virtual environments localizes your production within the project. There are several ways to create a virtual environment but I found pipenv to be the easiest. Let's create an empty project directory and create our virtual environment:
mkdir helloworld cd helloworld pip install pipenv pipenv shell
The command
pipenv shell creates our virtual environment. Again, this localizes our project into this directory. You'll notice it created a Pipfile for you. If you're new to pipenv, instead of running
pip to install packages, you use
pipenv instead. So let's install Flask then create our app.py:
pipenv install flask
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!'
And, honestly, that's it. This is the minimum amount of code you need to create a web app. In your terminal, enter
flask run to start your server. You'll now see something like
Running on in your terminal. This is telling us that our site is now live and can be visited at that address in your browser (or localhost:5000)!
You should see the text "Hello World!". Congrats on making your first Flask application! If this tickles your fancy, I suggest you take a look at the (Flask docs) for a lot more info. I also think you should take a look at my public repo for Ninny Code! so you can get an idea of what a beefier Flask app looks like :D
Discussion (1)
If your using Flask as a backend service you can just use FastAPI and use JavaScript frontend to make it work. | https://dev.to/2spacemilk/hello-world-with-flask-105g | CC-MAIN-2022-05 | refinedweb | 505 | 73.37 |
Converting all of our modern JavaScript into ES5 compatible syntax is a great way to use modern features while targeting older browsers. What happens when the browsers natively support these language features? Then it no longer makes sense to transform that code or to include polyfills that will go unused. In this lesson, we’ll add the
@babel/polyfill package and configure
babel-preset-env
the video shows npm i -S @babel/polyfill but the transcript shows npm i -S @level/polyfill This cought me out for a minute, just use the @babel/polyfill and it all works fine.
The setting should be 'not IE 11' (space between IE and 11).
These series of lectures contain amazing tips!
Thank you Andy!!
I am having trouble building:
ERROR in ./src/index.js Module not found: Error: Can't resolve 'core-js/modules/es7.string.trim-left' in '/Users/alex/work/personal/react-biolerplate/src' @ ./src/index.js 2:0-46
I am having trouble building:
ERROR in ./src/index.js Module not found: Error: Can't resolve 'core-js/modules/es7.string.trim-left' in '/Users/alex/work/personal/react-biolerplate/src' @ ./src/index.js 2:0-46
npm i -D core-js@2.5.7 resolves this for me. core-js@3.x does not have the module :-(
thx @Alex!! =)
Looks like @babel/polyfill is deprecated, as of c 7.4.0
npm i -S @babel/polyfill npm WARN deprecated @babel/polyfill@7.4.4: 🚨";
core-js@2.6.9 postinstall /Volumes/Development/Learning/React/react-starter/node_modules/core-js node scripts/postinstall || echo "ignore"
If we have have babel/polyfill, does babel now still transpile es5+ code or does it only add polyfills or does it do a mix of both ?
A few notes, babel/polyfill is now deprecated, so it's useful to still install it, but then you need to:
import "core-js/stable"; import "regenerator-runtime/runtime";
instead of importing @babel/polyfill.
Then, in your config, you need to add: targets: [ "last 2 versions", "not dead", "not < 2%", "not ie 11", ], useBuiltIns: "entry", corejs: "3.0.0",
the last line.
Otherwise it won't trim down your bundle and you'll be very confused as to why it wasn't changing, even though all it was throwing was a warning. | https://egghead.io/lessons/babel-target-specific-browsers-with-babel-preset-env-and-the-babel-pollyfill | CC-MAIN-2021-21 | refinedweb | 384 | 58.28 |
view raw
First a little setup. Last week I was having trouble implementing a specific methodology that I had constructed which would allow me to manage two unique fields associated with one db.Model object. Since this isn't possible, I created a parent entity class and a child entity class, each having the key_name assigned one of the unique values. You can find my previous question located here, which includes my sample code and a general explaination of my insertion process.
On my original question, someone commented that my solution would not solve my problem of needing two unique fields associated with one db.Model object.
My implementation tried to solve this problem by implementing a static method that creates a ParentEntity and it's key_name property is assigned to one of my unique values. In step two of my process I create a child entity and assign the parent entity to the parent parameter. Both of these steps are executed within a db transaction so I assumed that this would force the uniqueness contraint to work since both of my values were stored within two, separate key_name fields across two separate models.
The commenter pointed out that this solution would not work because when you set a parent to a child entity, the key_name is no longer unique across the entire model but, instead, is unique across the parent-child entries. Bummer...
I believe that I could solve this new problem by changing how these two models are associated with one another.
First, I create a parent object as mentioned above. Next, I create a child entity and assign my second, unique value to it's key_name. The difference is that the second entity has a reference property to the parent model. My first entity is assigned to the reference property but not to the parent parameter. This does not force a one-to-one reference but it does keep both of my values unique and I can manage the one-to-one nature of these objects so long as I can control the insertion process from within a transaction.
This new solution is still problematic. According to the GAE Datastore documentation you can not execute multiple db updates in one transaction if the various entities within the update are not of the same entity group. Since I no longer make my first entity a parent of the second, they are no longer part of the same entity group and can not be inserted within the same transaction.
I'm back to square one. What can I do to solve this problem? Specifically, what can I do to enforce two, unique values associated with one Model entity. As you can see, I am willing to get a bit creative. Can this be done? I know this will involve an out-of-the-box solution but there has to be a way.
Below is my original code from my question I posted last week. I've added a few comments and code changes to implement my second attempt at solving this problem.
class ParentEntity(db.Model):
str1_key = db.StringProperty()
str2 = db.StringProperty()
@staticmethod
def InsertData(string1, string2, string3):
try:
def txn():
#create first entity
prt = ParentEntity(
key_name=string1,
str1_key=string1,
str2=string2)
prt.put()
#create User Account Entity
child = ChildEntity(
key_name=string2,
#parent=prt, #My prt object was previously the parent of child
parentEnt=prt,
str1=string1,
str2_key=string2,
str3=string3,)
child.put()
return child
#This should give me an error, b/c these two entities are no longer in the same entity group. :(
db.run_in_transaction(txn)
except Exception, e:
raise e
class ChildEntity(db.Model):
#foreign and primary key values
str1 = db.StringProperty()
str2_key = db.StringProperty()
#This is no longer a "parent" but a reference
parentEnt = db.ReferenceProperty(reference_class=ParentEntity)
#pertinent data below
str3 = db.StringProperty()
After scratching my head a bit, last night I decided to go with the following solution. I would assume that this still provides a bit of undesirable overhead for many scenarios, however, I think the overhead may be acceptable for my needs.
The code posted below is a further modification of the code in my question. Most notably, I've created another Model class, called named EGEnforcer (which stands for Entity Group Enforcer.)
The idea is simple. If a transaction can only update multiple records if they are associated with one entity group, I must find a way to associate each of my records that contains my unique values with the same entity group.
To do this, I create an EGEnforcer entry when the application initially starts. Then, when the need arises to make a new entry into my models, I query the EGEnforcer for the record associated with my paired models. After I get my EGEnforcer record, I make it the parent of both records. Viola! My data is now all associated with the same entity group.
Since the *key_name* parameter is unique only across the parent-key_name groups, this should inforce my uniqueness constraints because all of my FirstEntity (previously ParentEntity) entries will have the same parent. Likewise, my SecondEntity (previously ChildEntity) should also have a unique value stored as the key_name because the parent is also always the same.
Since both entities also have the same parent, I can execute these entries within the same transaction. If one fails, they all fail.
#My new class containing unique entries for each pair of models associated within one another. class EGEnforcer(db.Model): KEY_NAME_EXAMPLE = 'arbitrary unique value' @staticmethod setup(): ''' This only needs to be called once for the lifetime of the application. setup() inserts a record into EGEnforcer that will be used as a parent for FirstEntity and SecondEntity entries. ''' ege = EGEnforcer.get_or_insert(EGEnforcer.KEY_NAME_EXAMPLE) return ege class FirstEntity(db.Model): str1_key = db.StringProperty() str2 = db.StringProperty() @staticmethod def InsertData(string1, string2, string3): try: def txn(): ege = EGEnforcer.get_by_key_name(EGEnforcer.KEY_NAME_EXAMPLE) prt = FirstEntity( key_name=string1, parent=ege) #Our EGEnforcer record. prt.put() child = SecondEntity( key_name=string2, parent=ege, #Our EGEnforcer record. parentEnt=prt, str1=string1, str2_key=string2, str3=string3) child.put() return child #This works because our entities are now part of the same entity group db.run_in_transaction(txn) except Exception, e: raise e class SecondEntity(db.Model): #foreign and primary key values str1 = db.StringProperty() str2_key = db.StringProperty() #This is no longer a "parent" but a reference parentEnt = db.ReferenceProperty(reference_class=ParentEntity) #Other data... str3 = db.StringProperty()
One quick note-- Nick Johnson pinned my need for this solution:
This solution may be sufficient to your needs - for instance, if you need to enforce that every user has a unique email address, but this is not your primary identifier for a user, you can insert a record into an 'emails' table first, then if that succeeds, insert your primary record.
This is exactly what I need but my solution is, obviously, a bit different than your suggestion. My method allows for the transaction to completely occur or completely fail. Specifically, when a user creates an account, they first login to their Google account. Next, they are forced to the account creation page if there is no entry associated with their Google account in SecondEntity (which is actually UserAccount form my actual scenario.) If the insertion process fails, they are redirected to the creation page with the reason for this failure.
This could be because their ID is not unique or, potentially, a transactional timeout. If there is a timeout on the insertion of their new user account, I will want to know about it but I will implement some form of checks-and-balance in the near future. For now I simply want to go live, but this uniqueness constraint is an absolute necessity.
Being that my approach is strictly for account creation, and my user account data will not change once created, I believe that this should work and scale well for quite a while. I'm open for comments if this is incorrect. | https://codedump.io/share/TrpP850Hlefl/1/how-can-i-create-two-unique-queriable-fields-for-a-gae-datastore-data-model | CC-MAIN-2017-22 | refinedweb | 1,324 | 55.03 |
Introduced since Python 3.5, Python’s typing module attempts to provide a way of hinting types to help static type checkers and linters accurately predict errors.
Due to Python having to determine the type of objects during run-time, it sometimes gets very hard for developers to find out what exactly is going on in the code.
Even external type checkers like PyCharm IDE do not produce the best results; on average only predicting errors correctly about 50% of the time, according to this answer on StackOverflow.
Python attempts to mitigate this problem by introducing what is known as type hinting (type annotation) to help external type checkers identify any errors. This is a good way for the programmer to hint the type of the object(s) being used, during compilation time itself and ensure that the type checkers work correctly.
This makes Python code much more readable and robust as well, to other readers!
NOTE: This does not do actual type checking at compile time. If the actual object returned was not of the same type as hinted, there will be no compilation error. This is why we use external type checkers, such as mypy to identify any type errors.
Table of Contents
Recommended Prerequisites
For using the
typing module effectively, it is recommended that you use an external type checker/linter to check for static type matching. One of the most widely used type checkers in use for Python is mypy, so I recommend that you install it before reading the rest of the article.
We have already covered the basics of type checking in Python. You can go through this article first.
We will be using
mypy as the static type checker in this article, which can be installed by:
pip3 install mypy
You can run
mypy to any Python file to check if the types match. This is as if you are ‘compiling’ Python code.
mypy program.py
After debugging errors, you can run the program normally using:
python program.py
Now that we have our prerequisites covered, let’s try to use some of the module’s features.
Type Hints / Type Annotations
On functions
We can annotate a function to specify its return type and the types of its parameters.
def print_list(a: list) -> None: print(a)
This informs the type checker (
mypy in my case) that we have a function
print_list(), that will take a
list as an argument and return
None.
def print_list(a: list) -> None: print(a) print_list([1, 2, 3]) print_list(1)
Let’s run this on our type checker
mypy first:
vijay@JournalDev:~ $ mypy printlist.py printlist.py:5: error: Argument 1 to "print_list" has incompatible type "int"; expected "List[Any]" Found 1 error in 1 file (checked 1 source file)
As expected, we get an error; since the line #5 has the argument as an
int, rather than a
list.
On Variables
Since Python 3.6, we can also annotate the types of variables, mentioning the type. But this is not compulsory if you want the type of a variable to change before the function returns.
# Annotates 'radius' to be a float radius: float = 1.5 # We can annotate a variable without assigning a value! sample: int # Annotates 'area' to return a float def area(r: float) -> float: return 3.1415 * r * r print(area(radius)) # Print all annotations of the function using # the '__annotations__' dictionary print('Dictionary of Annotations for area():', area.__annotations__)
Output of mypy:
vijay@JournalDev: ~ $ mypy find_area.py && python find_area.py Success: no issues found in 1 source file 7.068375 Dictionary of Annotations for area(): {'r': <class 'float'>, 'return': <class 'float'>}
This is the recommended way to use
mypy, first providing type annotations, before using the type checker.
Type Aliases
The
typing module provides us with Type Aliases, which is defined by assigning a type to the alias.
from typing import List # Vector is a list of float values Vector = List[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] a = scale(scalar=2.0, vector=[1.0, 2.0, 3.0]) print(a)
Output
vijay@JournalDev: ~ $ mypy vector_scale.py && python vector_scale.py Success: no issues found in 1 source file [2.0, 4.0, 6.0]
In the above snippet,
Vector is an alias, which stands for a list of floating point values. We can type hint at an alias, which is what the above program is doing.
The complete list of acceptable aliases is given here.
Let’s look at one more example, which checks every key:value pair in a dictionary and check if they match the name:email format.
from typing import Dict import re # Create an alias called 'ContactDict' ContactDict = Dict[str, str] def check_if_valid(contacts: ContactDict) -> bool: for name, email in contacts.items(): # Check if name and email are strings if (not isinstance(name, str)) or (not isinstance(email, str)): return False # Check for email xxx@yyy.zzz if not re.match(r"[a-zA-Z0-9\._\+-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]+$", email): return False return True print(check_if_valid({'vijay': 'vijay@sample.com'})) print(check_if_valid({'vijay': 'vijay@sample.com', 123: 'wrong@name.com'}))
Output from mypy
vijay@JournalDev:~ $ mypy validcontacts.py validcontacts.py:19: error: Dict entry 1 has incompatible type "int": "str"; expected "str": "str" Found 1 error in 1 file (checked 1 source file)
Here, we get a static compile time error in
mypy, since the
name parameter on our second dictionary is an integer (123). Thus, aliases are another way to enforce accurate type checking from
mypy.
Create user defined datatypes using NewType()
We can use the
NewType() function to create new user defined types.
from typing import NewType # Create a new user type called 'StudentID' that consists of # an integer StudentID = NewType('StudentID', int) sample_id = StudentID(100)
The static type checker will treat the new type as if it were a subclass of the original type. This is useful in helping catch logical errors.
from typing import NewType # Create a new user type called 'StudentID' StudentID = NewType('StudentID', int) def get_student_name(stud_id: StudentID) -> str: return str(input(f'Enter username for ID #{stud_id}:\n')) stud_a = get_student_name(StudentID(100)) print(stud_a) # This is incorrect!! stud_b = get_student_name(-1) print(stud_b)
Output from mypy
vijay@JournalDev:~ $ mypy studentnames.py studentnames.py:13: error: Argument 1 to "get_student_name" has incompatible type "int"; expected "StudentID" Found 1 error in 1 file (checked 1 source file)
The Any type
This is a special type, informing the static type checker (
mypy in my case) that every type is compatible with this keyword.
Consider our old
print_list() function, now accepting arguments of any type.
from typing import Any def print_list(a: Any) -> None: print(a) print_list([1, 2, 3]) print_list(1)
Now, there will be no errors when we run
mypy.
vijay@JournalDev:~ $ mypy printlist.py && python printlist.py Success: no issues found in 1 source file [1, 2, 3] 1
All functions without a return type or parameter types will implicitly default to using
Any.
def foo(bar): return bar # A static type checker will treat the above # as having the same signature as: def foo(bar: Any) -> Any: return bar
You can thus use Any to mix up statically and dynamically typed code.
Conclusion
In this article, we have learned about the Python typing module, which is very useful in the context of type checking, allowing external type checkers like
mypy to accurately report any errors.
This provides us with a way to write statically typed code in Python, which is a dynamically typed language by design!
References
- Python Documentation for the typing module (This contains extensive detail on more methods in this module, and I recommend this as a secondary reference)
- StackOverflow question on type hints (This provides a very good discussion on the topic. I highly recommend you to read this topic as well!) | https://www.journaldev.com/34519/python-typing-module | CC-MAIN-2021-25 | refinedweb | 1,317 | 61.67 |
- Fund Type: ETF
- Objective: Broad Market
- Asset Class: Equity
- Geographic Focus: Australia
Vanguard Australian Shares High Yield ETF+ Add to Watchlist
VHY:AU65.8600 AUD 0.3100 0.47%
As of 23:43:26 ET on 01/29/2015.
Snapshot for Vanguard Australian Shares High Yield ETF (VHY)
ETF Chart for VHY
- VHY:AU 65.8600
Previous Close
- 1D
- 1W
- 1M
- YTD
- 1Y
- 3Y
- 5Y
Fund Profile & Information for VHY
Vanguard Australian Shares High Yield ETF is an exchange traded fund incorportated in Australia. The Fund seeks to match the return (income and capital appreciation) of the FTSE ASFA Australia High Dividend Yield Index before fees and expenses.
Fundamentals for VHY
Dividends for VHY
Performance for VHY
Top Fund Holdings for VHYFiling Date: 12/31/2014
Quotes delayed, except where indicated otherwise. Mutual fund NAVs include dividends. All prices in local currency. Time is ET.
- 1
- 2
- 3
- 4
- 5 | http://www.bloomberg.com/quote/VHY:AU | CC-MAIN-2015-06 | refinedweb | 150 | 67.25 |
I need to test sub-domains on my localhost. How can I effectively have this result of adding *.localhost.com to m /etc/hosts/ file?
If it's not possible, how do I work around this problem? I need to test wildcard sub-domains on my localserver. It is a Django dev server, can the django dev server handle the sub-domains? Can some other piece of software/routing give me the end result I want?
This question came from our site for professional and enthusiast programmers.
I have written a dns proxy in Python. It will read wildcard entries in /etc/hosts. See here:
pip install
Install dnsmasq (I do this on all my Linux desktops as a DNS cache anyways). In dnsmasq.conf add the line:
dnsmasq.conf
address=/localhost.com/127.0.0.1
sudo port install dnsmasq
/opt/local/etc/dnsmasq.conf
sudo port load dnsmasq
It is not possible to specify wildcards in the /etc/hosts file. Either specify the required hostnames explicitly or alternatively set up a local name server with the appropriate rules.
/etc/hosts
You need to set up a DNS server and have each client use it for resolution. The server itself can be something as "light" as dnsmasq or as heavy as BIND.
This DNS based solution worked perfectly in my case, without need to install anything : (Mac OSX 10.7)
You cannot use a wildcard in /etc/hosts.
Have a look here for a good walkthrough on how to accomplish on OS X using BIND, the built-in but inactive DNS server, and Apache.
I've tidied up an old project of mine:
requirements:
Advantages over using dnsmasq or the python dns proxy:
I personally like to create a PAC file for that and make my browser just use it.
Step 1: create a file e.g.: .proxy.pac somewhere (I use my $home folder)
Step 2: paste this code (example is with port 8000):
function FindProxyForURL(url, host) {
if (shExpMatch(host, "*localhost")) {
return "PROXY localhost:8000";
}
return "DIRECT";
}
Step 3:
Make your Browser use this PAC file.
Youtube Video for PAC & Firefox
Step 4:
Now you can test your app by accessing: ""
Step 5: Enjoy :)
The short answer is you don't. The longer answer is you need to be clearer on what you desire to actually achieve, because there is perhaps either a better way, and a different way to achieve it.
For web-hosting (I've never seen it used otherwise) is done in DNS in combination with a virtual hosting aware web server. For more information on wildcard DNS records (Wikipedia), and an article Wildcard hosting with Apache and Bind for Linux using bind and Apache.
At worst, you could use a local DNS server I suppose.
I would have commented on tomchuk's excellent answer, but I do not have enough reputation on this domain in the stackexchange world.
dnsmasq worked for me, except I had to make some additional steps.
Here is the full procedure:
Prepend /etc/resolv.conf with the following line
/etc/resolv.conf
nameserver 127.0.0.1
Add the following lines to /etc/dnsmasq.conf
/etc/dnsmasq.conf
listen-address=127.0.0.1
address=/localhost.localdomain/127.0.0.1
address=/localhost/127.0.0.1
Restart dnsmasq
A common task for this subject is to map directories to subdomains. A very straightforward way for that is to append the directory-based entries automatically to the hosts file:
#!/usr/bin/python
import os
hostsFile = open("/etc/hosts", "a+");
lines = hostsFile.readlines()
for fileName in os.listdir('/opt/subdomainDirs'):
entryExists = False
for line in lines:
if fileName in line:
entryExists = True
if not entryExists:
hostsFile.write("127.0.0.1 " + fileName + ".localhost\n");
Thank you tschundeee for what I consider to be the ultimate answer to this issue, wish I could just comment but here is the total configuration for those trying to accomplish the original goal (wildcards all pointing to same codebase -- install nothing, dev environment ie, XAMPP)
file: /etc/hosts (non-windows)
127.0.0.1 example.local
file: /XAMPP/etc/httpd.conf
# Virtual hosts
Include etc/extra/httpd-vhosts.conf
file: XAMPP/etc/extra/httpd-vhosts.conf
<VirtualHost *:80>
ServerAdmin admin@example.local
DocumentRoot "/path_to_XAMPP/htdocs"
ServerName example.local
ServerAlias *.example.local
# SetEnv APP_ENVIRONMENT development
# ErrorLog "logs/example.local-error_log"
# CustomLog "logs/example.local-access_log" common
</VirtualHost>
restart apache
save as whatever.pac wherever you want to and then load the file in the browser's network>proxy>auto_configuration settings (reload if you alter this)
function FindProxyForURL(url, host) {
if (shExpMatch(host, "*example.local")) {
return "PROXY example.local";
}
return "DIRECT";
}
Short answer:
Your /etc/hosts/ file won't let you use wildcards or port numbers. You will need to create one entry for each of your subdomain
If you want to use dnsmasq with NetworkManager you can (or even must?) start dnsmasq from NetworkManager by adding
dnsmasq
NetworkManager
dns=dnsmasq
to /etc/NetworkManager/NetworkManager.conf. Then the dnsmasq config goes to /etc/NetworkManager/dnsmasq.conf or /etc/NetworkManager/dnsmasq.d/ resp.
/etc/NetworkManager/NetworkManager.conf
/etc/NetworkManager/dnsmasq.conf
/etc/NetworkManager/dnsmasq.d/
By posting your answer, you agree to the privacy policy and terms of service.
asked
5 years ago
viewed
71140 times
active
8 months ago | http://serverfault.com/questions/118378/in-my-etc-hosts-file-on-linux-osx-how-do-i-do-a-wildcard-subdomain/118381 | CC-MAIN-2015-18 | refinedweb | 882 | 58.18 |
the PDF has the limitations and what im supposed to do for each option and the zip has the executable as to how is supposed to run and look.
my 1st problem is this do while loop that i enclosed put on */
im trying to keep the input running until i get a Y,y,n,N and when it receives any of those it goes into the if statements and quits the do while loop i dont understand why is it not working
im doing if choice not equal to y or Y or n or N show the message that you need to select y or N
if choice 2 happens to be y,Y,n,N i want it to quit and go to the right if statement
what im doing wrong for this part?
/*do{ 035 cin>>choice2; 036 if(choice2!="y" || choice2!="Y" || choice2!="n" || choice2!="N") 037 {cout<<"please select Y or N";} 038 039 }while(choice2=="y" || choice2=="Y" || choice2=="n" || choice2=="N"); 040 */ //my poor attempt at keeping the option repeating until user input y,Y,N,n
for my second part im having problem is working with arrays is confusing as hell
my idea for the second part is to have the user input
the # of shifts and i will substract by that amount
and shift letters respectivey
this is my idea for example i input the message hello,there!!!
it gets stored in message[140]; and now i want to shift my message by the # of shifts
my idea is to store the new message after is shifted into a new array but im confused about the syntax or how does that work i get all sorts of errors.
i want to do this
char newarray[140];
cin>>shift
for (int i=0;i<140;i++)
newarray=message[i]-shift; //new array would be a char to
the problems that i see here are the following how do i declare properly the newarray to save the value?
for this part is it newarray[]=message[i]-shift; or newarray[140]=message[i]-shift;??
some help on that would be extremely appreciated
thank you guys
#include <iostream> using namespace std; void intro(); //protoype void intro()//function intro message describing what program does {cout <<"COP2271 Encrypter/Decrypter\nThis program is supposed to decrypt and encrypt messages using\nthe Caesar Cipher algorithm.\n\n"; } void menu() {cout <<"Main Menu\n\n1. To input a message\n2. To encrypt a message\n3. To decrypt a message.\n4. To perform a statistical analysis of the message\nPress 0 to quit.\n\nPlease choose: "; } int main() { char loweralphabet[27]={"abcdefghijklmnopqrstuvwxyz"}; //array containing all the lowercase letters of the alphabet char upperalphabet[27]={"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}; //array containing all the uppercase letters of the alphabet int choice; //variable for menu to choose options char choice2; // variable for option 1 if it wants to overwrite message char message[140]; //array where message is to be stored and max is 140 characters as specified char message2[140]; int shift; int on=0; intro(); do{ menu(); cin >> choice; if(choice==1){ if(on==1){cout<<"Currently, your message is:\n"; int i=0; for(i=0;message[i]!='\0';i++) cout<<message[i]; cout<<endl<<"Are you sure you want to overwrite it? (Y/N)"; cin>>choice2; /*do{ cin>>choice2; if(choice2!="y" || choice2!="Y" || choice2!="n" || choice2!="N") {cout<<"please select Y or N";} }while(choice2=="y" || choice2=="Y" || choice2=="n" || choice2=="N"); */ //my poor attempt at keeping the option repeating until user input y,Y,N,n if (choice2=='y' || choice2=='Y') {//on=0; past code put as reference cout<<"Please give new message: "; cin.get(); cin.getline(message,sizeof(message)); cout << endl; } // turns on to 0 which makes it ask for message again } if(choice2=='n' || choice2=='N') {cout<<"Going back to main menu\n"; // if user decides to not overwrite message display that cout<< endl;} if(on==0) {cout << "Please give message: "; //ask user for message to be stored in array cin.get(); cin.getline(message,sizeof(message)); //takes input from user and saves to message array on=1;} } else if(choice==2){ //if statement if option 1 hasn't been run yet if(on!=1) cout<< "Please give a message first using option 1.\n\n"; else{ //if option 1 has run at least once then proceed to do shift cout << "Please give the number of shifts to the left: "; cin >> shift; // get message array do + shift to the whole message by doing a for or a while loop // then store this value into a new array that is a char if not values will be in ascii after summation // //display new messag inside the new array with shift } } else if(choice==3) {if(on!=1) //if statement if option 1 hasn't been run yet cout<< "Please give a message first using option 1.\n\n"; // if option 1 has been run once proceed to decryp it else{cout<<"test"; //grab array with shifted message and do opposite calculation to cancel it out //store array back into another array //cout array after modification } } else if(choice==4) {if(on!=1) //if statement if option 1 hasn't been run yet cout<< "Please give a message first using option 1.\n\n"; // do option 4 nd proceed to test else{cout<<"test";} } else if(choice==0) {cout<<"Now quitting.."; cin.ignore(); cin.get(); } else{cout<<"Wrong choice, please choose again.\n\n"; } }while(choice!=0); return 0; }
Attached File(s)
pro3Spring2012.pdf (86.44K)
Number of downloads: 22
cipher(1).zip (12.69K)
Number of downloads: 13 | http://www.dreamincode.net/forums/topic/269321-working-with-arrays-project/ | CC-MAIN-2013-20 | refinedweb | 939 | 61.09 |
WCEM Upgrade from 1.0 to a higher release
A release upgrade of SAP Web Channel Experience Management is possible from any release to the latest in a direct upgrade. This is shown in the Product Availability Matrix (search for “SAP Web Channel”):
Please read the Release Information Notes for WCEM 2.0 and WCEM 3.0 to check the release requirements, especially the required Service Pack levels of the Java Application Server version and the MDM components. Additionally, obligatory upgrade steps are available in the Master Guide and Installation Guide on the Help Portal () for both releases.
Please be aware that until WCEM 3.0 the mandatory NetWeaver release is 7.30 (not 7.31 or higher!).
In WCEM release 2.0 a major upgrade of the technology stack has been performed: SAP upgraded the used JSF library from 1.2 to 2.1 version. This step opens up a whole range of new possibilities for development of state-of-the art web applications, simplifies the architecture and improves runtime performance. Based on the standard JSF2 architecture some JSF1 concepts are not available anymore so that such implementations need to be adjusted accordingly. These adjustments have been performed in standard WCEM 2.0 so that WCEM Framework and all WCEM Modules have been migrated to JSF2 technology.
Of course this cannot be ensured for custom extensions of the framework, extensions of the SAP modules and for newly created custom modules. This blog shows major aspects which need to be considered with regard to migration of such WCEM 1.0 based custom enhancements.
More information:
- WCEM Public WIKI, section „Installation“, „Configuration“, „Development & Extension“
- WCEM Platform – Technical Introduction
- Advantage of using Java Server Faces
- What’s new in WCEM 2.0 and 3.0
- Feature List of WCEM 2.0 and 3.0
- A short walk from WCEM 1.0 to 3.0 by De Villiers Walton Consulting
Java Application Server (Java AS)
Because with beginning of WCEM 2.0 the technology basis changed considerably, you need to be careful while deploying of standard WCEM 2.0 or newer on a Java AS where WCEM 1.0 runs successfully including custom enhancements. The Java AS for WCEM cannot serve two different release versions in parallel so that in case the WCEM 1.0 based enhancements won’t be adjusted before, you have to expect that your custom development won’t be runnable anymore.
In case you rely on a runnable WCEM system w/o any down times, it is recommended to use a separate server for the higher release version inparallel. When the new release is running successfully, the older system can be dismantled accordingly.
In case you have no customer or partner specific changes yet, you can use your existing Java AS for the upgrade w/o any obvious risk. In general, the Java AS server can run on a virtual machine or on a physical server.
Customizing Settings
Generally the WCEM related settings, like customizing data maintained in the Web Channel Builder tool, will be upgraded automatically so that you don’t need to execute and manual configuration data migration. For all other steps please check the Release Information Notes, the Installation Guides and the Master Guides as mentioned above.
SSL Certificate
You should be aware about one important change which could hinder you after the upgrade: from WCEM 2.0 Patch 8 and higher, the application switches automatically to https protocol, latest before displaying logon screen. This is mandatory because of security reasons. In case you decide to disable this functionality, please read SAP note 1812800 how to achieve it.
Backend System Activation
Business functions in the backend systems ERP and/or CRM have to be activated in order to support the higher WCEM release. For backend activation please read the notes for WCEM 2.0 resp. WCEM 3.0
NetWeaver Development Infrastructure
As next step you need to take care about your developed extensions. It’s recommended at first to create new version of your already existing Software Component which hosts your custom code based on former release.
Then a new Track needs to be created. You’re creating it in the Change Management Service (CMS) of the NWDI and there you’re assigning the Usage Dependencies to the SAP-delivered Software Components of the new release. In particular, you need to assign references to NW and MDM Software Components and to the SAP-delivered WCEM Software Components of the new WCEM release (please use always the newest patch). The process at this point is the same as for the former WCEM release so that you can follow the steps which you’ve done in the past.
Finally the new Software Component version of your extensions needs to be assigned to the newly created Track as well.
As a result you should have a new NWDI Track for the new WCEM release with all needed SAP components so that you’re able to deploy the standard SAP software on a Java AS successfully. Additionally you have new Software Component version for your custom made WCEM extensions which need to be migrated as the next step.
Net Weaver Developer Studio (NWDS)
Now you can use the NWDS for importing the new Track and focusing on the adoptions relating your WCEM extensions.
As already pointed out, WCEM switched in release 2.0 to the JSF2 standard. It’s strongly recommended to become familiar with JSF2 before any coding activities to get better understanding of available implementation options from the Java standard perspective. Additionally the WCEM 2.0 Development and Extension Guide provides extended documentation relating the technical basis of WCEM.
As additional prerequisite you shall update/install newest version of the WCEM Workbench Plugin. See WCEM 2.0 Development and Extension Guide, chapter 7.8 for more details.
At this point you should be able to start with code-related activities. All important implementation steps and cases are described in very detailed form in the WCEM 2.0 Development and Extension Guide, chapter 7.10. At this point it should be specifically highlighted that most of the needed migration steps will be covered by the WCEM Workbench Plugin in an automatic way. Additional, more special and manual steps has been described in chapter 7.10.
After your extensions have been migrated entirely you can deploy your custom Web Site (Main App) and your custom Web Channel Builder on a Java AS, open your web application in a web browser and test if the new WCEM release runs with customer/partner namespace changes successfully.
Hi Adam,
WCEM 2 is JSF 2 correct? - I think there is a dependency on 2.1 to be on Servlet Container 3 and EL 2.1.. Can you confirm?
Regards,
D. | https://blogs.sap.com/2013/03/11/wcem-upgrade-from-10-to-a-higher-release-a-guide/ | CC-MAIN-2021-43 | refinedweb | 1,126 | 56.55 |
Gentlemen,
I have a table call of ' A' and this table not this partitioned
I created a table call ' B' with 6 partitions, and identical in the columns of the table 'A'
I made a command of
insert into B select * from A;
it came back me that 10000 rows had been created.
When went make a
select count (*) from b where col x=2;
for my surprise 0 rows came.
When I made a
select count (*) from b;
answered that there are 0 lines in the
table in the tablespaces that they were loaded,
it exists busy spaces.
What can have been happening????
If does an export of the table A and an
import in B i
it will be inserted in B according to the partition table.
I would advise you to use "COPY" command to get data to new table, rather spend time in troubleshoot whats happening. Its pretty quick....
Reddy,Sam
Did you commit?
Jeff Hunter
marist89@yahoo.com
"I pledge to stop eating sharks fin soup and will not do so under any circumstances."
Jeff got a point... thats what happened possibly...pretty common mistake every one does..
HA! HA! HA!
God Joke.
marist89
OK, I guess the joke's on me because I was serious.
Ok.
marist89
I understend , dont worry. And the import what you tell me?
The only way you might get the export/import to work is:
1. export non-partitioned table A
2. drop table A
3. create table A partitioned
4. import with ignore=y
Forum Rules | http://www.dbasupport.com/forums/showthread.php?26946-Partitioned-Tables-Import&p=113316 | CC-MAIN-2013-48 | refinedweb | 258 | 76.32 |
Bug Description
Traceback (most recent call last):
File "/home/
result = netsvc.
File "/home/
result = ExportService.
File "/home/
res = fn(db, uid, *params)
File "/home/
return f(self, dbname, *args, **kwargs)
File "/home/
res = self.execute_cr(cr, uid, obj, method, *args, **kw)
File "/srv/openerp/
return fct_src(cr, uid, model, method, *args)
File "/home/
return getattr(object, method)(cr, uid, *args, **kw)
File "/home/
tools.
AttributeError: 'module' object has no attribute 'trans_
Hello Ferdinand,
i have tested your issue with latest code but i am not able to reproduce it .it has fixed with recent changes.
will you please check with latest code,if you still face any problem reopen issue with more information.
revision no: 4255
Thanks,
Turkesh Patel
Hello Turkesh,
Again here the correct status should be "Fix released" not "Invalid".
Please open the http://
Thank you!
Hello,
Sorry for inconvenient faced. Here issue has been fixed at following revison
Revision No: 3951
Revision ID: <email address hidden>
Thanks,
Turkesh Patel
def trans_load_data(cr, fileobj, fileformat, lang, lang_name=None, verbose=True, context=None):
update_ res_ids' function below."""
"""Populates the ir_translation table. Fixing the res_ids so that they point
correctly to ir_model_data is done in a separate step, using the
'trans_
there is no such function | https://bugs.launchpad.net/openobject-server/+bug/908289 | CC-MAIN-2016-36 | refinedweb | 206 | 56.45 |
0
hi, I dont know how to use bubble sort or heap or whatever else there is.
what im trying to do is sort a list of number and delete the repeats.
So the user types in how many numbers they want to enter, and then types in the numbers.
ex. i want to enter 5 numbers.
numb1. 9
numb2. 9
numb3. 1
numb4. 3
numb5. 1
then a list is printed like the following
first column is the numbers in descending order, with the count next to them.
9 2
3 1
1 2
heres what i got can i get code for sorting and completing the last part.
#include <iostream> using namespace std; int main(){ int numb; cout<<"How many numbers do you want to enter(1-50): "; cin>>numb; int array[numb]; for(int x=1;x<=numb;x++){ cout<<"Enter number "<<x<<": "; cin>>array[x]; } int count[numb]; for(int h=1;h<=numb;h++){ count[h]=0; } for(int y=1;y<=numb;y++){ for(int u=1;u<=numb;u++){ if(array[y]==array[u]){ count[y]+=1; } } } for(int a=1;a<=numb;a++){ cout<<array[a]<<" "<<count[a]<<endl; } system("pause"); }
Edited 6 Years Ago by WaltP: Added CODE Tags | https://www.daniweb.com/programming/software-development/threads/284518/sorting-array | CC-MAIN-2016-50 | refinedweb | 208 | 73.51 |
How Wikipedia Works/Chapter 12
Chapter 12: Community and Communication[edit | edit source]
A large, diverse, and thriving group of volunteers produces encyclopedia articles and administers Wikipedia. Over time, members of the Wikipedia community have developed conventions for interacting with each other, processes for managing content, and policies for minimizing disruptions and maximizing useful work.
In this chapter, we'll discuss where to find other contributors and how to ask for help with any topic. We'll also explain ways in which community members interact with each other. Though most discussion occurs on talk pages, Wikipedia has some central community forums for debate about the site's larger policies and more specific issues. We'll also talk about the make-up of the community. First, however, we'll outline aspects of Wikipedia's shared culture, from key philosophies about how contributors should interact with each other to some long-running points of debate to some friendly practices that have arisen over time. Although explicit site policies cover content guidelines and social norms, informal philosophies and practices help keep the Wikipedia community of contributors together.
Wikipedia's Culture[edit | edit source]
Wikipedia's community has grown spontaneously and organically—a recipe for a baffling culture rich with in-jokes and insider references. But core tenets of the wiki way, like Assume Good Faith and Please Don't Bite the Newcomers, have been with the community since the beginning.
Assumptions on Arrival[edit | edit source].
Agree to Disagree
If you disagree with someone's edit or action, but you can see that the edit or action followed from a reasonable position, consider refraining from reverting the edit. Does it matter that much? Different edits might be just as good for the encyclopedia, and not every decision should be treated as a point of principle. This aspect of the site may be one of the harder ones for the newcomer to appreciate. Because no one really directs Wikipedia, you should take a peaceful approach and assume that the community's good sense as a whole will prevail; reasonable people can agree to disagree.
Random Acts of Kindness[edit | edit source] w).
Figure 12.1. The original Wikipedia barnstar
The Origin of the Barnstar
The barnstar was created by Sunir Shah on MeatballWiki (see Chapter 2, The World Gets a Free Encyclopedia) in 2003; barnstars were introduced to Wikipedia in February 2004. Since then, the concept has become ingrained in Wikipedia culture. Barnstars are rewards for hard work and due diligence. The image used most commonly on Wikipedia is of a structural barnstar, a metal object used to help brace a wall, which relates to the wiki notion of barnraising by building a page together; see the article at Barnstar for more details.
You can see other awards at w:Wikipedia:A nice cup of tea and a sit down (shortcut WP:TEA). In fact w w:Wikipedia:The Core Contest, are sometimes held.
The Open Door[edit | edit w.)
Soft Security[edit | edit source].
- Further Reading
- The guideline concerning Assume Good Faith
- The guideline about being nice to newcomers
- Information about barnstars with links to other award pages
- A statement of community principles
Another Take on Soft Security
The idea of soft security on a wiki comes from MeatballWiki (described in Chapter 2, The World Gets a Free Encyclopedia). At, an essay on the topic says:
Soft Security is like water. It bends under attack, only to rush in from all directions to fill the gaps. It's strong over time yet adaptable to any shape. It seeks to influence and encourage, not control and enforce. […]
Soft Security follows from the principles of
Assume Good Faith People are almost always trying to be helpful; so, we apply the Principle of First Trust, confident that occasional bad will be overwhelmed by the good.
Peer Review Your peers can ensure that you don't damage the system.
Forgive and Forget Even well-intentioned people make mistakes. They don't need to be permanent.
Limit Damage When unpreventable mistakes are made, keep the damage within tolerable limits.
Fair Process Kim and Mauborgne's theory that being transparent and giving everyone a voice are essential management skills.
Non-Violence Do no violence lest violence seek you.
Communicating with Other Editors[edit | edit source] Page Guidelines[edit | edit source]. Note.
Figure 12.2. A talk page.
- Stick to discussing the article, and save self-expression for your own user page.
Stay on topic, focusing on how to fix the article. Article talk pages are not provided as a place for general discussion about the article's subject, and they shouldn't be used by editors as platforms for their personal views or experiences. Discussion about other articles should note duplications, possible imports or exports of content, or merges with the article in question. Avoid unrelated conversations.
- Use the talk pages for discussing facts and sources.
The talk page is the ideal place for raising verification-related issues. If you believe an article is misleading or plain wrong about a claim, go to its talk page and present your case. Ask for help to find some better sources, compare contradictory facts from different sources, and examine critically the reliability of references. Requesting a verifiable reference to support a suspect statement is often better than merely arguing against it ("Can you tell me who else supports that statement?" rather than "I think you're wrong"). And offering a reliable, contradicting reference won't hurt your case either.
- Be brief but not abrupt. Be specific about changes you'd like to see.
Amplify your edit summaries with fuller discussions. In some cases you may be editing the talk page but not the article deliberately (for example, if you are personally involved in the topic). You can expect to be heard if you're reasonable; remember being shrill is probably counterproductive, whereas being patient will gain sympathy from other editors. Explain what you see as the problem with an edit or section, and offer suggestions as to how fix it. Help matters along, even if you're in an argument, by offering new drafts.
- Talk pages have a warehousing function.
You can post material removed from an article to the talk page. This is commonly done for verification purposes (to ask other editors if they have any references to support a claim, for instance) or to comment in detail on some problems. This technique is less in-your-face and aggressive than simply discarding someone else's work: The implication is not as strong as a permanent cut. You're also acknowledging that the material may be useful if rewritten or incorporated elsewhere. But you can't move copyrighted materials onto a discussion page. If copyright problems have necessitated a heavy pruning of the article, add a talk page note explaining the issue and referencing a source for the apparent violation.
- Be civil, and make no personal attacks.
This is absolutely fundamental. Be reasonable and treat other people with respect; after all, you're having a polite and professional conversation with them. Carry yourself as a colleague, not an adversary. Assume good faith by starting with the attitude that others are trying to do the right thing. No insults: Don't make ad hominem attacks, such as calling someone an idiot or a fascist. Discussing an editor rather than the article is going down the wrong path. Bear in mind that level-headed, fair-minded, constructive, consensus-seeking, and other similar descriptions (from others) are pure gold in terms of developing your Wikipedia reputation; try to epitomize these qualities when discussion becomes heated.
- Avoid the absolute no-nos.
Don't threaten people. For example, promising bans for disagreeing with you is not going to help matters. Bringing up the "administrators you know" is not a great topic to raise. Never make legal threats: Threatening a lawsuitis highly disruptive to Wikipedia and almost never has the intended result. (And you'll likely get banned yourself.) Dispute resolution is more effective, so see Chapter 14, Disputes, Blocks, and Bans for more on the proper channels. Never post personal details or insinuations about others or threaten anyone with anything off the site. Indefinite blocks await those who do these things.
- Don't delete comments, and refactor discussion only as a last resort.
Everyone is entitled to their opinion on a discussion page. Do not delete or rewrite comments, including your own. The convention is to leave other people's comments completely alone: Don't even correct the spelling. If you wish to take something back, delete it and insert a quick apology in its place. But if it is too late and removing the offending comment would make other editors' comments look strange, strike out your comment with the
and tags. In principle, talk pages can be refactored, or summarized, to make discussion clearer. This is relatively rare and requires skill. The better, and definitely easier, course is to add some summaries of your own.
- Don't exclude newcomers.
One statement that is frowned on is "We've already decided that point." A newcomer can reasonably reopen any issue about article content. Wikipedia pages are supposed to improve over time. Learn patience. If a point has been discussed previously and then archived, be courteous and point the newcomer to the discussion. If consensus has been reached, take a moment to explain it or gently refer to the archived discussion.
- Problem users show themselves over time.
When you first answer a comment, whether reasonable or not, you really don't know whether a teenager or a tenured professor left it. Part of assuming good faith is not judging other editors based on just one or two comments; good manners are never wasted. Avoid accusations: Say "I disagree" rather than "you're obviously biased on this issue.".
- Don't Feed the Trolls
Some people are simply attention seeking and argumentative, to the point of being disruptive. The saying Don't feed the trolls encourages you to ignore this behavior and not be provoked into an unncessary argument. See?..
- Those Tilde Signatures
Unlike article contributions, discussion contributions should be signed. Using four tildes to sign ~~~~ is standard and produces your username and a timestamp. Signing with three tildes produces your username but no timestamp. Five tildes, on the other hand, produce a timestamp but no name.
Voting and Discussing[edit | edit source]. 1.5.3. On-Wiki Forums.
Asking Questions and Resolving Problems[edit | edit source]. Note.
- Further Reading
Communicating with Others
- Guidelines on using talk pages effectively
Getting Help
- A page where you can ask questions about Wikipedia
- A page where you can ask questions about any subject
- A page where you can ask questions or make comments
Community Forums
- The Community Portal, for getting news about Wikipedia activities and finding collaborations to participate in
- The page where you can make proposals or conduct general discussion
- Various noticeboards for reporting different types of problems
-'_noticeboard For drawing administrator attention to a problem (anyone may post here)
Getting News[edit | edit source]
You may want to find out what is currently happening on Wikipedia..
Figure 12.3. The Wikipedia Signpost, a weekly on-site newsletter The Wikipedia Signpost, a weekly on-site newsletter
Mailing Lists and Internet Relay Chat[edit | edit source].
Meetups and Conferences[edit | edit source].
Figure 12.4. The Wikimania logo (designed by Ben Yates) The Wikimania logo (designed by Ben Yates)
Further Reading
Getting News The Wikipedia Signpost weekly community newspaper The Wikipedia Weekly podcast The Wikizine newsletter (in English, Spanish, and German)
Mailing Lists and IRC Information about mailing lists and links to their archives Information about Wikimedia's IRC channels Email archives of lists at Nabble (provides a forum-like view that is easier to read for high-traffic lists)
Meetups The page for coordinating meetups, including a list of past meetups along with pictures Information about the annual Wikimania conference (will redirect to the current year's website) The Meta page where conference planning is coordinated
Wikiphilosophies[edit | edit source].
Funny Business[edit | edit source]
Silliness, bad jokes, and shared humor have a place in Wikipedia culture. You'll find (allegedly) humorous material on many project pages, and some of these memes spill over into supposedly serious debates. (shortcut WP:HUMOR) is a collection of some of these funny ha-ha pages. The template.
Deadpan or Nothing
Charles once asked the main author of The Cantos, an article on Ezra Pound's poetic masterpiece, whether he was going to add a spoiler warning. That was rightly taken as a joke. But a suggestion that 0.9999… should be redirected to 1 (number) to save arguments fooled a few people into thinking Charles was being serious..
Uncyclopedia
While most Wikipedia humor focuses on long-running memes, for true parody of the site, try Uncyclopedia. Although not a Wikimedia project, Uncyclopedia is a sister project in spirit—that is, if your sister is the type who teases you mercilessly. Uncyclopedia comes complete with its own sister projects—a dictionary, unbooks, and a news section (UnNews), where current events in the real news are often skewered. Ostensibly run by the shadowy Uncyclomedia Foundation, the site is, in fact, hosted by Wikia. Though the unpolicy is How to be funny and not just stupid, Wikipedia in-jokes abound, and a number of Wikipedians moonlight at Uncyclopedia. The mascot is a potato named Sophia that looks remarkably like a misshapen Wikipedia logo, complete with puzzle pieces; Uncyclopedia informs us that it is, in fact, an untato—technically a brain that connects to the Uncyclomedia servers that power up all the Uncyclomedia projects. See.
"Heavy Metal Umlaut"
The article on the Heavy Metal Umlaut—the umlauts in heavy-metal band names such as Mötley Crüe and Motörhead—has a long and storied history, making it a famous "unusual article." First started in 2003 by an anonymous editor, the article has been featured, cited by the press, printed on a T-shirt, and was the subject of a short video describing the collaborative editing process by Jon Udell; see.).
- Further Reading
Wikiphilosophies
- An explanation of deletionism
- An explanation of inclusionism
- Information on more wiki philosophies
Humor
- A collection of silly vandalism (previously called Bad Jokes and Other Deleted Nonsense)
- A collection of humorous or parody project pages
- The Uncyclopedia site
The classic odd Wikipedia article is w:Exploding whale. Also check out w:Undecimber, the thirteenth month of the year; w:ETAOIN SHRDLU; w.
Who Writes This Thing Anyway?[edit | edit source]
Who writes Wikipedia? Who are the members of the Wikipedia community? No one knows the exact answer to this question, and Wikipedia has no single point of reference for its social side.
One simple but of course inadequate approach is to ask how much work is actually connected with the English-language Wikipedia. Well, the amount of work is equivalent to 1,000 full-time people. Or it's probably more like 5,000 people working one day a week and even more like those 5,000 people devoting 8 hours a week of spare time. Wikipedia has a division of labor, because people gravitate to work they enjoy, but little hierarchy.
Believing that Wikipedia has one community is a mistake, and referring to "the community" is somewhat confusing. Who is the community? After all, the work on the project includes developing software, writing articles, and tending to the practicalities of managing a publicly editable website. Is the community those few people who actively contribute to the general mailing list or hang out on IRC? The people who care about and watch policy pages or post their thoughts at the Village Pump? Are you thinking of the contributors you encounter at a particular WikiProject? Those people who enjoy going to meetups and conferences and meeting other Wikipedians? Or the handful of people who talk to the press and give presentations? Is it those people who spend hours daily contributing and fighting vandalism, or the majority of people who are silent and occasional contributors? What about those involved with governance on the Foundation level, who may help run the sites as a whole but no longer edit articles?
The answer, of course, is that these people are all part of the Wikipedia community. The degree of social complexity, coupled with the site's large scale, probably undermines all assumptions based on previous discussions of online groups.
Demographics[edit | edit source]
Wikipedia—also known as Unemployed Ph.D. Deathmatch (User:Finlay McWalter)
Wikipedia's editors are any recruits who can show that they have the talent to write and upgrade encyclopedia articles. Nothing else counts for much. Contributor anonymity is acceptable, in large part because who you are or what prior background you have is not supposed to have any effect on your contributions being accepted, as long as you respect the content policies. Whether you're a teenager or a tenured Ph.D. doesn't matter: On Wikipedia, no one needs to know you're a Doc.
Godwin's Nine Points
Use software that promotes good discussions.
Don't impose a length limitation on postings.
Front-load your system with talkative, diverse people.
Let the users resolve their own disputes.
Provide institutional memory.
Promote continuity.
Be host to a particular interest group.
Provide places for children.
Most Important: Confront the users with a crisis.
These nine points on promoting a successful online community were published in June 1994 in Wired magazine, by Mike Godwin. Godwin is a celebrated name on the Internet, for Godwin's law and other much more substantial achievements with the Electronic Frontier Foundation. In 2007, he became legal counsel to the Wikimedia Foundation.
Seeing where Wikipedia actually fails any of these points is difficult. On point 7, Wikipedia has played host to thousands of people who are intensely interested in a subject. Young contributors are welcome in Wikipedia: They are, for example, enfranchised in elections because voting doesn't have an age requirement. No one can be sure of the median age of Wikipedians, but for Wikipedia's readers, it probably corresponds to the age of the average college student.
Point 9 about a crisis may raise a wry smile from those who read the mailing lists. When has Wikipedia not had a crisis? When have discussion threads not spoken about imminent disaster? In a sense, the morphing of Nupedia into Wikipedia, with the destruction of mechanisms for approving content, was a founding crisis with constant repercussions.
Because no personal data is collected during the registration process, assumptions and information about contributor demographics are largely anecdotal. Although many editors chose to reveal parts of their identity publicly, either on their user page or in another forum (such as what they do for a living or their real name), many others do not. Meetups provide some information, but this is a self-selected group. The German-language Wikipedia, which is distinctly more academic in tone, has given some survey results suggesting a median age in the late 20s for editors.
One thing that is clear from the English-language Wikipedia is that native English speakers do not necessarily predominate. Wikipedia has many editors for whom English is a second language, and they have historically played a large part in building the site. Some edit Wikipedias in two or more languages. See Chapter 15, 200 Languages and Counting for more.
Systemic Bias[edit | edit source]
If you think of Wikipedia purely as an encyclopedia, its coverage of current affairs and popular culture might seem disproportionate. For instance, around half the biographies are about living people: Much effort is devoted to upgrading those 200,000 articles because real lives can be affected by the content available on Wikipedia. But what about the antiquarian, the obscure but scholarly, and topics not so well known in the English-speaking world?
Systemic bias is a term used on Wikipedia to describe the concept that notions of notability and breadth of article coverage both reflect the community of editors and their demographic. And indeed, Wikipedia's coverage is skewed toward subjects relating to Anglophone countries. For example, articles about people and places in the developing world are often missing or incomplete compared to articles about North American and European geography and personalities. Topics related to women (such as biographies of famous women or articles about feminism) are underrepresented, along with articles about blue-collar trades. This is a known problem but not one easy to address with policy. (The term systemic bias is not to be confused with systematic bias, which is one kind of violation of Neutral Point of View, where a given article or group of articles is one-sided.)
The articles that prosper on Wikipedia, generally speaking, are those that when created can immediately be linked to from existing articles and that attract editors (other than the initial author) who are active in the same general area. These positive factors can also be read the other way: If an area is somewhat neglected in Wikipedia, a new article's life cycle (Chapter 10, The Life Cycle of an Article) is initiated in a less favorable environment.
These issues are more easily understood than remedied. Volunteer editors will choose the areas they want to work on, and Wikipedia can't legislate its way into being more representative. The community must also work through the founder effect, a concept from evolution that the system will, for some time, remember or be influenced by characteristics of the founding group, rather than the larger population. See Wikipedia:WikiProject Countering systemic bias (shortcut WP:BIAS) for a dedicated forum on this topic.
Dress Sense
WikiProject Fashion was started in March 2007 to address a known weakness. Alexandra Shulman, editor of the British edition of Vogue, had awarded the Haute couture article a lowly 0 marks out of 10 in an October 24, 2005, survey in London's The Guardian. [28]
Women and Wikimedia
Are more men than women involved in Wikipedia? Evidence from in-person meetups, mailing lists, and other community forums does suggest that more Wikipedia contributors are men than women, though knowing for sure is impossible. This bias is not unusual on the Internet and in computing generally, but it is definitely not ideal for a project that aims to be welcoming to everyone.
Though discrimination based on personal characteristics (including gender) is certainly against Wikipedia's principles, some feel the site's culture is overly aggressive, a criticism that does depend on where you look for evidence. Does Wikipedia do enough to control misogynistic editors who take gender into account in debates and potentially in more harmful ways such as by harassing female editors? Others feel that given Wikipedia's practices and essential values regarding inclusiveness, no particular issue with gender exists on the projects. The topic remains controversial, and no one editor's experience is likely to be exactly the same as another's, always a difficulty in defining systemic problems.
This debate around the treatment of women on Wikipedia (and how to improve it) led to the creation of the WikiChix project in 2007 (). WikiChix, which is modeled after the similar LinuxChix group, offers a female-only environment to discuss wikis and the Wikimedia projects and explore ways to make the projects more accessible and friendly toward women. On a Foundation level, several women have won elections to the Board of Directors of the Wikimedia Foundation. These include (as of early 2008) the current chair of the organization, Florence Devouard.
All is not gloom, though, since Wikipedia does gradually overcome some of these limitations. Individual WikiProjects are created for weaker areas that need work (such as Wikipedia:WikiProject Gender Studies), and Wikipedia attracts some academic experts and others who do steady work filling in gaps in coverage. Working on a neglected area can be rewarding as well, as there is more opportunity to create new articles.
Wikipedians on Wikipedia[edit | edit source]
Wikipedians love to write about Wikipedia. This is revealed in the large number of essays about the site, posted both on user talk pages and project pages. Happy, sad, critical, and usually interesting, these essays are a mosaic of opinions about the site, its people, and its governance. An essay may aim to influence site policies or the way people behave or may simply be self-expression, one small addition to the site's culture. Many end up being cited by other editors in discussions, and some even end up as guideline or policy.
Here is a selection of extracts from a small handful of our favorite essays. Some of them connect to points that are made elsewhere in this book, whereas others concern thought-provoking aspects of Wikipedia that we don't follow up.
- A high proportion of Wikipedians are people with issues with authority. That's why many people are attracted to Wikipedia in the first place. Keep this in mind if you become an administrator, for you may have just become, unwittingly, what these people most resent; and no matter how good a job you do, they'll find your one mistake and beat you up with it. It's best just to accept this demographic for the reality it is. They are often the best editors, and as long as Wikipedia remains open to all, this situation will remain. (From User:Antandrus/observations on Wikipedia behavior, shortcut WP:OWB)
- Wikipedia is space age Corningware, not ceramic, and it's not going to shatter if you drop it. Don't let your fear of messing things up keep you from editing. (From Wikipedia:Can't break it)
- Wikipedia, in many senses, can be a Byzantine mess of policies, guidelines, style conventions, formatting tricks, and essays. It is essentially impossible for a new editor to know or anticipate most of them and even experienced editors accidentally run afoul of policies and guidelines occasionally. When this happens, it's not necessarily an indication that the editor is acting badly or has lost the community's trust. Usually, it just means they made a minor mistake and someone else corrected it. That's the way wikis like Wikipedia work: mistakes are constantly found and corrected. What is important to the functioning of any wiki, and especially large, complex ones like the English Wikipedia, is not that people become paranoid about avoiding mistakes. Mistakes are inevitable. What is important is that editors learn from errors, read the relevant policy, guideline, or whatever, and try to follow it in the future. Mistakes will happen; don't let them get you down. (From User:Chaser/Make mistakes, then learn from them, shortcut WP:BOOBOOS)
- If a debate, discussion, or general exchange of views has come to a natural end through one party having "won" or (more likely) the community having lost interest in the entire thing, then no matter which side you were on, you should walk away. (From Wikipedia:Drop the stick and back slowly away from the horse carcass, shortcut WP:DEADHORSE)
- Writing for the enemy is the process of explaining another person's point of view as clearly and fairly as you can, similar to devil's advocate. The intent is to satisfy the adherents and advocates of that perspective that you understand their claims and arguments. (From Wikipedia:Writing for the enemy, shortcut WP:WFTE)
- The fight-or-flight response developed by our pre-human ancestors may have helped them escape from angry mastodons, but it isn't constructive in an online encyclopedia. (From Wikipedia:No angry mastodons, shortcut WP:KEEPCOOL)
- A coatrack article is a Wikipedia article that ostensibly discusses the nominal subject, but in reality is a cover for a tangentially related bias subject. The nominal subject is used as an empty coatrack, which ends up being mostly obscured by the "coats." (From Wikipedia:Coatrack, shortcut WP:COAT)
-. (From Wikipedia:Beware of the tigers, shortcut WP:TIGER)
- A young novice asked, "Is Wikipedia a community, or an encyclopedia?" Alkivar answered "Yes."; later, another novice asked Alkivar the same question, to which he answered "No." (From Wikipedia:The Zen of Wikipedia, shortcut WP:KOAN)
- Wikipedia is just an encyclopedia. The Wikipedia community is at its core just a community made up of a bunch of people who think writing a free, complete, and accurate encyclopedia is a good idea (and a lot of fun, too). The Wikipedia community isn't too happy about people trying to use Wikipedia to promote causes other than having a good online encyclopedia. This includes contributions meant to promote websites and products, political causes, religions, and other beliefs, and of course one's personal view of what's really funny. (From Wikipedia:Don't hand out panda sandwiches at a PETA convention, shortcut WP:PANDA)
- It is particularly important to get the last word where you are in some doubts as to the merits of your case. The last word will serve as a clinching argument that will make up for any deficiencies in your logic. (From Wikipedia:The Last Word, shortcut WP:TLW)
- Before you make yourself and others unhappy, remember this: you have the Right To Leave. (From Wikipedia:Right to leave, shortcut WP:RTL)
You can find many other such essays collected in w:Category:Wikipedia essays. Many Wikipedians also blog about Wikipedia and related Wikimedia issues. You can find a list of self-identified bloggers on Meta, but for easier and more focused reading, you can find a collection of blogs about Wikimedia topics at the Planet Wikimedia site, where they are conveniently aggregated; see. An RSS feed is also available.
Operational Analysis: Raul's Laws[edit | edit source]
One essay in particular, known as "Raul's laws" (shortcut WP:RAUL), contains a collection of observations on how Wikipedia works and how Wikipedians work together. The essay was started by User:Raul654, an experienced contributor, but has been built by dozens of contributors. The page gives what is very much an insider's view of how Wikipedia works, though the later laws that have been added vary greatly in interest.
We've taken 6 "laws" from the original 15. Two bits of jargon are Astroturfing, a public relations term for an orchestrated campaign meant to look like spontaneous grassroots activity and Metcalfe's law, which points to the square of the number of users in a network as a measure of its value.
Much of Wikipedia's content and all of the day-to-day functions are overseen by a small core of the most dedicated contributors.
Content brings visitors—this is as true for wikis as it is for networks, as dictated by Metcalfe's law. Of those visitors, a certain number will stay and become contributors. Of those contributors, a certain number will stay long enough to become dedicated users.
You cannot motivate people on a large scale to write about something they don't want to write about.
Over time, contentious articles will grow from edit-war inspiring to eventually reach a compromise that is agreed upon by all the editors who have not departed in exasperation. This equilibrium will inevitably be disturbed by new users who accuse the article of being absurdly one sided and who attempt to rewrite the entire article.
Wikipedia's steadily increasing popularity means that within the next year or two, we will begin to see organized corporate astroturfing campaigns. [29]
As time goes on, the rules and informal policies on Wikipedia tend to become less and less plastic and harder and harder to change.
Practical Values, Process, and Policy[edit | edit source]
Wikipedia has no centralized control, yet the site progresses and is successful. The administration of Wikipedia as a whole has scaled up much better than its critics predicted. Something clearly does work. But what is it that works?
Discussion alone may not achieve much. If no meeting of minds occurs, a productive debate can become an unresolvable dispute. A common theme in interviews with editors turns out to be this: Wikipedians clearly feel they share values with others who are editing.
These values include the following:
The worth of open information that is outside copyright barriers (and, therefore, probably support for free software too)
A commitment to sharing knowledge worldwide
Multiculturalism, diversity, and multilingualism
Fairness in representing diverse points of view
Wikis attract people who can live with freeform structures. But shared and practical values mean that Wikipedians will admit that some structure is necessary and some idea of how the encyclopedia should be built has to be present. Wikipedia's structures, such as how editing permissions are provided, must match up with these core values.
The key way Wikipedia gets through its project-related work is its characteristic structure: Processes consist of decentralized discussions about separable issues. That's how decisions are actually made and how site administration moves forward. Backlogs are avoided by limiting discussion time. These processes are, in turn, governed by policy documents that have general consent. (Chapter 13, Policy and Your Input picks up from here and will explain how you can have wiki-style editable policy.)
Policy and process, then, are closely related on Wikipedia, providing a structure for editors to work together through discussion. So much needs to be done that the sensible approach that has evolved is to have all those differentiated processes, not a single executive body. Processes and policies, despite their imperfections, evolve to meet changing circumstances. See an overview essay Wikipedia:Product, process, policy (shortcut WP:3P) for more on this idea.
More Research Required[edit | edit source]
At this point, we still simply don't know some things.
Will the English-language Wikipedia have to evolve different social processes in the long term?
Will every language version of Wikipedia go through the same stages of developing content and community?
Will time bring the English-language Wikipedia's community into a stable demographic composed of people with a broad-based interest in encyclopedic knowledge? How can more people, including experts, be involved in editing?
Can quality be sustained in an open encyclopedia with millions of articles?
See Wikipedia:Researching Wikipedia (shortcut WP:RW) for some ideas for studies. Wikipedia:Wikipedia in academic studies showcases some work that has already been done.
Further Reading
Community's laws Raul's laws, a collaboratively written collection of thoughts about the community Mike Godwin's nine points
Demographics and Systemic Bias Who are Wikipedians? WikiProject countering systemic bias The WikiChix group, open to any woman interested in wikis
Essays Essays about Wikipedia by Wikipedians; these essays in the Wikipedia namespace are often referenced by other users. More essays about Wikipedia by Wikipedians; these essays are in user space and may be less widely referenced or only represent the view of one person. Essays on the Meta site; these are older essays written by Wikipedians about Wikipedia, Wikimedia, and wiki philosophies. Planet Wikimedia is an aggregator of blogs about Wikimedia by Wikimedians.
Researching Wikipedia A list of studies that have focused on Wikipedia The Wikimedia research network, a page for Wikimedia researchers from around the world to share their work Some research questions
[28] See "Can You Trust Wikipedia?" The Guardian. Monday, October 24, 2005,.
[29] Prediction confirmed, August 28, 2005 (nine months after the prediction was made): One anonymous reader contacted Boing Boing to say that he worked at a marketing company that uses Wikipedia for its online marketing strategies. See.
Summary[edit | edit source]
Though loose and somewhat ill-defined, the notion of community is absolutely fundamental to Wikipedia; without it, the site could not succeed. The way Wikipedia is set up has led to a community that doesn't rely on central authority or a central forum. Instead, Wikipedia's editors communicate largely, but not exclusively, by editing pages for others to read—both article talk pages and central discussion forums. Those pages run quickly into tens of thousands of separate discussions, where issues are separated out and dealt with individually. Each debate will bring together a small, probably diverse group of people interested in any topic. Wikipedia has no true center and no easy overview of all these interactions. Wikipedia's success relies on the way that the overarching philosophies mesh with the intricate, small-scale actions on the sit | https://en.wikibooks.org/wiki/How_Wikipedia_Works/Chapter_12 | CC-MAIN-2021-43 | refinedweb | 6,047 | 52.7 |
I am doing an assignment that is for the days of the week. This is what I am supposed to do, STEP 1: Create the Project and Main Class
1. Create a new console application project and name it "Week1Lab_YourName".
2. Create a new class called DayOfTheWeek. The class should have a data member that can store the day of the week, such as Mon for Monday, Tues for Tuesday, and so on.
STEP 2: Create the Member Functions.
STEP 3: Create a Main() Program
1. Write a main program that will instantiate two objects of the class DayOfTheWeek. Use these objects to test the various operations on this class, using the examples in the lectures and reading to perform the required operations.
STEP 4: Build and Test
1. Build your project (compile your program).
2. Eliminate all syntax errors.
3. Run the program.
4. Verify results of program execution and correct any logic errors discovered.
This is what I have:
If I build it I get: fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?If I build it I get: fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?Code:#include <string> #include "DayOfTheWeek.h" using std::string; class DayOfTheWeek { private: string day; public: void SetDay(string); void PrintDay(string); string GetDay(); }; MAIN #include <string> #include "DayOfTheWeek.h" using namespace std; int Main() { DayOfTheWeek day; day.GetDay ("mon"); cout << DayOfTheWeek.PrintDay << endl; } void DayOfTheWeek::SetDay(string day) { string Monday = "mon"; string Tuesday = "tues"; string Wednesday = "wed"; string Thursday = "thurs"; string Friday = "fri"; string Saturday = "sat"; string Sunday = "sun"; } void DayOfTheWeek::PrintDay(string day) { cout << "Today is " << day << endl; } string DayOfTheWeek::GetDay() { string day = "Monday"; return day; }
If I add the #include "stdafx.h" it tells me: fatal error C1083: Cannot open include file: 'DayOfTheWeek.h': No such file or directory
What am I doing wrong? | http://cboard.cprogramming.com/cplusplus-programming/135281-please-help-not-sure-whats-wrong.html | CC-MAIN-2014-42 | refinedweb | 335 | 68.06 |
>>
Gmail account giveaway
Optimize Plone.org with slimmer.py
Related blogsXHTML, HTML and CSS compressor
Optimized stylesheets
Date formatting in Python or in PostgreSQL (part II)
Quick PostgreSQL optimization story
The problem with CSS
Fastest way to uniqify a list in Python
To JSON, Pickle or Marshal in Python
Corp Calendar 0.0.5
CorpCalendar review on ZopeMag.com
Related by category
Python optimization anecdote
optimization, anecdote, cpickle, marshal, checkoutabletemplates, write2config, pickled, pickler, pickling, fredik lundh
11th of February 2005
I've learned something today. The
cPickle module in Python can be boosted with very little effort. I've also learnt that there's something even faster than a hotted 'cPickle':
marshal.
The code in question is the CheckoutableTemplates which saves information about the state of templates in Zope to a file on the file system. The first thing I did was to insert a little timer which looked something like this:
def write2config(...): t0=time() result = _write2configPickle(...) t1=time()-t0 debug("_write2configPickle() took %s seconds"%t1) return result
I ran it many times over to be able to generate some sort of average time for writing a config item to file. The first result was: 0.0035016271.
The second thing I did was that I rewrote the algorithm at which it does the writing. I managed to prevent one avoidable read from the pickled file. This was timed in the same fashion again and the second result was: 0.00175877291 which is twice as fast already!
Now the
cPickle.dump() function has an optional parameter called
proto. I let the code explain itself:
>>> print cPickle.Pickler.__doc__ Pickler(file, proto=0) -- Create a pickler. This takes a file-like object for writing a pickle data stream. The optional proto argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2. The default protocol is 0, to be backwards compatible. (Protocol 0 is the only protocol that can be written to a file opened in text mode and read back successfully. When using a protocol higher than 0, make sure the file is opened in binary mode, both when pickling and unpickling.) Protocol 1 is more efficient than protocol 0; protocol 2 is more efficient than protocol 1. Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. The file parameter must have a write() method that accepts a single string argument. It can thus be an open file object, a StringIO object, or any other custom object that meets this interface.
So I tried writing the pickle file in a binary mode with
proto=-1 which boosted the average time down to: 0.000777201219 which is more than twice as fast as the improved algorithm.
Lastly. I had completely forgotten about the
marshal module. It basically does was
pickle and
cPickle does but is much more primitive. This is what Fredik Lundh writes in the book Python Standard Library about the
pickle module:
"It's a bit slower than marshal, but it can handle class instances, shared elements, and recursive data structures, among other things."
But for my particular problem, all I had to serialize was a simple but long list and a dictionary; so I can use the
marshal module without any problems. Rewriting the code to use
marshal instead of
cPickle get it another boost so the fourth and last result was: 0.000445931848. That's less than twice as fast as the previous solution. But, the difference between the beginning and the end is from 0.00350162718 to 0.000445931848 the difference is roughly a factor of 8! Pretty neat, huh?
Results:
0.00175877291747 _write2Picklconfig() 0.000445931848854 _write2marshalconfig() 0.00350162718031 OLD_write2Pickleconfig() 0.000777201219039 _write2Pickleconfig(proto=-1)
Comment
The problem with the marshal module is that the underlying format is subject to change without notice. This can make it useful for passing objects around as strings between Python instances on the same machine, but not very useful for any kind of long-term storage. Mostly it's designed to generate pyc files.
Interesting.
Fortunately my program doesn't need to do long term storage. I also don't need to open the serialized file from any other perspective other than debugging.
Instead of writing your own timing stuff, why not use the timeit module in the standard library?
Isn't timeit just for strings of code?
In my setup I was able to "listen in" on a running program. | http://www.peterbe.com/plog/python-optimization-anecdote | crawl-002 | refinedweb | 755 | 66.23 |
Edit a package
Start by installing and importing the package you wish to modify:
import quilt quilt.install("uciml/wine") from quilt.data.uciml import wine
Alternatively, you can build an empty package and import it for editing:
import quilt quilt.build("USER/FOO") from quilt.data.USER import FOO
Editing dataframes
Use the Pandas API to edit existing dataframes:
df = wine.tables.wine() hue = df['Hue'] df['HueNormalized'] = (hue - hue.min())/(hue.max() - hue.min())
Add package members
Use the
_set helper method on the top-level package node to create new groups and data nodes:
import pandas as pd df = pd.DataFrame(dict(x=[1, 2, 3])) # insert a dataframe at wine.mygroup.data() wine._set(["mygroup", "data"], df) # insert a file at wine.mygroup.anothergroup.blob() wine._set(["mygroup", "anothergroup", "blob"], "localpath/file.txt") #
Delete package members
Use
del to delete attributes:
del wine.raw.wine
Edit metadata
Use the
_meta attribute to attach any JSON-serializable dictionary of metadata to a group or a data node:
wine.mygroup._meta['foo'] = 'bar' wine.mygroup._meta['created'] = time.time()
Data nodes contain a built-in key
_meta['_system'] with information such as the original file path. You may access it, but any modifications to it may be lost.
Filter the package
The top-level package node has a
_filter method that accepts either a dictionary or a lambda.
It returns a new package that has the same tree structure, but contains only the nodes that matched the filter.
If a group matches the filter, its whole subtree is included.
Dictionary filter supports two properies,
name and
meta:
pkg = wine._filter({'name': 'README'}) # Just the readme pkg = wine._filter({'meta': {'foo': 'bar'}}) # The group we created earlier pkg = wine._filter({'meta': {'_system': {'transform': 'csv'}}}) # Dataframes created from CSVs
Lambda filter accepts the node object and its name. It provides more flexibility, but requires more care when accessing values:
pkg = wine._filter(lambda node, name: node._meta.get('_system', {}).get('filepath', '').endswith('.data'))
Persist changes
At this point, your changes only exist in memory. To persist your changes you can build and push your package. | https://docs.quiltdata.com/edit-a-package.html | CC-MAIN-2018-22 | refinedweb | 355 | 60.01 |
The previous post looked at the images of concentric circles under functions defined by power series. The terms of these series have the form
zθ(n) / θ(n)
where θ(n) is a rapidly increasing function of n. These series are thin (technically, lacunary) because all the terms between values of θ(n) are missing.
The previous post used factorials and powers of 2 as the thinning function. This post uses Fibonacci numbers. It differs from the previous post by using more circles and by making all the circles the same color rather than using matplotlib’s default colors.
Without further ado, here’s the plot.
It looks sorta like a tree with ingrown bark.
The code to produce the plot was the same as the code in the previous post with the following changes.
def fib(n): phi = (1 + 5**0.5)/2 return int(phi**n/5**0.5 + 0.5) for r in linspace(0, 1, 60): z = f(fib, r*exp(1j*theta)) plt.plot(z.real, z.imag, 'b', alpha=0.6)
The function
fib above uses Binet’s formula to compute Fibonacci numbers. | https://www.johndcook.com/blog/2020/08/10/ingrown-bark/ | CC-MAIN-2021-31 | refinedweb | 189 | 68.26 |
Now that you have installed JUnit with the last tutorial, we will be ready to test it.
So, go!
Open Eclipse, select a project, then create a new Class.
In your example, it will be a class with classical mathematical operations.
So let's name it MyOperations.
We don't need a package for this tutorial JUnit for beginners, so here the code of this class:
/** * * Classical mathematical operations * @author BadproG * */ public class MyOperations { /** * Classical addition * @param x * @param y * @return */ public int addition(int x, int y) { return x + y; } /** * Classical division * @param x * @param y * @return */ public int division(int x, int y) { return x / y; } /** * Classical modulo * @param x * @param y * @return */ public int modulo(int x, int y) { return x % y; } /** * Classical multiplication * @param x * @param y * @return */ public int multiplication(int x, int y) { return x * y; } /** * Classical subtraction * @param x * @param y * @return */ public int subtraction(int x, int y) { return x - y; } }
As you can see, these methods are really easy to understand.
Let's continue by creating a JUnit Test Case (right click on the default package > New > JUnit Test Case).
In the Name input, type MyOperationsTest then at the end, fill the Class under test input with MyOperations.
Click Next and select all methods from MyOperations class, such as addition(int, int), division(int, int), etc.
Click Finish.
OK, now right click this file (MyOperationsTest) > Run As > JUnit Test.
A new window appears, this is the JUnit one, and all testd are in red! Oh my God, what's going on?
No panic, it is normal.
Indeed, all tests in your class (MyOperationsTest) are fail("Message") methods.
It means that they are programmed to fail your tests.
So replace all these methods by the following ones:
import static org.junit.Assert.*; import org.junit.Test; public class MyOperationsTest { @Test public void testAddition() { MyOperations tester = new MyOperations(); assertEquals(15, tester.addition(5, 10)); } @Test public void testDivision() { MyOperations tester = new MyOperations(); assertEquals(2, tester.division(10, 5)); } @Test public void testModulo() { MyOperations tester = new MyOperations(); assertEquals(1, tester.modulo(10, 3)); } @Test public void testMultiplication() { MyOperations tester = new MyOperations(); assertEquals(1000, tester.multiplication(25, 40)); } @Test public void testSubstraction() { MyOperations tester = new MyOperations(); assertEquals(47, tester.subtraction(50, 3)); } }
Re Run As the JUnit Test and this time all tests will be in green!
You have just performed your first test unit.
Well done!
kannan (not verified)
Tuesday, January 31, 2012 - 6:15am
Permalink
thank u sir... really its
thank u sir... really its working on well.....
kannan (not verified)
Saturday, February 11, 2012 - 7:18am
Permalink
can u give some more examples
can u give some more examples for junit... and also how to use the packages...
Mi-K
Saturday, February 11, 2012 - 5:55pm
Permalink
Hello kannan,
Hello kannan,
Thank you for your comments.
For your last one proposition, I would certainly do it in the future.
But I don't know when.
Ricardo Rodrigues (not verified)
Sunday, June 3, 2012 - 1:30am
Permalink
I'm beginning with JUnit and
I'm beginning with JUnit and your tutorial is great to start.
I'm using the book JUnit in Action 2nd Edition, but I had some problems because the first test was not going on. A version issue. I guess.
Now I think I can continue.
Thank you very much!
Jonathan Sidwell (not verified)
Friday, June 27, 2014 - 8:56am
Permalink
Thanks man, that was a nice
Thanks man, that was a nice and simple example. I've had trouble understanding jUnit testing until this. Thanks alot
Add new comment | https://www.badprog.com/comment/233 | CC-MAIN-2021-10 | refinedweb | 600 | 56.55 |
The new PhpStorm 2018.2 EAP build (182.3341.34) is now available! You can download it here or via JetBrains Toolbox App. Or, if you have the previous PhpStorm 2018.2 EAP build (182.3208.33) installed, you should soon get a notification in the IDE about a patch update.
“Add method” quick fix now inserts parameter type hints
When a method is complex, part of the functionality it implements may be handled by a call to a different method that doesn’t exist yet. To generate the skeleton of such a method at any point, you can simply type the full method call and invoke the “Add method” quick fix. If you have PHP Language Level set to 7 or above, PhpStorm 2018.2 will additionally provide you with parameter type hints for the method’s parameters, which will make your code more reliable.
This build delivers new features, bug fixes, and improvements for PHP and the Web, and includes the latest improvements in IntelliJ Platform:
- Fixes for SQL Injections: WI-42485, WI-42419, WI-42486, WI-42586, WI-42587, WI-42588
- Add option to wrap words in docker logs IDEA-175476
- Unregistered Git roots are not auto-detected if they are more than 2 folder levels deep than any project module IDEA-108316
- Support TypeScript 3.0 named type arguments WEB-33222
- Support TS 3.0 ‘unknown’ type WEB-33221
- Add references to TS 3.0 named generic arguments (so that they can be renamed/navigated) WEB-33326
- Flow/TSX/React: provide the possibility to navigate via namespaced React tags WEB-18381341.34 for your platform from the project EAP page or click “Update” in your JetBrains Toolbox App. And please do report any bugs and feature request to our Issue Tracker.
Your JetBrains PhpStorm Team
The Drive to Develop | https://blog.jetbrains.com/phpstorm/2018/06/phpstorm-2018-2-eap-182-3341-34/ | CC-MAIN-2018-30 | refinedweb | 303 | 64.51 |
Don’t predict too far into the future.
I was exploring the pandas docs while preparing a pandas course for calmcode.io when I stumbled on an interesting fact: there are bounds for timestamps in pandas.
To quote the docs:
Since pandas represents timestamps in nanosecond resolution, the time span that can be represented using a 64-bit integer is limited to approximately 584 years:
import pandas as pd min pd.Timestamp.# Timestamp('1677-09-21 00:12:43.145224193') max pd.Timestamp.# Timestamp('2262-04-11 23:47:16.854775807')
It makes sense when you consider pandas can handle nano-seconds and there’s only so much information that you can store in a 64-bit integer. If you have a use-case outside of this span of time, pandas does have a trick up it’s sleeve: you can create a date-like
Period that could work as a datetime instead.
Periodclass
Here’s how to generate periods.
= pd.period_range("1215-01-01", "1381-01-01", freq="D")span
You can also cast dates manually as an alternative to
pd.to_datetime if you like.
= pd.Series(['1111-01-01', '1212-12-12']) s def convert(item): = int(item[:4]) year = int(item[5:7]) month = int(item[8:10]) day return pd.Period(year=year, month=month, day=day, freq="D") apply(convert) s. # 0 1111-01-01 # 1 1212-12-12 # dtype: period[D] | https://koaning.io/til/2021-10-20-pandas-time/ | CC-MAIN-2021-49 | refinedweb | 237 | 57.67 |
Answered by:
VS 2012 Express support database
Question
Does VS 2012 Express support to connect MySQL or other Database?
I tried to connect a database connection and realized that the only option is to link SQL Server.
It looks like express version only can connect MS SQL Server.
My question would be does Prefession verison can connect MySQL or other database?
Does Preofessional version have report function?
Your help and information is great appreciated,
Sourises,Sunday, September 30, 2012 4:45 PM
Answers
The Professional Edition of VS 2012 includes MS Reporting.
As far as Crystal Reports for VS 2012 is concerned, SAP appears to be dragging their feet (as usual):
Riced answered your other question.Sunday, September 30, 2012 8:28 PM
All replies
- You can certainly connect to dbs other than SQL Server. Try looking at OleDB functions. Or google for MySQL VB.Net - that will give you plenty to look at..Sunday, September 30, 2012 4:54 PM
The Professional Edition of VS 2012 includes MS Reporting.
As far as Crystal Reports for VS 2012 is concerned, SAP appears to be dragging their feet (as usual):
Riced answered your other question.Sunday, September 30, 2012 8:28 PM
You absolutely can connect to MySQL using Oracle's own MySQL Connector/NET using the Express editions of Visual Studio.
The limitation, however, is that you can't use the tools in the designer as, like you've noticed, only Microsoft's own connectors are available. However, if you do your database connectivity in code (just add the MySql.Data.MySqlClient namespace then the MySQL ADO.NET datatypes will become available to you) then it'll work fine.
Thursday, October 4, 2012 7:51 AM
- Edited by ResidentSD Tuesday, October 9, 2012 1:04 PM Correct typo
Thanks again for the message,
Once I import MySql.Data.MySqlclient namespace, I can use designer to access MySQL or I need write code to connect MySQL.
Thanks again for help,
Sorrises,Tuesday, October 9, 2012 4:34 PM | https://social.msdn.microsoft.com/Forums/en-US/18e9a015-a257-424e-a10a-8ef5d55f394e/vs-2012-express-support-database | CC-MAIN-2020-29 | refinedweb | 337 | 64.81 |
I recently presented a TechNet Webcast on the topic “Configuring with Least Privilege in SQL Server 2008”.
The topics covered in the Webcast are:-
1. Configuring SQL Server service accounts with least privilege. Service isolation is also explained.
2. Configuring accounts connecting to SQL Server from a Web application (Principals) with least privilege.
3. Running xp_cmdshell with a proxy so that the account invoking xp_cmdshell need not be a sysadmin.
4. Running SQL Server jobs with least privilege.
The Webcast can be viewed here:-
If you can find the security issue with this piece of code, write about it by adding a comment to this blog post.
This is the scenario:-
1. There is a Web site that allows end users to upload their pictures.
2. On the Web server, the Web site is physically located at C:\Inetpub\wwwroot\sampleapp, which is obviously a virtual directory.
3. The uploaded pictures are stored on the file system in the following directory C:\Uploads\{username}. This is not a virtual directory. {username} is the logged in user’s username and can contain only alphabets and numbers.
This is what the page looks like to the end user.
This is the code that gets executed. The code for the UploadPicture.aspx.cs file is this.
1: public partial class UploadPicture : System.Web.UI.Page
2: {
3: protected void Page_Load(object sender, EventArgs e)
4: {
5: lblUserName.Text = "Welcome " + User.Identity.Name;
6: }
7: protected void btnSubmit_Click(object sender, EventArgs e)
8: {
9: new UploadHelper().UploadFile(fileUploadControl, User.Identity.Name);
10: }
11: }
The code for the UploadHelper.cs file is this:-
1: public class UploadHelper
3: private string uploadFolder;
4: public UploadHelper()
5: {
6: uploadFolder = @"C:\Uploads\";
7: }
8:
9: private void SetUpUploadFolder(string userName)
10: {
11: uploadFolder += userName + @"\";
12: if (!System.IO.Directory.Exists(uploadFolder))
13: System.IO.Directory.CreateDirectory(uploadFolder);
14: }
15:
16: public string UploadFile(FileUpload fp, string userName)
17: {
18: string extension = fp.PostedFile.FileName.Substring(fp.PostedFile.FileName.LastIndexOf("."));
19: if (extension.ToLower() == ".jpg" || extension.ToLower() == ".gif")
20: {
21: string strFileName = fp.PostedFile.FileName.Substring(fp.PostedFile.FileName.LastIndexOf("\\") + 1);
22: SetUpUploadFolder(userName);
23: string strFullPath = uploadFolder + strFileName;
24: fp.SaveAs(strFullPath);
25: return strFileName;
26: }
27: return null;
28: }
29: }
If I login to the Web site as “varun” and upload a picture with name mypic.gif, it gets uploaded to this folder on the Web server:-
C:\Uploads\varun\mypic.gif
Happy Hunting!
Microsoft Virtual TechDays is starting from the 18th February 09. In the security track, I will be presenting on the topic “Top 5 Web Application Security bugs in custom code”. As a security engineer in the ACE Team, I have been reviewing line-of-business applications for the past two years. In this presentation, I will talk about the most common security mistakes that developers make while writing code. Since developers from various geographical locations tend to make the same mistakes, the audience can take back a lot of practical knowledge and apply it to secure their applications.
In my last post, I showed input validation code that uses RegularExpressionValidators improperly. Thanks to Mathew Grabau and Marius Cristian CONSTANTIN for pointing out that the Page’s IsValid property has not been checked before using the input. As a result, effectively, the code performs only client side validation, which can easily be bypassed. As a matter of fact, there are three more vulnerabilities in the code, that, together lead to a bigger vulnerability.
1. “validateRequest” is set to false.
1: <%@ Page Language="C#" ValidateRequest="false"
2: AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
2. User supplied input is, without encoding, rendered back to the browser.
1: protected void btnSubmit_Click(object sender, EventArgs e)
2: {
3: Response.Write("Welcome " + Request["txtName"]);
4: }
3. The Request object has been used ambiguously.
1: Response.Write("Welcome " + Request["txtName"]);
What I mean by ambiguously is, that, a specific collection like Request.Forms or Request.QueryString has not been used to get the input parameter. If, Request[“txtName”] is used directly, the Web server searches the collections in the following order:
QueryString Form Cookies ClientCertificate ServerVariables
If “txtName” exists in more than one collection, the Request object returns the first instance that the object encounters [1]. As a result, if “txtName” is entered in the query string as well, it will be picked up from there and not from the form variable.
Therefore, an attacker can lure a victim into clicking a link like('xss')%3b%3c%2fscript%3e
If the victim clicks on this link, enters any name in the text box and clicks the submit button, script payload in the query string will execute in the victim’s browser, leading to cross-site scripting.
A much more secure way of writing the same code would be:-
1: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
2: <html xmlns="" >
3: <body>
4: <form id="form1" runat="server">
5: <asp:TextBox</asp:TextBox>
6: <asp:Button
7: <asp:RegularExpressionValidator ID="regexpName" runat="server"
8: ErrorMessage="This expression does not validate."
9: ControlToValidate="txtName"
10:
11: </form></body></html>
1: public partial class Default2 : System.Web.UI.Page
5: }
6: protected void btnSubmit_Click(object sender, EventArgs e)
7: {
8: if (Page.IsValid)
9: {
10: Response.Write("Welcome " +
11: HttpUtility.HtmlEncode(txtName.Text));
12: }
13: }
14: }
References:-[1] Request Object
A lot of web applications use RegularExpressionValidators for performing input validation [1]. Sometimes these validators are not implemented properly, which can lead to potential flaws. See if you can catch the flaw here:-
Code for Default.aspx:-
1: <%@ Page Language="C#" ValidateRequest="false" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
2: <html xmlns="" >
3: <body>
4: <form id="form1" runat="server">
5:
6: <asp:TextBox</asp:TextBox>
7: <asp:Button
8: <asp:RegularExpressionValidator ID="regexpName" runat="server"
9: ErrorMessage="This expression does not validate."
10: ControlToValidate="txtName"
11:
12:
13: </form>
14: </body>
15: </html>
Code behind Default.aspx.cs file:-
9: Response.Write("Welcome " + Request["txtName"]);
Reference:-
[1] How To: Use Regular Expressions to Constrain Input in ASP.NET
Identify as many security issues as you can with this piece of code:-
1: [WebMethod]
2: public string GetEmpName(string empid)
3: {
4: SqlConnection con = new SqlConnection("server=.;database=test;uid=sa;pwd=PassW2rd12");
5: SqlCommand cmd = new SqlCommand("select username from users where id = " + empid, con);
6: con.Open();
7: string empname = (string)cmd.ExecuteScalar();
8: con.Close();
9: return empname;
How many did you get? Lets go over them one by one:-
1. The SQL connection string uses SQL Authentication to connect to the server. If possible, you should use Windows authentication instead. This eliminates the need to store credentials in the application.
2. If Windows Authentication is not possible, store the connection string in the web.config file and encrypt it using the aspnet_regiis tool.
3. The account used to connect to the SQL server is “sa”, which is a member of the all powerful sysadmin server role. Instead, the account used to connect to the SQL Server must have the least amount of permissions on the server as needed to do the job.
3. There is no validation for the “empid” parameter. If only integers are expected, try to parse it into an integer, otherwise use a regular expression for white list validation.
4. The “empid” parameters is being concatenated to form a SQL statement, which is then executed. This means that the application is vulnerable to SQL Injection. Instead of concatenating user input to create a SQL statement, use parameterized SQL.
5. There is no structured exception handling in this code. As a result, verbose error messages containing managed exceptions will be sent to the end user. Implement structured exception handling and close the connection in a finally block.
This is how the code looks after restructuring:-
1:
2: [WebMethod]
3: public string GetEmpName(string empid)
5: int id;
6: if (int.TryParse(empid, out id))
7: {
8: SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
9: SqlCommand cmd = new SqlCommand("select username from users where id = @id", con);
10: cmd.Parameters.Add(new SqlParameter("@id", id));
11: try
12: {
13: con.Open();
14: return (string)cmd.ExecuteScalar();
15: }
16: catch (Exception exp)
17: {
18: LogException(exp);
19: throw new ApplicationException("An unexpected error occured");
20: }
21: finally
22: {
23: if (con != null && con.State == ConnectionState.Open)
24: con.Close();
25: }
27:
28: return null;
29: }
My colleague Sagar and I will be conducting an application security workshop at the NASSCOM – DSCI Information Security Summit 2008 on the 1st December in IIIT, Hyderabad, India.
More information can be found here:-
The agenda is here:-
1. Consider a Microsoft Office SharePoint Server 2007 site that will be used as a “Document Approval System”. Certain users will be “Editors” and they will be able to upload documents for approval. Another set of users will be “Approvers”. These users can either approve or reject the uploaded documents. The security requirement is that “Editors” should not be able to approve the documents and the “Approvers” should not be able to edit or delete the documents.
2. Create a document library where the documents will be uploaded.
In this document library, create an Out-of-the-box MOSS 2007 Approval Workflow. In the “Select a task list to use with this workflow”, select “New task list”.
3. In the text box for “Approvers”, add the windows group that will contain all the “Approver” users. Also so that an editor cannot change this “Approver” group at the time the workflow is being created, uncheck the “Allow changes to the participant list when this workflow is started” checkbox.
4. As you can see a new task list is created for this workflow.
5. Give Contribute permissions on the site to the windows group that will contain the “Editors”.
This group can now add, edit and delete items from lists.
6. Now login as an “Editor” and upload a document.
Start the workflow on the uploaded document.
As you can see the approvers text box is disabled.
Once the workflow is started, a task is created in the task list specific to this workflow.
7. Let us see what happens if the “Editor” tries to approve the document herself.
We are trying to approve a workflow logged in as an editor.
The “Editor” will get an error message and the following will be added to the workflow history.
8. Now login as the “Administrator” and create a new permission level for the “Approver”. Give this permission level, edit items, view items, open items, view versions and view application pages permissions.
9. Create a new Share Point group for workflow approvers. Give it read permissions on the site.
Give the same group edit permissions on the workflow task list (that was specifically created for the approval workflow) using the “WorkflowApprovalPerm” permission just created.
The Share Point group “Workflow Approvers” now has the following effective permissions on the site. Effectively it has read-only permissions on the entire site, but “edit” permissions on the task list specific to the approval workflow.
10. Add the windows group containing all the approvers to this “Workflow Approvers” Share Point group.
11. Now login as an “Approver”. Go to the document library. See that the approver can neither edit nor delete the uploaded documents.
12. Go to the task created for approval. Try to approve it.
As you can see the “Approver” is able to approve the document.
Summary:-
This “How To” shows that it is possible using the out-of-the-box MOSS 2007 approval workflow to create a document approval system where
1. The “Editors” can only upload documents to be approved but cannot approve the documents themselves.
2. The “Approvers” can only approve or reject the documents but cannot edit or delete them.
Quite a few web applications encrypt query string values. This is generally done as an added measure to prevent unauthorized access. Since the end user cannot chose a value and then encrypt it, changing parameters becomes difficult. But encryption is not a panacea. See if you can spot this bug.
The code behind file looks like this:-
Implementation for the Encrypt and Decrypt methods is not shown. They are using the DES algorithm. There is no flaw in the usage or key management.
The end user can upload files and the screen look like this:-
On clicking Upload, the file gets uploaded and a message is shown. Note the query string values. The HTML source is also shown.
Do you think the code or design is flawed in any way? Can this be exploited?
Modern.
In my previous “Catch the Security Flaw” post I wrote about a flawed CAPTCHA implementation. In this post I discuss what are the flaws in that implementation and how to prevent them. Before I go into the exact flaws, let us agree upon a standard notation to describe the flow of data.
C stands for Client. This is the end user. S stands for Server which is the web server in this case.
In the implementation of the flawed CAPTCHA, the data flow is:-
1) C ----> S; GET somepage.aspx
2) S ----> C; Somedata || CAPTCHA Picture || hash (CAPTCHA value)
3) C ----> S; Somedata’ || hash (CAPTCHA value) || CAPTCHA value
In the flawed implementation, hash (CAPTCHA value) is being maintained on the client side as a hidden field. CAPTCHA value is supposed to be entered by the end user in the text box.
If in the 3rd step, Server gets the ”right” CAPTCHA value, it takes the action. To check if the value is “right”, the server simply hashes the CAPTCHA value sent by the client and then compares it with the hash (CAPTCHA value) also sent by the client.
To discuss the flaws, we will look only at the 3rd step. The attacker, to run an automated script, will continually call step 3.
Attack 1:- The client can take any value, say A. Then hash it to get hash (A). It can then continually call step 3 as:-
3) C ----> S; Somedata’ || hash (A) || A
This value A is not the same as in the picture in step 2. It doesn't have to be. The server does not maintain state. Hence it doesn't know that this value A is not the same as the one it had sent in the picture in step 2.
Countermeasure of Attack 1:-
So to prevent this attack, instead of hashing the value, let us encrypt it. The flow now becomes:-
2) S ----> C; Somedata || CAPTCHA Picture || Encrypt (CAPTCHA value, Key)
3) C ----> S; Somedata’ || Encrypt (CAPTCHA value, Key) || CAPTCHA value
Key is the encryption key used to encrypt the CAPTCHA value. This key is known only to the server. Now if the Client takes any value, say A. It does not have the Key to encrypt it to create Encrypt (A, Key). Hence it cannot choose any A and then call step 3. Great!
Attack 2:-
Even if the above countermeasure is put in place, the Client can still call step 3 continually. The Client can once manually see the CAPTCHA picture. Say the value in it is B. It can then call step 3 continually with the same value.
3) C ----> S; Somedata’ || Encrypt (B, Key) || B
Client doesn't know how to calculate Encrypt (B, Key). It does not need to. The Server is not storing any state. Hence the server does not know if this value has been used before.
Therefore, never forget this principle for a CAPTHCA implementation:-
“The Server MUST maintain state in a secure CAPTCHA implementation”
Countermeasure for Attack 2:-
2) S ----> C; Somedata || CAPTCHA Picture =>Server maintains CAPTHCA value
3) C ----> S; Somedata’ || CAPTCHA value =>Server verifies CAPTCHA value
In step 2, the Server creates a random CAPTCHA value and stores it on the server side. It links this value with a particular Client, say using a session ID. In step 3, the Server verifies if the value sent by the Client is the same as in its state. It then must nullify the CAPTCHA value for that client.
An ASP.NET Framework for Human Interactive Proofs
Consider a fictional web site that lets you create new accounts (as shown below).
This site implements CAPTCHA to prevent a malicious user from creating large number of false accounts by running an automated script.
The following code is used to implement the CAPTCHA. What do you think is the flaw here?
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int randomValue = GetRandomCaptchaValue();
imgCaptcha.ImageUrl = GenerateImage(randomValue);
// hdnCaptchaValue is a hidden variable.
// <asp:HiddenField
hdnCaptchaValue.Value = GenerateHash(randomValue.ToString());
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
if (GenerateHash(txtImageValue.Text).CompareTo(hdnCaptchaValue.Value) == 0)
// Code to create the account
else
lblCaptcha.Text = "The value entered is not correct.";
}
public static string GenerateHash(string text)
string hash = string.Empty;
System.Text.UnicodeEncoding uEncode = new System.Text.UnicodeEncoding();
System.Security.Cryptography.SHA512Managed sha = new System.Security.Cryptography.SHA512Managed();
Byte[] hashBuffer = sha.ComputeHash(uEncode.GetBytes(text));
return Convert.ToBase64String(hashBuffer);
}
private int GetRandomCaptchaValue()
Random random = new System.Random();
return random.Next(100001, 999999);
/// <summary>
/// This method generates an image using Bitmap class and then saves it in webroot.
/// It returns the URL of the image.
/// </summary>
/// <param name="captchaValue">URL of the image</param>
/// <returns></returns>
private string GenerateImage(int captchaValue)…
It is time to discuss the flawed code that I posted a couple of weeks back. The comments posted were good and in essence summarize the flaw.
The circled part is an example of an embedded code block. The query string parameter “id” will be inserted inside the <% %> block, creating HTML at the client that looks something like this:-
<!--<input type="text" value="123" />--> for a query string value id=123.
This can lead to Cross Site Scripting (XSS).
The countermeasure is simple. Treat user controlled input which is put inside an embedded code block with caution, even if there are comments around the HTML element. If you do not need the element, remove the embedded code block. If you need it, validate the input and encode the output.
Setting ValidateRequest to true (which is by default) would have prevented this bug from getting exploited. But would ValidateRequest prevent this from being exploited?
I will be from time to time, putting up flawed code as an open question on this blog. Those who can catch the flaw please do post about it in the comments section (preferably with the repro steps). After a few days, I will post the flaw and its countermeasure.
Here is the first one:-
I have seen quite a few web applications that rely on disabling controls for authorization. Consider this code:-
The scenario may be that the page has to be displayed in a read-only manner for certain roles, or after submission of some details but prior to approval (in a workflow). This reason depends on the business requirement. In this dummy app, the page looks like this:-
This authorization can easily be bypassed. Without using any special tool, an attacker can just enter script this way in the address bar and hit enter:-
Now the attacker enters some text and hits the submit button, completely bypassing the authorization control:-
Countermeasure:-
Check the condition in the event handler before taking action. | http://blogs.msdn.com/varun_sharma/ | crawl-002 | refinedweb | 3,234 | 57.98 |
Using ubuntu 9.10 and python, constructed with Boa:
I have written a desktop menu to provide quick access to application. It works well except that after I have opened one app, the menu program will not allow a second app to be opened until the first is closed.
I a second app is clicked, there is no response until the first is closed. the second app then starts to appear, but freezes the computer before it is complete.
A window labeled Metacity gives the message "<Subject> is not responding. Neither the Force Quit button nor the Wait button, nor the X at the top right have any effect. Opening a terminal to facilitate the kill command is frustrated when it too freezes. Only a switch off and a reboot will clear the computer.
Here is some of the button code I am using:
--------------------------------------------------------------------
def OnOOoCalcBttnButton(self, event): os.system("ooffice -calc") def OnOpenOfficeNewButton(self, event): os.system("ooffice") def OnBttnThunderbirdReadButton(self, event): os.system("thunderbird")
------------------------------------------------------------
Is there something that can be added to these functions which will eliminate my problem?
Manitoban HarryX
This post has been edited by Dogstopper: 14 March 2010 - 02:38 PM | http://www.dreamincode.net/forums/topic/161917-python-menu-program/ | CC-MAIN-2016-44 | refinedweb | 196 | 66.54 |
hi
I was wondering, how do you insert a photo from file in your program?
Printable View
hi
I was wondering, how do you insert a photo from file in your program?
I'd imagine you'd want to use a graphics API like DirectX or OpenGL to handle that.
Perhaps also GD depending on what you want:
OpenGL - good for showing photos
SDL - Good for showing photos and custom manipulation, could mix with OpenGL: Tutorial
GD - I like using this for picture manipulation but not showing it
DevIL - I used it once, can't say much
Perhaps you mean to package the program with the image not being a seperate file but "embeded" into the code. That I don't know but is doable.
Displaying images is hard. Looking at your recent threads, you probably wouldn't be up to the task at the moment. I mean, you could try it if you wanted, but it would involve a lot of code. Here's a simple SDL program that displays an image.
I just typed that into the quick reply box, so there's no guarantee it will work. But you can see how complicated things can be with images . . . .I just typed that into the quick reply box, so there's no guarantee it will work. But you can see how complicated things can be with images . . . .Code:
#include "SDL.h"
int main(int argc, char *argv[]) {
SDL_Surface *image;
SDL_Event event;
int quit = 0;
if(SDL_Init(SDL_INIT_VIDEO) < 0) return 1;
image = SDL_LoadBMP("file.bmp");
if(!image) return 1;
if(!SDL_SetVideoMode(image->w, image->h, 0, SDL_SWSURFACE)) return 1;
while(!quit) {
SDL_BlitSurface(image, 0, SDL_GetVideoSurface(), 0);
while(SDL_WaitEvent(&event)) {
switch(event->type) {
case SDL_QUIT:
case SDL_KEYDOWN:
quit = 1;
}
}
}
SDL_FreeSurface(image);
return 0;
}
thanks for the replies. i didn't know it was that hard.
but i didn't need it that much anyway. I'll just learn more c++ before trying something like this. | http://cboard.cprogramming.com/cplusplus-programming/101553-photo-program-printable-thread.html | CC-MAIN-2015-32 | refinedweb | 325 | 74.08 |
C# Nested if Statements
- In this if statement form you can declare any number of if…else statements inside another if…else.
- This is called inner or nested ifs, this form is very useful for complex programs or real world examples such as user authentication where user enters his/her name and password for authentication, that user and password must be valid, if any one from these two will be invalid user cannot be logged in.
Example:
using System; namespace csharpBasic { // Start class definition / declaration. class Program { // Static main method void type declaration. static void Main(string[] args) { // 2 string variables are initialized. string userName = "admin", userPassword = "admin123"; // An outer if statement is declared. if (userName == "admin") { // An inner if statement is declared. if (userPassword == "admin123") Console.WriteLine("You have authenticated..."); // An inner else statement is declared, this else is associated with inner if statement. else Console.WriteLine("Invalid Password!"); } // End of an outer if statement. // An outer else statement is declared, this else is associated with outer if statement. else Console.WriteLine("Invalid User name!"); Console.ReadKey(); } // End of main method definition. } // End of class. /* The Output will be: You have authenticated... */ }
REMEMBER:
- If you use parenthesis with if…else such as if (condition) {statement 1} else {statement 2} this means you can declare more than one statements or anything else inside (else or if statement’s body) and those multiple statements will be associated with that if or else statement.
- If you do not use parenthesis with if…else statements such as if (condition) statement 1; else statement 2; this means only single or one statement associates with that (if or else statement). It is recommended that use parenthesis with if…else statements. | https://tutorialstown.com/csharp-nested-if-statements/ | CC-MAIN-2018-43 | refinedweb | 285 | 57.06 |
Qt3D: how to print text? (QText2DEntity)
Hello,
I want to use Qt3D to do a 3D graph visualizer. I'm at the very beginning, studying if Qt3D could be a good option for me.
Among other, I want to print the names of the nodes in the 3D view (next to the nodes). These names should always face the camera, even if the camera moves. I have the feeling that Qt3DExtras::QText2DEntity is the class I should use. Unfortunately, its documentation is very succinct, and I can't find better example than what is shown here: (scroll to "Text Support").
I don't think I want to use the other mentioned text class (
QExtrudedText...) as I don't want 3D text.
I tried this in C++:
auto *text2d = new Qt3DExtras::QText2DEntity(_rootEntity); text2d->setText("LOL!!!"); text2d->setHeight(3); text2d->setWidth(3); text2d->setColor(Qt::green); text2d->setFont(QFont("Courier New", 10));
Unfortunately, nothing appears. From this video, it seems that the
QText2DEntityclass embed a mesh and a material, so I'm not supposed to add it (?):
I also tried in QML, even if I want a C++ solution in the end (just to test). I changed the "simple-qml" example from Qt3D to this:
import QtQuick 2.2 as QQ2 import Qt3D.Core 2.0 import Qt3D.Render 2.0 import Qt3D.Input 2.0 import Qt3D.Extras 2.9 ) } OrbitCameraController { camera: camera } components: [ RenderSettings { activeFrameGraph: ForwardRenderer { clearColor: Qt.rgba(0, 0.5, 1, 1) camera: camera } }, // Event Source will be set by the Qt3DQuickWindow InputSettings { } ] Text2DEntity { id: text text: "Hello World" width: 20 height: 10 color: Qt.red } }
But I have the same problem: nothing appears...
What am I doing wrong? Do you have any inputs on this class?
Thanks for any help :D
Nice, the documentation of this class is less than unsatisfactory, it's simply absent. But it looks like (and that's what they say in the video) that you can simply use it like any other entity, transform it, etc. What do you mean by "so I'm not supposed to add it"? I would say your setup looks about right. Did you try out different camera positions? Or to rotate the text? I'd assume that it's located at the origin, but maybe the text is flat, for example, and for the camera it becomes a 1D line. Do you know what I mean? Your camera is set to look along the z-axis, maybe add some height or rotate the text around the x-axis by 90 degrees.
If you managed to display some text, the next step would probably be to maybe subclass QEntity (I'm not sure if this is the nicest solution), and add the node and update it whenever the entity is moved. This way, you could achieve that the entity is always labeled. You then only have to define a branch of the framgraph using a QLayerFilter and a disabled depth-test (such that the text is always visible) and add the respective QLayer to the text node. You then still have to link rotation changes in the camera to a function that sets that rotation (or inverse? not sure...) on the text node.
Hope this helps.
Hi!
Thanks for your answer :) I actually have been able to display some text with this code:
// camera position auto *camera = _view->camera(); camera->setPosition({ 0, 40.0f, 0 }); camera->setViewCenter({ 0, 0, 0 }); camera->setUpVector({ 0, 0, 1.0f }); camera->panAboutViewCenter(180.0f) // text auto *text2D = new Qt3DExtras::QText2DEntity(_rootEntity); text2D->setFont(QFont("monospace")); text2D->setHeight(20); text2D->setWidth(100); text2D->setText("monospace"); text2D->setColor(Qt::yellow); auto *textTransform = new Qt3DCore::QTransform(text2D); textTransform->setRotation(QQuaternion::fromAxisAndAngle({ 1, 0, 0 }, 90.0f)); textTransform->setScale(0.125f); text2D->addComponent(textTransform);
I have to downscale it a lot!
setScale(0.125f)
The size of the font doesn't change anything, everything must be done with the scale (apparently).
I think, this is why I didn't have text before: the size (3*3) was too little and the text too big... Do you know how I could compute this window? Here I put 20*100, but it is just some magic numbers, results of tries and fails...
I'm totally new to Qt3D and really not familiar with the framegraph and all. Do you have links to some tutorials or good starting points? Thanks a lot :)
And Qt3D's documentation is a pain in the ***, unfortunately. And I don't know how to compute the size to fit the text. Maybe have a look into the git repository, they compute some sizes there.
They compute the size of the The only good starting points that I know of are actual examples. I wrote two relatively simple framegraphs for a background image and offscreen rendering. This example helped me understand the framgraph, as well.
One things that really confused me was that the framegraph and the scenegraph classes share the same baseclass: QNode. But the framegraph nodes are all of type QFrameGraphNode and the scene graph nodes are all of type QEntity.
Another thing I really didn't understand was how to set a custom framegraph on the Qt3DWindow and what this render settings thing was. Well, the QRenderSettings are supposed to hold the whole frame graph. But in the end, you have to add the settings to a root QEntity, which is the root of the WHOLE graph, i.e. the root of the framegraph and the scene graph. This root entity is then set as the root on the aspect engine, which does all the processing in the background. If you want rendernig, you have to add a QRenderAspect to the engine (same goes for input, etc.). The aspect (or whatever) uses the render settings to retrieve the framegraph and process all nodes. Like I said before, I was really confused first because I didn't sometimes get the difference between the nodes (e.g. there is a QLayerFilter, which should be part of the framegraph, and a QLayer, which should be part of the scene graph -> this way you can ensure that only one branch of the scene graph is being process by the branch employing the QLayerFilter).
This was probably a quite confusing text but I hope I helped you in some way :D
Thanks for all your help :)
I mark this thread as solved. I'll eventually update it if / when I succeed to do the last steps.
As it is just for demo right now, I don't want to go in to much complexity.
I looked at your repos, and it helped me a lot to understand how it works. It will surely help me in the future :D
@zespy , hello!
I've been trying to do exactly same thing - print text with QText2DEntity.
And, unfortunately, that code doesn't work for me. I've been variating all parameters for a while and haven't reach any result - just nothing appears on screene.
Is it possible to add any other example or\and example project?
And thank's you for this thread, it's still biggest conversation about QText2DEntity usage
I've got the same issue with Qt3DExtras::QText2DEntity. But I found the workaround.
Look like there is a bug? in implementation of Qt3DExtras::QText2DEntity that prevents internal initialization (
QText2DEntityPrivate::setSceneis never called). This happens when scene is already visible and Qt3DExtras::QText2DEntity is created with parent entity passed to constructor. The workaround I used to make it work is to pass nullptr (which is default) as parent in constructor and call ->setParent(parentEntity) in separate call.
m_text2dLabel = new Qt3DExtras::QText2DEntity(); m_text2dLabel->setParent(parentNode); | https://forum.qt.io/topic/92944/qt3d-how-to-print-text-qtext2dentity/7 | CC-MAIN-2019-39 | refinedweb | 1,279 | 65.22 |
Revision: 8528
Author: jodyer@adobe.com
Date: 2009-07-13 09:45:02 -0700 (Mon, 13 Jul 2009)
Log Message:
***********
This change adds support for the new API versioning solution (see design note below). There are two signficant changes: 1/ActionBlockEmitter translates version (legacy "Version" and new "API" named) metadata into version markers on the annotated traits' names; and 2/AbcParser strips traits that are introduced in a larger version than the version of the code being compiled. Some helper support has been added to Context. Information about the current versions is recorded in the Flash Runtime provided APIVersions.java.
QE: Yes. (Chris Peyer has the test plan)
Doc: Maybe. Users and tools which want to compile code as though it was an earlier version need to know about the -api flag
Checkintests: PASS (asc-tests PASS too, except where they were already broken)
Reviewer: Peter D.
Bugs: ASC-3771 - ASC needs to support versioning of Flash Runtime APIs
###
API Versioning in Argo/Athena
Jeff Dyer
09-Jul-2009
BACKGROUND
Logically, a version can be thought of as a set of bindings. There is a partial order of versions such that every version is a subset of itself and zero or more other versions. A version is said to be compatible with every other version of which it is a superset including itself.
In AIR 2.0 (Athena, which includes Argo), the partial order is such
FP_9_0 < AIR_1_0
FP_9_0 < FP_10_0
AIR_1_0 < AIR_1_5
FP_10_0 < FP_10_1
FP_10_0 < AIR_1_5
AIR_1_5 < AIR_1_5_1
AIR_!_5_1 < AIR_2_0
FP_10_1 < AIR_2_0
From these relations we can see, for example, that a binding introduced in FP9 will be in every other version; a binding introduced in AIR_1_0 is not in FP_9_0 but is in AIR_1_5; and a bidning introduced in AIR_2_0 is only in AIR_2_0.
Library code definitions are of the version specified by the version metadata or by default of the smallest version (FP_9_0). Library code references are always of the largest version (in this case AIR_2_0). This means that regardless of the version it was introduced library code references can ?\226?\128?\156see?\226?\128?\157 all bindings.
Client code is of the version it was built with as determined by the SWF version or some other application specific information.
Only public names in the Flash runtime built-ins (avmglue and avmcore) may be versioned. Versioning names in a private, protected, internal, interface, or user defined namespace is prohibited. Note: Private names are not visible outside of the builtin code and so versioning has no effect on them; other names might be visible outside of the builtin code but are not required by targeted use cases to be versioned and therefore doing so unnecessarily complicates the implementation.
We further limit the set of names being versioned to those whose namespaces have one of the flash runtime package names or the empty string.
USAGE
API Version Metadata
The metadata syntax for marking a builtin API with a version is this:
VersionMetaData := ?\226?\128?\152[?\226?\128?\152 ?\226?\128?\152API?\226?\128?\153 ?\226?\128?\152(?\226?\128?\152 VersionList ?\226?\128?\152)?\226?\128?\153 ?\226?\128?\152]?\226?\128?\153
VersionList := VersionList ?\226?\128?\152,?\226?\128?\153 Version
Version := Integer (between 660 and 666, in Argo/Athena)
ASC configuration variables are defined to alias these integers:
FP_9_0 660
AIR_1_0 661
FP_10_0 662
AIR_1_5 663
AIR_1_5_1 664
FP_10_1 665
AIR_2_0 666
These values are derived from an enum definition in splayer.h
enum APIVersion {
APIVersionNotYetKnown = 659,
FP_9_0,
AIR_1_0,
FP_10_0,
AIR_1_5,
AIR_1_5_1,
FP_10_0_32,
AIR_1_5_2,
FP_10_1,
AIR_2_0,
AIR_ZEPHYR,
// | https://forums.adobe.com/thread/461470 | CC-MAIN-2017-51 | refinedweb | 590 | 59.03 |
martian 0.14
Martian is a library that allows the embedding of configuration information in Python code. Martian can then grok the system and do the appropriate configuration registrations. One example of a system that uses Martian is the system where it originated: Grok ()
A library to grok configuration from Python code.
Martian tutorial
Introduction
"There was so much to grok, so little to grok from." -- Stranger in a Strange Land, by Robert A. Heinlein
Martian provides infrastructure for declarative configuration of Python code. Martian is especially useful for the construction of frameworks that need to provide a flexible plugin infrastructure. Martian doesn't actually provide infrastructure for plugin registries (except for itself). Many frameworks have their own systems for this, and if you need a generic one, you might want to consider zope.component. Martian just allows you to make the registration of plugins less verbose.
You can see Martian as doing something that you can also solve with metaclasses, with the following advantages:
- the developer of the framework doesn't have to write a lot of ad-hoc metaclasses anymore; instead we offer an infrastructure to make life easier.
- configuration doesn't need to happen at import time, but can happen at program startup time. This also makes configuration more tractable for a developer.
- we don't bother the developer that uses the framework with the surprising behavior that metaclasses sometimes bring. The classes the user has to deal with are normal classes.
Why is this package named martian? In the novel "Stranger in a Strange Land", the verb grok is introduced:
Grok means to understand so thoroughly that the observer becomes a part of the observed -- to merge, blend, intermarry, lose identity in group experience.
In the context of this package, "grokking" stands for the process of deducing declarative configuration actions from Python code. In the novel, grokking is originally a concept that comes from the planet Mars. Martians grok. Since this package helps you grok code, it's called Martian.
Martian provides a framework that allows configuration to be expressed in declarative Python code. These declarations can often be deduced from the structure of the code itself. The idea is to make these declarations so minimal and easy to read that even extensive configuration does not overly burden the programmers working with the code.
The martian package is a spin-off from the Grok project, in the context of which this codebase was first developed. While Grok uses it, the code is completely independent of Grok.
Motivation
"Deducing declarative configuration actions from Python code" - that sounds very abstract. What does it actually mean? What is configuration? What is declarative configuration? In order to explain this, we'll first take a look at configuration.
Larger frameworks often offer a lot of points where you can modify their behavior: ways to combine its own components with components you provide yourself to build a larger application. A framework offers points where it can be configured with plugin code. When you plug some code into a plugin point, it results in the updating of some registry somewhere with the new plugin. When the framework uses a plugin, it will first look it up in the registry. The action of registering some component into a registry can be called configuration.
Let's look at an example framework that offers a plugin point. We introduce a very simple framework for plugging in different template languages, where each template language uses its own extension. You can then supply the framework with the template body and the template extension and some data, and render the template.
Let's look at the framework:
>>> import string >>> class templating(FakeModule): ... ... class InterpolationTemplate(object): ... "Use %(foo)s for dictionary interpolation." ... def __init__(self, text): ... self.text = text ... def render(self, **kw): ... return self.text % kw ... ... class TemplateStringTemplate(object): ... "PEP 292 string substitutions." ... def __init__(self, text): ... self.template = string.Template(text) ... def render(self, **kw): ... return self.template.substitute(**kw) ... ... # the registry, we plug in the two templating systems right away ... extension_handlers = { '.txt': InterpolationTemplate, ... '.tmpl': TemplateStringTemplate } ... ... def render(data, extension, **kw): ... """Render the template at filepath with arguments. ... ... data - the data in the file ... extension - the extension of the file ... keyword arguments - variables to interpolate ... ... In a real framework you could pass in the file path instead of ... data and extension, but we don't want to open files in our ... example. ... ... Returns the rendered template ... """ ... template = extension_handlers[extension](data) ... return template.render(**kw)
Since normally we cannot create modules in a doctest, we have emulated the templating Python module using the FakeModule class. Whenever you see FakeModule subclasses, imagine you're looking at a module definition in a .py file. Now that we have defined a module templating, we also need to be able to import it. Fake modules are always placed automatically into the martiantest.fake namespace so you can import them from there:
>>> from martiantest.fake import templating
Now let's try the render function for the registered template types, to demonstrate that our framework works:
>>> templating.render('Hello %(name)s!', '.txt', name="world") 'Hello world!' >>> templating.render('Hello ${name}!', '.tmpl', name="universe") 'Hello universe!'
File extensions that we do not recognize cause a KeyError to be raised:
>>> templating.render('Hello', '.silly', name="test") Traceback (most recent call last): ... KeyError: '.silly'
We now want to plug into this filehandler framework and provide a handler for .silly files. Since we are writing a plugin, we cannot change the templating module directly. Let's write an extension module instead:
>>> class sillytemplating(FakeModule): ... class SillyTemplate(object): ... "Replace {key} with dictionary values." ... def __init__(self, text): ... self.text = text ... def render(self, **kw): ... text = self.text ... for key, value in kw.items(): ... text = text.replace('{%s}' % key, value) ... return text ... ... templating.extension_handlers['.silly'] = SillyTemplate >>> from martiantest.fake import sillytemplating
In the extension module, we manipulate the extension_handlers dictionary of the templating module (in normal code we'd need to import it first), and plug in our own function. .silly handling works now:
>>> templating.render('Hello {name}!', '.silly', name="galaxy") 'Hello galaxy!'
Above we plug into our extension_handler registry using Python code. Using separate code to manually hook components into registries can get rather cumbersome - each time you write a plugin, you also need to remember you need to register it.
Doing template registration in Python code also poses a maintenance risk. It is tempting to start doing fancy things in Python code such as conditional configuration, making the configuration state of a program hard to understand. Another problem is that doing configuration at import time can also lead to unwanted side effects during import, as well as ordering problems, where you want to import something that really needs configuration state in another module that is imported later. Finally, it can also make code harder to test, as configuration is loaded always when you import the module, even if in your test perhaps you don't want it to be.
Martian provides a framework that allows configuration to be expressed in declarative Python code. Martian is based on the realization that what to configure where can often be deduced from the structure of Python code itself, especially when it can be annotated with additional declarations. The idea is to make it so easy to write and register a plugin so that even extensive configuration does not overly burden the developer.
Configuration actions are executed during a separate phase ("grok time"), not at import time, which makes it easier to reason about and easier to test.
Configuration the Martian Way
Let's now transform the above templating module and the sillytemplating module to use Martian. First we must recognize that every template language is configured to work for a particular extension. With Martian, we annotate the classes themselves with this configuration information. Annotations happen using directives, which look like function calls in the class body.
Let's create an extension directive that can take a single string as an argument, the file extension to register the template class for:
>>> import martian >>> class extension(martian.Directive): ... scope = martian.CLASS ... store = martian.ONCE ... default = None
We also need a way to easily recognize all template classes. The normal pattern for this in Martian is to use a base class, so let's define a Template base class:
>>> class Template(object): ... pass
We now have enough infrastructure to allow us to change the code to use Martian style base class and annotations:
>>> class templating(FakeModule): ... ... class InterpolationTemplate(Template): ... "Use %(foo)s for dictionary interpolation." ... extension('.txt') ... def __init__(self, text): ... self.text = text ... def render(self, **kw): ... return self.text % kw ... ... class TemplateStringTemplate(Template): ... "PEP 292 string substitutions." ... extension('.tmpl') ... def __init__(self, text): ... self.template = string.Template(text) ... def render(self, **kw): ... return self.template.substitute(**kw) ... ... # the registry, empty to start with ... extension_handlers = {} ... ... def render(data, extension, **kw): ... # this hasn't changed ... template = extension_handlers[extension](data) ... return template.render(**kw) >>> from martiantest.fake import templating
As you can see, there have been very few changes:
- we made the template classes inherit from Template.
- we use the extension directive in the template classes.
- we stopped pre-filling the extension_handlers dictionary.
So how do we fill the extension_handlers dictionary with the right template languages? Now we can use Martian. We define a grokker for Template that registers the template classes in the extension_handlers registry:
>>> class meta(FakeModule): ... class TemplateGrokker(martian.ClassGrokker): ... martian.component(Template) ... martian.directive(extension) ... def execute(self, class_, extension, **kw): ... templating.extension_handlers[extension] = class_ ... return True >>> from martiantest.fake import meta
What does this do? A ClassGrokker has its execute method called for subclasses of what's indicated by the martian.component directive. You can also declare what directives a ClassGrokker expects on this component by using martian.directive() (the directive directive!) one or more times.
The execute method takes the class to be grokked as the first argument, and the values of the directives used will be passed in as additional parameters into the execute method. The framework can also pass along an arbitrary number of extra keyword arguments during the grokking process, so we need to declare **kw to make sure we can handle these.
All our grokkers will be collected in a special Martian-specific registry:
>>> reg = martian.GrokkerRegistry()
We will need to make sure the system is aware of the TemplateGrokker defined in the meta module first, so let's register it first. We can do this by simply grokking the meta module:
>>> reg.grok('meta', meta) True
Because TemplateGrokker is now registered, our registry now knows how to grok Template subclasses. Let's grok the templating module:
>>> reg.grok('templating', templating) True
Let's try the render function of templating again, to demonstrate we have successfully grokked the template classes:
>>> templating.render('Hello %(name)s!', '.txt', name="world") 'Hello world!' >>> templating.render('Hello ${name}!', '.tmpl', name="universe") 'Hello universe!'
.silly hasn't been registered yet:
>>> templating.render('Hello', '.silly', name="test") Traceback (most recent call last): ... KeyError: '.silly'
Let's now register .silly from an extension module:
>>> class sillytemplating(FakeModule): ... class SillyTemplate(Template): ... "Replace {key} with dictionary values." ... extension('.silly') ... def __init__(self, text): ... self.text = text ... def render(self, **kw): ... text = self.text ... for key, value in kw.items(): ... text = text.replace('{%s}' % key, value) ... return text >>> from martiantest.fake import sillytemplating
As you can see, the developer that uses the framework has no need anymore to know about templating.extension_handlers. Instead we can simply grok the module to have SillyTemplate be register appropriately:
>>> reg.grok('sillytemplating', sillytemplating) True
We can now use the .silly templating engine too:
>>> templating.render('Hello {name}!', '.silly', name="galaxy") 'Hello galaxy!'
Admittedly it is hard to demonstrate Martian well with a small example like this. In the end we have actually written more code than in the basic framework, after all. But even in this small example, the templating and sillytemplating module have become more declarative in nature. The developer that uses the framework will not need to know anymore about things like templating.extension_handlers or an API to register things there. Instead the developer can registering a new template system anywhere, as long as he subclasses from Template, and as long as his code is grokked by the system.
Finally note how Martian was used to define the TemplateGrokker as well. In this way Martian can use itself to extend itself.
Grokking instances
Above we've seen how you can grok classes. Martian also supplies a way to grok instances. This is less common in typical frameworks, and has the drawback that no class-level directives can be used, but can still be useful.
Let's imagine a case where we have a zoo framework with an Animal class, and we want to track instances of it:
>>> class Animal(object): ... def __init__(self, name): ... self.name = name >>> class zoo(FakeModule): ... horse = Animal('horse') ... chicken = Animal('chicken') ... elephant = Animal('elephant') ... lion = Animal('lion') ... animals = {} >>> from martiantest.fake import zoo
We define an InstanceGrokker subclass to grok Animal instances:
>>> class meta(FakeModule): ... class AnimalGrokker(martian.InstanceGrokker): ... martian.component(Animal) ... def execute(self, instance, **kw): ... zoo.animals[instance.name] = instance ... return True >>> from martiantest.fake import meta
Let's create a new registry with the AnimalGrokker in it:
>>> reg = martian.GrokkerRegistry() >>> reg.grok('meta', meta) True
We can now grok the zoo module:
>>> reg.grok('zoo', zoo) True
The animals will now be in the animals dictionary:
>>> sorted(zoo.animals.items()) [('chicken', <Animal object at ...>), ('elephant', <Animal object at ...>), ('horse', <Animal object at ...>), ('lion', <Animal object at ...>)]
More information
For many more details and examples of more kinds of grokkers, please see src/martian/core.txt. For more information on directives see src/martian/directive.txt.
CHANGES
0.14 (2010-11-03)
Feature changes
The computation of the default value for a directive can now be defined inside the directive class definition. Whenever there is a get_default classmethod, it is used for computing the default:
class name(Directive): scope = CLASS store = ONCE @classmethod def get_default(cls, component, module=None, **data): return component.__name__.lower()
When binding the directive, the default-default behaviour can still be overriden by passing a get_default function:
def another_default(component, module=None, **data): return component.__name__.lower() name.bind(get_default=another_default).get(some_component)
Making the default behaviour intrinsic to the directive, prevents having to pass the get_default function over and over when getting values, for example in the grokkers.
0.13 (2010-11-01)
Feature changes
- Ignore all __main__ modules.
- List zope.testing as a test dependency.
0.12 (2009-06-29)
Feature changes
Changes to better support various inheritance scenarios in combination with directives. Details follow.
CLASS_OR_MODULE scope directives will be aware of inheritance of values that are defined in module-scope. Consider the following case:
module a: some_directive('A') class Foo(object): pass module b: import a class Bar(a.Foo): pass
As before, Foo will have the value A configured for it. Bar, since it inherits from Foo, will inherit this value.
CLASS_OR_MODULE and CLASS scope directives will be aware of inheritance of computed default values. Consider the following case:
module a: class Foo(object): pass module b: import a class Bar(a.Foo): pass def get_default(component, module, **data): if module.__name__ == 'a': return "we have a default value for module a" return martian.UNKNOWN
When we now do this:
some_directive.bind(get_default=get_default).get(b.Bar)
We will get the value "we have a default value for module a". This is because when trying to compute the default value for Bar we returned martian.UNKNOWN to indicate the value couldn't be found yet. The system then looks at the base class and tries again, and in this case it succeeds (as the module-name is a).
martian.ONCE_IFACE storage option to allow the creation of directives that store their value on zope.interface interfaces. This was originally in grokcore.view but was of wider usefulness.
Bugs fixed
- Ignore things that look like Python modules and packages but aren't. These are sometimes created by editors, operating systems and network file systems and we don't want to confuse them.
- Ignore .pyc and .pyo files that don't have a matching .py file via module_info_from_dotted_name if its ignore_nonsource parameter is True. The default is True. To revert to the older behavior where .pyc files were honored, pass ignore_nonsource=False.
- Pass along exclude_filter (and the new ignore_nonsource flag) to ModuleInfo constructor when it calls itself recursively.
- Replace fake_import to import fake modules in tests with a real python import statement (from martiantest.fake import my_fake_module). This works by introducing a metaclass for FakeModule that automatically registers it as a module. The irony does not escape us. This also means that martian.scan.resolve() will now work on fake modules.
0.11 (2008-09-24)
Feature changes
- Added MULTIPLE_NOBASE option for directive store. This is like MULTIPLE but doesn't inherit information from the base class.
0.10 (2008-06-06)
Feature changes
- Add a validateClass validate function for directives.
- Moved FakeModule and fake_import into a martian.testing module so that they can be reused by external packages.
- Introduce new tutorial text as README.txt. The text previously in README.txt was rather too detailed for a tutorial, so has been moved into core.txt.
- Introduce a GrokkerRegistry class that is a ModuleGrokker with a MetaMultiGrokker in it. This is the convenient thing to instantiate to start working with Grok and is demonstrated in the tutorial.
- Introduced three new martian-specific directives: martian.component, martian.directive and martian.priority. These replace the component_class, directives and priority class-level attributes. This way Grokkers look the same as what they grok. This breaks backwards compatibility again, but it's an easy replace operation. Note that martian.directive takes the directive itself as an argument, and then optionally the same arguments as the bind method of directives (name, default and get_default). It may be used multiple times. Note that martian.baseclass was already a Martian-specific directive and this has been unchanged.
- For symmetry, add an execute method to InstanceGrokker.
0.9.7 (2008-05-29)
Feature changes
- Added a MethodGrokker base class for grokkers that want to grok methods of a class rather than the whole class itself. It works quite similar to the ClassGrokker regarding directive definition, except that directives evaluated not only on class (and possibly module) level but also for each method. That way, directives can also be applied to methods (as decorators) in case they support it.
0.9.6 (2008-05-14)
Feature changes
- Refactored the martian.Directive base class yet again to allow more declarative (rather than imperative) usage in grokkers. Directives themselves no longer have a get() method nor a default value factory (get_default()). Instead you will have to "bind" the directive first which is typically done in a grokker.
- Extended the ClassGrokker baseclass with a standard grok() method that allows you to simply declare a set of directives that are used on the grokked classes. Then you just have to implement an execute() method that will receive the data from those directives as keyword arguments. This simplifies the implementation of class grokkers a lot.
0.9.5 (2008-05-04)
- scan_for_classes just needs a single second argument specifying an interface. The support for scanning for subclasses directly has been removed as it became unnecessary (due to changes in grokcore.component).
0.9.4 (2008-05-04)
Features changes
- Replaced the various directive base classes with a single martian.Directive base class:
- The directive scope is now defined with the scope class attribute using one of martian.CLASS, martian.MODULE, martian.CLASS_OR_MODULE.
- The type of storage is defined with the store class attribute using one of martian.ONCE, martian.MULTIPLE, martian.DICT.
- Directives have now gained the ability to read the value that they have set on a component or module using a get() method. The class_annotation and class_annotation_list helpers have been removed as a consequence.
- Moved the baseclass() directive from Grok to Martian.
- Added a martian.util.check_provides_one helper, in analogy to check_implements_one.
- The scan_for_classes helper now also accepts an interface argument which allows you to scan for classes based on interface rather than base classes.
Bug fixes
- added dummy package_dotted_name to BuiltinModuleInfo. This allows the grokking of views in test code using Grok's grok.testing.grok_component without a failure when it sets up the static attribute.
- no longer use the convention that classes ending in -Base will be considered base classes. You must now explicitly use the grok.baseclass() directive.
- The type check of classes uses isinstance() instead of type(). This means Grok can work with Zope 2 ExtensionClasses and metaclass programming.
0.9.3 (2008-01-26)
Feature changes
- Added an OptionalValueDirective which allows the construction of directives that take either zero or one argument. If no arguments are given, the default_value method on the directive is called. Subclasses need to override this to return the default value to use.
Restructuring
- Move some util functions that were really grok-specific out of Martian back into Grok.
0.9.2 (2007-11-20)
Bug fixes
- scan.module_info_from_dotted_name() now has special behavior when it runs into __builtin__. Previously, it would crash with an error. Now it will return an instance of BuiltinModuleInfo. This is a very simple implementation which provides just enough information to make client code work. Typically this client code is test-related so that the module context will be __builtin__.
0.9.1 (2007-10-30)
Feature changes
- Grokkers now receive a module_info keyword argument. This change is completely backwards-compatible since grokkers which don't take module_info explicitly will absorb the extra argument in **kw.
0.9 (2007-10-02)
Feature changes
- Reverted the behaviour where modules called tests or ftests were skipped by default and added an API to provides a filtering function for skipping modules to be grokked.
0.8.1 (2007-08-13)
Feature changes
- Don't grok tests or ftests modules.
Bugs fixed
- Fix a bug where if a class had multiple base classes, this could end up in the resultant list multiple times.
0.8 (2007-07-02)
Feature changes
- Initial public release.
Download
- Author: Grok project
- License: ZPL
- Package Index Owner: faassen, jw, philikon
- Package Index Maintainer: jw
- DOAP record: martian-0.14.xml | http://pypi.python.org/pypi/martian/0.14 | crawl-003 | refinedweb | 3,717 | 50.33 |
20 April 2010 10:01 [Source: ICIS news]
SHANGHAI (ICIS news)--Iran's Jam Polypropylene Co plans to start producing block copolymer grade polypropylene (PP) by the fourth quarter of 2010, a company source said at the ChinaPlas exhibition in Shanghai on Tuesday.
"Currently, we are producing only random copolymer grade, which constitutes 20% of our total PP capacity of 300,000 tonnes/year," the source said.
The company would increase its output of copolymer grades at its Assaluyeh PP plant to 50% of its total production by early 2011 to improve its bottomline, the source added.
Copolymer PP grades currently fetch a premium of $100-200/tonne (€74-148/tonne) above homopolymer PP grades.
Although production costs are higher for copolymer PP compared with homopolymer grades, the price gap made the shift to copolymer grade worthwhile, the source said.
Homopolymer grades are mainly used in food, fertilizer and cement packaging.
The bullish sentiment in the automotive and consumer durables segments has fuelled strong growth in demand for copolymer PP.
"Demand growth is very strong in markets like ?xml:namespace>
The company exports 80% of its output, selling the remaining 20% to Iranian customers.
"Consumption of hompolymer grades is much higher than that of copolymer in
By the first quarter of next year, Jam wants to increase the share of random and block copolymers to 25% each, the source said.
"The remaining 50% will comprise homopolymer grades such as BOPP (bi-axially oriented PP) film and inverted (also known as inflated) PP (IPP) film as well as raffia and injection grade PP," the source added.
ChinaPl | http://www.icis.com/Articles/2010/04/20/9351897/irans-jam-to-produce-block-copolymer-pp-by-q4-2010.html | CC-MAIN-2013-48 | refinedweb | 266 | 56.39 |
A "character class", or a "character set", is a set of characters put in square brackets. The regex engine matches only one out of several characters in the character class or character set. We place the characters we want to match between square brackets. If you want to match any vowel, we use the character set [aeiou].
A character class or set matches only a single character. The order of the characters inside a character class or set does not matter. The results are identical.
We use a hyphen inside a character class to specify a range of characters. [0-9] matches a single digit between 0 and 9. Similarly for uppercase and lowercase letters we have the character class [A-Za-z]
The following code finds and prints all the vowels in the given string
import re s = 'mother of all battles' result = re.findall(r'[aeiou]', s) print result
This gives the output
['o', 'e', 'o', 'a', 'a', 'e'] | https://www.tutorialspoint.com/What-are-character-classes-or-character-sets-used-in-Python-regular-expression | CC-MAIN-2021-17 | refinedweb | 161 | 65.62 |
I can find no examples of different ways to create a range. There's a
plethora of examples on what you can do when you start by creating a range
like so: "1..10"
But, how does one create a range when the min and max values are stored in
variables? There's no range constructor. I see that it's a form of a
list, but I see no helper methods for dynamically creating ranges given a
min and max value.
I even tried to get really fancy, but this evaluates to a string.
def v = "10..15"
assert Eval.x(v, "return x").getClass().name ==
"java.lang.String"
My use case is this. I populate a bunch of form fields with variable
definitions... but they all get passed to my code as strings. But I want to
pass port ranges and lists and maps. So, the Eval() method is exactly what
I needed.. it just isn't working for ranges.
Regards,
Jerry
Gerald R. Wiltse
jerrywiltse@gmail.com | http://mail-archives.eu.apache.org/mod_mbox/groovy-users/201604.mbox/%3CCAML1RCA_iX5j4x5rQ=m3GV-CZyLqqYR61EzngUgLnsmKKV6a8A@mail.gmail.com%3E | CC-MAIN-2020-40 | refinedweb | 170 | 86.91 |
1. The Sacred Scriptures and the spirit of prophecy (Rev. 19:10)
The Bible is prophetical; a book that reveals God's will through his Word and his works, like a book that reveals the divine plan and prophecies.
The entire Bible is a product of the Holy Spirit, who is not only the "spirit of truth" (John 16:13), but "the spirit of prophecy" (Rev. 19:10). The verb "to prophesy" (derived from the Greek preposition pro and the verb phemi) signifies "to speak, utter before". The preposition "before" in this case can mean: 1) in advance and/or 2) "beforehand. Thus, "to prophesy" is an appropriate term to describe the proclamation of the Word of GOD directly and boldly, or to confront a group or individual with it, in order to speak the truth and communicate GOD's will. So the Bible, in both senses, is a prophetic word: a book that reveals GOD's will, and also his plans and purposes.
This verse defines the testimony of Jesus himself, testimony that is in the heart, in the spirit of prophecy. These words not only define the Scripture; they also define the mark of all the pronouncements and saying that claim to be true prophecy. Jesus Christ occupies the central place in all of them, as occurs with the entire Bible. 1) The Old Testament exists to reveal Christ (Luke 24:27; John 5:39: I Pet. 1:10-12); and 2) The Holy Spirit inspired the New Testament with the same purpose (John 14:26; 16:13-15).
2. Prophecy that isn't Christ-centered is disqualified (I John 4:1-6)
Jesus Christ should be presented and honored in a way that is in accord with the Scriptures.
The heart of true prophecy is always Christ himself (Rev. 19:10), the word "prophecy" not only defines the Bible, but limits all prophetic activity that pretends to be true. This passage shows that John distinguished the spirit of truth from the spirit of error by testing them: Every spirit that confessed the immaculate glory and saving virtue of Jesus Christ was of GOD. Paul pronounced a curse upon whoever violated this healing word of the Gospel (Gal. 1:6-9). Both led the community of the early Christian Church, and confronted false teachers or teachings that pretended to have prophetic authority but failed at the time to proclaim and honor Jesus Christ in a manner consistent with the entire Scriptures.
Likewise, we should also be cautious with respect to groups or individuals who claim to have a Christian foundation: What place is Jesus given? We should also reject any prophetic activity centered on mystical activity or secondary matters. All true prophecy rests on Christ and relates itself to Him, the foundation of our faith. If it is built upon this foundation, everything will remind us of and point us to Jesus, the Son of GOD.
3. The spirit of revelation (Eph. 1:17-19)
Paul wants a type of revelation that allows people to know Christ and to understand God's power and purposes in their lives.
Paul says that he prays that the addressees of his letter receive "the spirit of wisdom and revelation", with the double objective that they may know Christ and understand the purpose and power of GOD in their lives. Such "revelation" is like drawing back the veil of the heart, so that we can receive profound understanding about the way in which the Word of GOD tries to work in our lives. It can be applied to teaching or specially anointed preaching to help people see the glory of Christ and the manifestation of his purpose and power in their lives. But by making such biblical use of the term, as it appears in Ephesians 1, is to wisely remember its even more grandiose usage.
The word "revelation" is used in two ways in the Bible. It's important to distinguish them, not only to avoid confusion in the study of the Word of GOD , but also to avoid falling into the trap of humanistic ideas and irreparable error. The Sacred Scriptures are called "the revealed Word of GOD". The Bible declares that the "Law" of GOD (Deut. 29:29) and the "prophets" (Amos 3:7) are the result of divine revelation, which describes the entire Old Testament as "revealed". In the New Testament, this word is also applied to "the scriptures" (Rom. 16:25; Eph. 3:3, Rev. 1:1), which came to form part of the complete canon of the Bible (see "The content of the Word of GOD is complete", Prov. 30:5,6).
Wisdom and understanding, as well as healthy and practical speaking, recommend that the believer today know and clearly express what is meant when "revelations" are spoken of. The Holy Spirit, speaking truthfully, gives us revelation, as this text teaches us. But this prophetic intuition should never be considered equal to the actual reception of the Holy Scriptures. In spite of all the help that our intuition can be in studying the Word of GOD, the entire purpose for the revelation of the Holy Word is to be the secure foundation for edifying our lives Matt. 7:24-29).
4. Appropriate and desirable prophecy (I Cor. 14:1)
In accordance with Joel's prophecy and Moses' hope, prophecy should be received for edification, exhortation and consolation.
The purpose of the life of the New Testament church is to be blessed by the presence of the gift of prophecy. As Paul declares here, by making us see that love is our primary pursuit, prophecy has to be well received for the "edification, exhortation and consolation" of the congregation collectively and individually (v.3). Such "prophecy" is encouragement and incentive for each other, not "words" in the biblical sense, which uses the words themselves of GOD, but through human words that the Holy Spirit singularly brings to mind.
The practice of the gift of prophecy is a purpose of the fullness of the Holy Spirit (Acts 2:17). In this the prophecy of Joel (Joel 2:28) and the hope that was expressed earlier by Moses (Num. 11:29) are fulfilled.
Peter supports the operation of the gift of prophecy (I Pet. 4:11) and Paul says that this gift is within the reach of each believer (I Cor. 14:31). This gift has the intention of giving rise to a full participation among the members of the congregation, in that all are reciprocally blessed with anointed words that spiritually edify and deepen the understanding. Such prophecy can provide an amplification of understanding, that turns hearts humbly to the worship of GOD and, suddenly, makes them realize that the Holy Spirit knows their need and is prepared to answer their prayer (I Cor. 14:24,25). This class of prophecy is also a means propel and provide vision and expectation, without which people became passive or careless (I Sam. 3:1; Prov. 29:18; Acts 2:17). These specific instructions about how to utilize the gift of prophecy, as occurs with all the gifts of the Spirit, have the purpose of avoiding one gift replacing the exercise of others, or usurping the authority of the spiritual leadership. Even more, all prophecy is subordinate to the discipline of the eternal Word of GOD, the Bible, the standard by which all prophetic expression in the church should be judged (I Cor. 14:26-33).
5. Prophecy and the sufficiency of God's Word (II Pet. 1:16-19)
No prophecy or experience has more authority than the Word of God.
When Peter encouraged the believers to speak according to "the words [oracles] of GOD" (I Pet. 4:11), he wasn't trying to say that the expressions inspired by the Holy Spirit should be a substitute for the preaching and teaching of the Word of GOD. This passage emphasizes the relative importance of the prophetic "words", or experiences that we receive, in comparison with the place that corresponds to the Scriptures themselves. Here the apostle compares his own experience with Jesus on the Mount of Transfiguration, with the permanent "prophetic word" of the Sacred Scriptures (verses 19-21). He calls the word of the Scriptures "more sure", and in this way gives us a key for understanding the entire history of the Church. If Peter tells us that his experience with Jesus himself is subordinate to the "more sure" word of the Scriptures, that has the value of a definite instruction and conclusion. It means that no experience has greater authority than the Word of GOD. This, however, shouldn't dampen our enthusiasm for the manifestations of the power and blessings of the Spirit of GOD, but should simply remind us of the relative value of each type of "word" in our scale of values.
We are also in the presence of a definitive principal. There are many who ask if we, who accept the work of the gift of prophecy with approval, do so because of a lack of conviction in regards to the "sufficiency" of the Word of GOD. In other words, do we believe that the Bible contains all that we need for salvation, for faith, and for a life of obedience to GOD? Of course, because for the believer in the Bible this is never questioned; according to the spirit in which they were pronounced, and the practical truth that Peter's words contain, there is no comparison between the eternal Word of GOD and the present "words" of prophecy. Prophecies are, according to the Bible, desirable things (I Cor. 14:1) and helpful (I Cor. 14:3,5). But the Sacred Scriptures proclaim a definitive truth that is more precious than gold: the Eternal Word of GOD (Psa. 19:7-11).
6. The subject of personal prophecy (Acts 21:11)
Personal prophecy, as a rule, is a confirmation and reflects the character of the person who offers it. It should not be considered an "imposition", and could be partial, or perhaps, not embrace the entire subject.
The Bible clearly reserves a place for personal prophecy. The prophet Nathan brought King David a word of reprimand from GOD (II Sam. 12:13); Isaiah predicted the death of Hezekiah (Is. 38:1); and in this passage, Agabus told Paul that he would have problems in Jerusalem. "Personal prophecy" refers to a prophecy ("word"), of personal character, that the Holy Spirit charges one person to give to another. Many maintain deep reserves about the gift of prophecy, due to the occasional abuse of it. True "words" can be used to manipulate others or can be applied foolishly or precipitously. This passage reveals some safeguards against the abusive use of personal prophecy, which help us to conserve this biblical practice. First, the "word" won't be something new to the person to whom it is directed, but will confirm the message that GOD has been giving him. We deduce from Acts 20:22-24, that Paul was already preoccupied with the matter that Agabus brought up. Second, the character of the person who communicates the "word" should be balanced. Agabus' credibility was accredited, not to his claim of possessing a "word", but to his fame as a faithful servant of GOD, used by the LORD to the exercise of this gift (11:28; 21:10). Third, the prophecy, or "word", shouldn't be considered "manipulative". In other words, such prophecies must never be perceived as something that someone imposes on anyone else's free will. The Christian life is neither superstitious nor governed by foolish omens nor by the tricks of gurus. Paul didn't change his plans because of Agabus' prophecy or due to the insinuations of others (verses 12-14), but he received the "word" with pondering, but, by all means, continued with his plans. Fourth, all prophecy is "partial" (I Cor. 13:9), which signifies that no matter how truthful that "word" may be, it doesn't give us the complete picture. Agabus' "word" was certain, and Paul was attacked in Jerusalem. But this also offered him an opportunity to minister in Rome (Acts 23:11). Finally, confronted by a "word", we must consider it in prayer, as Mary did with the information from the shepherds (Luke 2:19). A precipitous response isn't what is requires: we must always wait on GOD. We should then advance in life with full trust in GOD, as King Hezekiah did. He was told that he would soon die; but instead of giving up before the prophecy, he went to GOD in prayer, and his infirmity was cut short. Occasional personal prophecy doesn't constitute a risk if it's maintained within biblical norms, but neither should it become a resource for planning or directing our lives.
7. The job of a prophet (Acts 11:27-30)
The ministry of prophecy is for edification of the Body: to make it grow (Greek auxano) and to give it new life, whether it be locally, or universally.
Agabus is an example of the "office of prophet in the New Testament. This role differs in form from the way the gift of prophecy works in the life of the believer, because it suggests a ministry entrusted by Christ to a person, rather than a gift dispensed by the Holy Spirit through a person. In the New Testament, this office wasn't exalted as much as it seems to be nowadays. All sensationalism is unworthy, as much in the prophet as in those to whom he ministers, and will certainly result in an unfruitful end. (Apparently, Paul was referring to a similar attitude toward the prophetic office when he pronounced the challenge in I Corinthians 14:37, where he exhorts them to submit to the spiritual authority and not to the complete autonomy of the individual). The office of prophet shouldn't be taken lightly. There is nothing in the New Testament that diminishes the strict requisites that regulate the fulfillment of this function; we have to take Deuteronomy 18:20-22 seriously. Prophecy isn't for "experimenting", for the future of souls is in the balance when this ministry is exercised.
Wisdom is gained when it's discovered that, in accordance with the Bible, the prophet fulfills more than a ministry. If it's rather certain that a few exercised notable gifts of preaching (Daniel, Zechariah, John), other characteristics of the prophetic office are also seen: 1) prediction especially on a national or international level (John the Baptist); 2) teaching: especially when an extraordinary sense of rapport exists and it makes a great contribution in service to the people of GOD (Ezra); 3) miracles: as notable signs that accompany the prophet's prophesy; (Elisha); 4) restoration (or renewal): as with Samuel (I Sam. 3:21; 4:1) or that for which the psalmist and Amos asked (Psa. 74:9; Amos 8:11,12).
The incident with Agabus resulted in the Church's effective action when faced with a challenging situation. This constitutes a valid proof of the prophetic office, that is for edification and not for entertainment; to expand and renew the body of the Church, locally as well as further away.
8. The purpose of prophecies that show the future (Deut. 28:1)
The purposes of predictive prophecies are to teach, to warn, and to instruct for an obedient and fruitful life.
Promises and prophecy abound in the Bible. GOD assured that he was ready to bless and often speaks of things that he proposes to do in the future. In both cases there are always conditions: GOD's calling to conform to his will so that his promise can bless the obedient. Chapter 28 constitutes a classic example, as much of the promises as the prophecies of GOD. Compare verses 1, 2 and 58, 59 to appreciate the blessings promised to the obedient and the judgments that are foretold for the disobedient.
This is an example of the purpose of predictive prophecy in the Bible, which serves to warn and teach obedience and a fruitful life. It's never pronounced to satisfy, provoke curiosity or promote divination. In Matthew 24 Jesus pronounces several prophecies about things to come, but he only suggests a practical norm for the disciples: watch (v.42), don't try to divine the possible course of events to come (v.36).
In another place, our LORD indicated that predictive prophecies are also given to help us trust in the sovereignty and omniscience of GOD, who has control over events and knows the end from the beginning. Notice his words in John 13:19; 14:20 and 16:4, where he emphasizes on three occasions the purpose of his prediction: "so that when it occurs, you can believe that I am" (that is, the Son of GOD, the Messiah).
9. Prophecies about the end times (I John 2:18)
God is sovereign over history, which will reveal Him to be wise and just to all who will come before His presence.
Eschatology is that aspect of biblical doctrine that deals with the "end times" (from the Greek eschatos, "final"). In this verse, John describes the times in which he wrote as "the final hour", putting into evidence the fact that he, as well as true Christians in each generation, would live in the immediate anticipation of the Second Coming of Christ. He also saw his century as one in which the present evidence appeared to show that that generation would possibly be the last. That's not a harmful or negative attitude: Christ Jesus desires that his people be on the lookout for his return (Matt 25:1-13; II Tim. 4:8).
John not only tackled history's final hour, as he saw it; but he also spoke of the Antichrist, a theme that is commonly discussed when eschatology is studied. The spirit of antichrist, the Church being caught away, the Great Tribulation, the restoration of the nation of Israel, and Christ' millennial reign on Earth are all within the theme that the Bible describes as "the end times". The Bible says that these things will occur, but isn't clear when they will happen and, in many cases, doesn't offer us the conclusive sequence or the exact manner in which these acts will be fulfilled.
The Biblia Plenitud doesn't adopt any conclusive point of view about these themes or subjects of popular discussion. We do affirm the following: 1) GOD is the Sovereign of the Universe and the GOD of History, which is his History. 2) As such, he knew the end from the beginning, and at the end of history, it will be irrefutably proven that GOD is wise and just. 3)His Son, Christ Jesus, will return to Earth for his Church (John 14:1-3; Acts 1:11; I Cor. 15:50-58; I Thes. 4:16,17), and he will govern over the earth (Isaiah 9:7; 11:6-9; Rev. 20:1-6). 4) There is a final judgment, with the recompense of eternal life in heaven, promised to the redeemed, and a judgment of eternal perdition in hell for the unregenerate (Rev. 20:11-15; 21:22-22:5).
We affirm the value of the study of "the end times" and, likewise, declare our conviction that differences of opinion over subjects such as the Rapture, the nature of the Millennium, and so on, neither gives us any advantage, nor hinders us, in relation to our life in Christ, when we choose to serve him in his love, walk in his truth, and be in expectation of his return.
10. Various interpretations of Revelation (Rev. 4:1)
The book of Revelation allows a wide range of interpretations, whose common denominator is the final triumph of Jesus Christ.
Many devout Christians are surprised to discover that other equally consecrated believers see the prophecies of the book of Revelation in mode different than they do. The book truly admits a full gamut of interpretations, but the common denominator of all is the final triumph of Jesus Christ, who makes history culminate with his final coming and who reigns with and through his Church forever.
The most popular and fully discussed interpretation is that which is called the dispensationalist interpretation. This proposes that 4:1 alludes to the Rapture or Snatching of the Church, when the redeemed in Christ are translated to heaven in the Second Coming of Christ to receive him "in the air" (I Thess. 4:17). Revelation 6-18 is perceived as the great tribulation (Matt. 24:21), of the wrath of GOD (I Thess. 5:9). This interpretation sees, in this age, the nation of Israel as the people of GOD upon earth (the Church having been raptured); restored Jerusalem, protected by the divine seal (7:1-8), worshiping in a rebuilt temple (11:1-3), and suffering at the hands of the Antichrist.
Not as fully popularized, but no less equally believed, is the Moderate Futurist viewpoint. This school of interpretation proposes the book of Revelation summaries the long pilgrimage of the Church in the process of tribulation and triumph, struggle and victory, all which finds its consumation in the return of Christ Jesus. According to this line of interpretation, the tribulation is generally seen as something that is extended in time but increases in intensity, and the Church as present through the greater part of the disturbances on earth, until a little while after the pouring out of "the cups filled with the wrath of GOD" (15:7). This occurs during chapter 16 and culminates with the collapse of the present world order (chapters 17 and 18).
Among other opinions there are: 1) The Historicist sees Revelation as a symbolic prophecy of the entire history of the Church, and the events of the book as a scene of the events and movements that the conflict and progress of the Christian Church have given form to. 2) The Preterist viewpoint sees Revelation as a message of hope and consolation directed to the believers of the 1st century only, in order to offer them a hope of deliverance from the Roman persecution and oppression. 3) The Idealist school doesn't draw any particular historical focus, or make any effort to interpret specific parts of the book, but sees it rather as a broad and poetic representation of the conflict between the kingdom of GOD and the powers of Satan.
11. The "Day of the Lord" in prophecy (Obad. 15)
The "Day of the Lord" refers to the time when God intervenes to bring salvation to his people, and punishes the rebellious.
The Old Testament prophets invoke the "Day of Jehovah" to refer to a moment in the history of mankind when GOD will intervene directly in order to bring salvation to his people and punish his enemies. He will thus restore the lost order on earth. The terms "that day", or simply "the day", are used at times as synonyms for the complete expression: the "Day of Jehovah".
The fulfillment of this prophecy should be seen, however, as a process in four stages: In the time of the prophets it was manifested in events like the invasion of Israel by powerful neighbors (Amos), the terrible plagues of locusts (Joel), and the Israelites' return from the Captivity (Ezra-Nehemiah); that prophetic vision had the virtue of being based on eschatological periods, so that even the prophets themselves weren't able to distinguish the various occasions in which their prophecies would be fulfilled; thus "that day" would become a much fuller biblical concept. The prophetic events nearest to the prophet's time were mixed with those whose consummation would take place in the end times. The first coming of Christ and the beginnings of the Church era inaugurated a new phase of the Day of the LORD. As the protagonist of these occurrences, the Church can ask the resurrected Christ to remove the spiritual forces that block GOD's work in the present world and who makes the Church the object of his innumerable blessings. This is evidenced by comparing Isaiah 61:1,2 with Luke 4:18,19 and Joel 2:25-32 with Acts 2:16-21. The Second Coming of Christ will inaugurate the third phase of the Day of the LORD, when his universal lordship of righteousness will restore GOD's order upon the earth (Is. 11:6-9; Amos 9:13); Finally, the Day of the LORD announces the arrival of the world to come, with its new heaven and new earth. Compare Ezekiel 47:1-12 with Revelation 22:1-5.
12. Prophecy and the future of Israel (Psa. 122:6)
The differences between positions dealing with Israel's future are based on the following: Israel still enjoys, as ancient people of God, a privileged place in the Divine dispensation, or it has been lost due to its unbelief.
Theologically, there are two different positions about what can be expected in the future of Israel. The difference is centered in the question: "Has Israel still, as the ancient people of GOD, a favorite place in the divine economy, or did it lose that position due to its unbelief?
Many see a continuity and distinct role for Israel in the divine plans until the end of time. They believe that Romans 9-11 indicates that there has to be a restoration of Israel ("all Israel will be saved", Rom. 11:26) and that the Church needs to recognize its Jewish roots ("you don't sustain the root, but the root sustains you", Rom. 11:18). This viewpoint also accepts the fulfillment of some Old Testament blessings and promises with individual believers and through the Church. The Church should demonstrate what it means to enjoy the full blessing of GOD to encourage Israel to return to the one who eternally loves it.
But others have seen the Church replacing Israel in the divine plan, because the majority of the Jewish people refused to accept Jesus as the Messiah. There, the blessings and promises, of which Israel was the object, today can only be applied to the Church. From this viewpoint, the modern state of Israel and the Jewish people are simply represented the same as other nations or ethnic groups, and GOD won't attend to them in a manner distinct from other peoples.
13. The Church and Israel today (Rom. 11:19-24)
It is wise for believers to avoid the presumption of apathy toward Israel, because throughout history it is obvious that God has not forgotten His people.
If it's rather certain that there basically exist two different prophetic positions about the future of Israel, there is only one biblical point of view with respect to the attitude of the Christian toward the Jewish people. First, the Bible calls us to honor the fact that, their having been the national instrument through which the Messianic blessing came to mankind (according to 9:4,5), we should "bless" the entire Jewish nation (Gen. 12:3), "pray" with sincere passion for them (Room. 10:1), and be ready to "give testimony" to any Jew, with as much spontaneity and simplicity as we would for any other human being (1:16,17).
Second, it mustn't be said that the biblical mandate of "praying for the peace of Jerusalem" (Psalm 122:6) has been annulled. Even though the text of this psalm focuses on the temple of ancient Jerusalem, the assignment shouldn't be negated. Those who take this text seriously, see the prayer for "Jerusalem" as a responsibility of constant concern because GOD extends his hand of protection and gives providential grace to the nation of Israel in particular (distinct from that of paragraph 1, which refers to Jews everywhere). It is wise that believers don't show indifference toward Israel, since the evidence of all history shows that GOD hasn't forgotten this people (Rom. 11:23,24).
[See also "The Major Prophets" and "The Minor Prophets"]
Back to Top
The focus of all prophetic truth is Jesus Christ (Heb. 1:2; Luke 24:25-27), who was destined to be the greatest prophet (Deut. 18:15-18). He declared GOD's truth in this age (John 3:31-33) and the age to come (Is. 2:2-4). As the embodiment of truth (John 1:1), Christ fully radiated the brilliance of GOD which the earliest prophets reflected only partially.
Earlier prophets anticipated Jesus Christ by reflecting His person and message in their own life and ministry (Ex. 34:29-35; I Kings 19:10; II Chron. 24:20-21). Each contributed a portion of the truth, sharing in the Spirit that would be completely expressed in Jesus Christ (John 6:68).
Prophecy was technically the task of the prophet. But all truth or revelation is prophetic, pointing to some future person, event, or thing. The full panorama of GOD's will takes many forms; it may be expressed through people, events, and objects. Historical events such as the Passover anticipated Jesus Christ (John 1:29), as did various objects in the tabernacle, including Manna (John 6:31-35) and the inner veil (Matt. 27:51; Heb. 10:20).
Prophecy may also be expressed in many different forms through the prophet himself, whether by his mouth or some bodily action. The prophets received GOD's messages from the voice of an angel (Gen. 22:14-19), the voice of GOD, a dream (Dan. 2), or a vision (Ezek. 40:2ff.). The prophetic speech might range from the somber reading of a father's last will (Gen. 49) to an exultant anthem to be sung in the Temple (Ps. 96:1,13).
Sometimes a prophet acted out his message symbolically. Isaiah's nakedness (Isaiah 20) foretold the exile of the Egyptians and the Cushites. Hosea's marriage symbolized GOD's patience with an unfaithful wife, or the nation of Israel. Ahijah divided his garment to foretell the division of the monarchy (I Kings 11:30-31). Even the names of some of the prophets are symbolic, matching their message. Hosea means "salvation"; Nahum, "comfort"; Zephaniah, "the LORD hides"; and Zechariah, "the LORD remembers".
Prophecy declared GOD's word for all time, so the time of fulfillment of a prophecy is rarely indicted in the Bible. Exceptions to this rule include the timetable assigned to Daniel's seventy weeks' prophecy (Dan. 9:24-27), the prophecy of Peter's denial (Matt. 26:34), and predictions of someone's death (Jer. 28:16-17). The common problem of knowing the time for the fulfillment of a prophecy is acknowledged by Peter (II Pet. 3:1-8). This problem is due to several factors. First, some prophecies appear together, as if they would be fulfilled simultaneously. For example, Isaiah 61:1-2 has already been fulfilled, according to Luke 4:18-19; but Isaiah 61:1, which adjoins it, awaits fulfillment. The same is true of Zechariah 9:9-10. The prophets saw the mountain peaks of prophetic events but not the valleys of time in between.
Another factor that complicates the problem is the ambiguity of tenses in the Hebrew language, which distinguishes type of action but not time of action. The prophets focused on the reality of their prophecies and not the time of their fulfillment. In their minds their prophecies were already accomplished, primarily because they knew GOD was in charge of history.
Finally, since the prophets' messages had eternal force, it is often difficult to tell whether they applied their messages to their day or the future. For example, Isaiah 7:14 promised a son who could be a contemporary of Isaiah (perhaps the prophet's son in 8:3, and 18 or the son of Hezekiah the king in Isaiah 36-39) or Jesus (Matt. 1:23), or both.).
In the same way, the destruction of Gog and Magog in Ezekiel 38 and 39 may be fulfilled in Revelation 20:8 after the Millennium. But similarities of this prophecy to earlier invasions from the north before the millennium seem to allow for its multiple fulfillment. The earlier parallels with Ezekiel 38 and 39 are two invasions from the north in Daniel 11:40,44 and a third in Revelation 19:17-18, where the birds consume the carcasses as in Ezekiel 39:17-20.
The problem of understanding when a prophecy is fulfilled is compounded if the modern reader has a theological bias about who is to fulfill a prophecy. For example, premillennilists believe that a 1,000-year reign by Christ (Rev. 20:2-7) will exalt the nation of Israel and the Jewish people in the future (Rom. 11:24-26). But amillennialists believe the promises to Israel in the Old Testament have been taken from Israel and transferred to the church (Gal. 6:16). Such a disagreement does not deny that Abraham's descendants will inherit Palestine from the River of Egypt to the Euphrates River (Gen. 15:18). But the premillennialist looks for a future revival of Israel as a nation (Ezek. 37:11-28), while the amillennialist claims the promise of the land was fulfilled in the past in the days of Joshua (Josh. 21:43-44) or Solomon (II Chron. 9:26). (The problem with that interpretation is that Israel as a nation has never occupied all of the land that GOD promised to Abraham."
Prophecy presents volumes about the future kingdom of GOD, particularly information about the Messiah and His Chosen People, Israel. Much prophecy also foretells the destiny of the nations and their relationship to the kingdom of GOD. The New Testament identifies Jesus as the King (John 1:49) who spends much of His ministry describing His kingdom and its establishment (Matthew 13; 24-25). The battleground is the world; and the arch-foe of Christ is Satan, whose intrigue in Eden gave him control of the nations (Matt. 4:9). Most prophecy is concerned with undoing Satan's work; it elaborates upon the initial promise of Genesis 3:15, which announced that Christ, the seed of the woman (Gal. 4:4), would crush the great Serpent, the Devil (Rom. 16:20; Rev. 20:2). All prophecy testifies about Jesus (Rev. 19:10).
Over 300 prophecies in the Bible speak of Jesus Christ. Specific details given by theses prophecies include His tribe (Gen. 49:10), His birthplace (Mic. 5:2), dates of His birth and death (Dan. 9:25-26), His forerunner John the Baptist (Mal. 3:1; 4:5; Matt. 11:10), His career and ministry (Is. 52:13-53:12), His crucifixion (Ps. 22:1-18), His resurrection (Ps. 16:8-11; Acts 2:25-28), His ascension (Ps. 2; Acts 13:33), and his exaltation as a priest-king (Psalm 110; Acts 2:34). The kingly magnificence of His second coming is also graphically portrayed. Psalms 2, 45, and 110 picture His conquest and dominion over the nations. His kingdom is characterized in Psalm 72. Events leading up to and including the first and second advents of Christ are described in the two burdens of the prophet Zechariah (Zechariah 9-11,12-14).
Premillennialist point to many Bible passages to support their belief in the national resurrection of Israel. Many prophecies graphically portray Israel's history (Leviticus 26; Deut. 27-28; Amos 6-9). Her bounty as a nation is prophesied in Deuteronomy 30 and Isaiah 35. Just as the nation had received a double punishment (Jer. 16:18), so it would receive a double blessing (Is. 61:7). Temple worship would be restored (Ezekiel 40-48); Israel would be the center of world government (Zechariah 1-6); and the Davidic line would be set up as a permanent dynasty (II Sam. 7:12-16; Luke 1:32-33).
Much controversy surrounds the roles of the church and Israel in the final days preceding Christ's Second Coming, known as the "day of Jacob's trouble" (Jer. 30:7), "the great tribulation" (Matt. 24:21), or "the great day of his wrath" (Rev. 6:17). This will be a period of seven years (9:27) with the most intense trial in the last three and one-half years of this time (Dan. 12:11-12; Rev. 12:6; 13:5).
As Christ's Second Coming approaches, many difficult prophecies about the Tribulation will be understood more clearly (Jer. 30:24; Dan. 11:32,35; 12:3,9-10). Premillennialists point to the establishment of the state of Israel in 1948 as just one of these signs of Christ's approaching return.
While premillennialists agree upon the restoration of Israel in the earthly reign of Jesus Christ, many are divided over the relation of Israel to the church, particularly just before Christ's appearance at the end of the Tribulation. Covenant theologians see Israel and the church as one people who go through the Tribulation together. Dispensational theologians believe Israel and the church are always separated in the Bible. As a result, dispensationalists believe the church will not join Israel in its days of tribulation, but will be transported to heaven before it begins, at the beginning of the seven years.
Three theories exist about the time of the church's departure to meet the LORD in the air (I Thes. 4:13-17): the pre-tribulational rapture, the mid-tribulational rapture, and the post-tribulational rapture. These three theories place the rapture at the time of John's ascension to heaven (Rev. 4:1), at the time when the two prophets ascend to heaven (Rev. 11:11-12), and at the end of the series of seven bowls (Rev. 16:15), respectively. | http://www.angelfire.com/sc3/wedigmontana/Prophecy.html | CC-MAIN-2017-47 | refinedweb | 6,304 | 59.03 |
Couple of interesting items related to Interop with Java and Office docs.
1st, MSDN article on saving MS-Word into XSL-FO. Oleg commented on it very favorably. In essence, you can use MS-Word as an XSL-FO designer. That's a huge step forward.
2nd, an old, but new to me, article on using Java to generate WordProcessingML. I picked this up from John R. Durant, which I found while surfing my new favorite XML-related page... which is...
3rd, TopXml's blog aggregator. High signal-to-noise ratio there.
So. what does it all mean? Well, item 2 stands on its own. That's a nice capability. In any Java app, you can generate a document that conforms to the published XML schema for MS-Office docs, produce Office docs (reports, memos, whatever), and then ship them via a webservice to a client, where they can be consumed - printed, viewed, whatever. In this scenario, there is no use of Office on the server side. It's Just XML, so it could be done on any any modern platform. [ Do mainframes speak XML? Can I write a CICS TP that generates an XML document? Hmm, I don't think I would want to do that. . . ]
2ndly, combining item 1 and 2 means that, if I for some reason don't want to use WordML, I could run the output through the RenderX XSL sheet mentioned in item 1, and generate an XSL-FO doc.
There is a license for the WordProcessingML stuff, but it is available free of charge. I don't know the license for the RenderX stylesheet but it is available for download at the MSDN article in question. Cool possibilities. . .
Ok, sure you could have been using Apache FOP as well, but ... it is really a pain to design XSL-FO docs manually, or programmatically starting from nothing. This combo allows you to use Word as the visual forms designer during development, then at runtime, use any XML-aware platform (like Java) to fill in blanks in the XML template foc, and transform to XSL-FO. This is a big step forward.
If you would like to receive an email when updates are made to this post, please register here
RSS
In the past I've posted some articles [ 1 , 2 ] about generating Office 2003 documents from a server-side
Is it really possible to use any Java application to dynamically generate MS-Word files, complete with graphics, tables, text styles, fonts, and more? Yes, quite possible. And Would you believe? - it's easy too!
Firstly great article.
Tapan - there are two different formats being discussed here. First, the .docx file format is a zip file, with a particular, well-defined internal structure. The .xml file I spoke of in this posting is different - it is the WordML format which pre-dated .docx by at least 2 years.
This particular post talks about how to format an .xml WordML document. This particular post does not talk about how to produce a .docx from Java. That is also possible, and is something I considered writing some example code for, it is not something covered here.
Now, your question has to do with querying and validating a .docx file, which is another thing entirely.
I'd suggest you look elsewhere for that. There is a System.Packaging namespace in the .NET base class library as of .NET 3.0 - it will help you if you are using .NET. If you are using Java, you will have to roll your own, I think.
Comment Policy: No HTML allowed. URIs and line breaks are converted automatically. Your e–mail address will not show up on any public page.
Connecting .NET to just about anything else | http://blogs.msdn.com/dotnetinterop/archive/2005/03/04/385184.aspx | crawl-002 | refinedweb | 626 | 76.72 |
Hi all!
As I said in a previous post, I'm working with HUGE numbers, and it was suggested to me to try GMP.
I have installed it on /usr/local/gmp-4.1.4 (with "./configure" and then "make") as it was said to be de default location. The installing procedures seemed to be ok. The validation tests were fine too.
So, I've wrote the following test.c file:
At first, I tried to compile withAt first, I tried to compile withCode:
#include <stdio.h>
#include <gmp.h>
int main (){
mpz_t i;
return;
}
gcc -o test test.c -lgmp
but I got a "gmp.h - File not found"
Then, I tried
gcc -o test test.c -I /usr/local/gmp-4.1.4 -lgmp
and
gcc -o test test.c -I /usr/local/gmp-4.1.4 -L /usr/local/gmp-4.1.4 -lgmp
and
gcc -o test test.c -I /usr/local/gmp-4.1.4/ -L /usr/local/gmp-4.1.4/lib -lgmp
but for all of them I got a "cannot find -lgmp"
As you can probably see, I'm not a C expert, so I would like to apologize if I am doing something obviously wrong. But the fact is that I am not able to simply compile that code...
PLEASE, HELP!!! :confused: :confused: :confused:
Thanks in advance, :D :D :D
Bruno | http://cboard.cprogramming.com/c-programming/70581-problem-compiling-gmp-code-printable-thread.html | CC-MAIN-2015-11 | refinedweb | 230 | 79.26 |
{-# LANGUAGE FlexibleContexts, Rank2Types #-} -- Standard boilerplate (de)serialization code -- |This module provides a small number of tricky functions used to implement -- (de)serializers. User code should not need to import this library. module Data.Generics.Serialization.Standard (ext2Q, gSerial, gDeser, (=>>), (>>$), unfoldM, match, manySat, matchs, getv_t, getcase, peekcase, matchws, space, readM, fromMaybeM, escape, unescape, mkescape, breakr) where import Data.Generics import Data.Char import Control.Monad import Data.Generics.Serialization.Streams infixl 1 >>$, =>> -- |Like 'ext1Q', except for a binary type constructor ext2Q :: (Data d, Typeable2 t) => (d -> q) -> (forall d1 d2. (Data d1, Data d2) => t d1 d2 -> q) -> (d -> q) ext2Q def ext = unQ (Q def `ext2` Q ext) newtype Q q x = Q { unQ :: x -> q } ext2 :: (Data a, Typeable2 t) => c a -> (forall a b. (Data a, Data b) => c (t a b)) -> c a ext2 def ext = maybe def id (dataCast2 ext) -- |Execute two monadic actions in sequence, returning the value of the first. -- This is mainly useful with parser combinators. (=>>) :: Monad m => m a -> m b -> m a (=>>) a b = do x <- a ; b ; return x -- |Execute a monadic action, piping the result through a pure function. This -- is the same as flip liftM, and has the same fixity as '>>='. (>>$) :: Monad m => m a -> (a -> b) -> m b (>>$) = flip liftM -- |Run a monadic action repeatedly until it returns 'Nothing'; all 'Just' -- values are returned in a list. unfoldM :: Monad m => m (Maybe a) -> m [a] unfoldM a = a >>= maybe (return []) (\v -> liftM (v:) (unfoldM a)) -- |Run a monadic action over each element in an existing data object; also -- return the 'Constr'. gSerial :: (Data d, MonadWStream m c) => (forall a . Data a => a -> m ()) -> d -> (Constr, m ()) gSerial cld v = (toConstr v, gmapQl (>>) (return ()) cld v) -- |Build an object using monadic actions to read the 'Constr' and all children. gDeser :: (Data d, Monad m) => (DataType -> m Constr) -> (forall a . Data a => m a) -> m d gDeser rc cld = (\id -> do con <- rc (dataTypeOf (id undefined)) liftM id (fromConstrM cld con)) id -- |Parse as many spaces as possible. space :: MonadRStream m Char => m () space = do ch <- peekv when (maybe False isSpace ch) $ getv >> space -- |Parse a designated character, error on a different character. match :: MonadRStream m Char => Char -> m () match ch = do chr <- getv ; when (chr /= ch) (fail ("expected '" ++ (ch:'\'':[]))) -- |Parse and return one or more characters parsed using a recognition function. manySat :: MonadRStream m a => (a -> Bool) -> m [a] manySat pred = do x <- peekv ; if (fmap pred x /= Just True) then return [] else liftM2 (:) getv (manySat pred) -- |Match a string, error on discrepancy. matchs :: MonadRStream m Char => [Char] -> m () matchs = mapM_ match -- |Get one character, then run a parser (e.g. space). getv_t :: MonadRStream m a => m b -> m a getv_t x = getv =>> x -- |Get one character and process it using a list of actions. getcase :: (Eq a, MonadRStream m a) => (a -> m b) -> [(a,m b)] -> m b getcase def lst = getv >>= \x -> maybe (def x) id (lookup x lst) -- |Peek at one character and process it using a list of actions. peekcase :: (Eq a, MonadRStream m a) => m b -> (a -> m b) -> [(a,m b)] -> m b peekcase eof def lst = do x <- peekv case x of Nothing -> eof Just x -> maybe (def x) id (lookup x lst) -- |Parse a designated character, then any amount of whitespace. matchws :: MonadRStream m Char => Char -> m () matchws ch = match ch >> space -- |Parse a value using a 'Read' instance. This differs from 'read' in that it -- uses a general monad and type infromation for error reporting. readM :: (Monad m, Read a, Typeable a) => String -> m a readM s = case filter ((=="").snd) $ reads s of ((n,_):_) -> return n v -> fail ("expected " ++ show (typeOf (fst (head v)))) -- |Convert a 'Maybe' object into any monad, using the imbedding defined by -- fail and return. fromMaybeM :: Monad m => String -> Maybe a -> m a fromMaybeM st = maybe (fail st) return -- |Escape a string. escape :: Char -> [Char] -> [Char] -> String -> String escape ec badch repch = concatMap (\c -> case lookup c (zip badch repch) of Nothing -> [c] Just n -> [ec,n]) -- |Unescape a string. unescape :: Char -> [Char] -> [Char] -> String -> Maybe String unescape ec usech repch = un' where un' (x:y:xs) | x == ec = liftM2 (:) (lookup y (zip usech repch)) (un' xs) un' (x:xs) = liftM (x :) (un' xs) un' [] = Just [] -- |Create an escape and unescape function at the same time. This allows -- you to only type the translations once. mkescape :: Char -> [Char] -> [Char] -> (String->String, String->Maybe String) mkescape ec badch repch = (escape ec badch repch, unescape ec repch badch) -- |Split a string at the rightmost occurence of a character matching a predicate. breakr :: (a -> Bool) -> [a] -> ([a],[a]) breakr p lst = case break p $ reverse lst of (a,(b:c)) -> (reverse c, b:reverse a) (_,[]) -> (lst,[]) | http://hackage.haskell.org/package/genericserialize-0.1/docs/src/Data-Generics-Serialization-Standard.html | CC-MAIN-2017-30 | refinedweb | 791 | 66.17 |
Today's Little Program locates the × button in the corner
of the window and
displays a balloon tip pointing at it.
We did this
some time ago
with the help of the
WM_ message,
which is new for Windows Vista.
But what if you don't have that message available,
say, because you're running on Windows 2000 or Windows XP
or (gasp) Windows 98?
You can use the classic Accessibility interface
IAccessible
to enumerate the buttons in the title bar and see which
one the window reports as the Close button.
Let's take the program from last time and change the
GetCloseButtonCenter function:
#include <oleacc.h> #include <atlbase> BOOL GetCloseButtonCenter(HWND hwnd, POINT *ppt) { CComPtr<IAccessible> spacc; if (FAILED(AccessibleObjectFromWindow(hwnd, OBJID_TITLEBAR, IID_PPV_ARGS(&spacc)))) return FALSE; CComQIPtr<IEnumVARIANT> spenum(spacc); if (!spenum) return FALSE; for (CComVariant vtChild; spenum->Next(1, &vtChild, nullptr) == S_OK; vtChild.Clear()) { CComVariant vtState; if (FAILED(spacc->get_accState(vtChild, &vtState))) continue; if (vtState.vt != VT_I4) continue; if (vtState.lVal & (STATE_SYSTEM_INVISIBLE | STATE_SYSTEM_OFFSCREEN | STATE_SYSTEM_UNAVAILABLE)) continue; long left, top, width, height; if (FAILED(spacc->accLocation(&left, &top, &width, &height, vtChild))) continue; POINT pt = { left + width / 2, top + height / 2 }; if (SendMessage(hwnd, WM_NCHITTEST, 0, MAKELPARAM(pt.x, pt.y)) == HTCLOSE) { *ppt = pt; return TRUE; } } return FALSE; }
We obtain the
IAccessible interface for the title bar
and proceed to enumerate its children.
For each child, we get its location, and then use the
WM_ message to determine
programmatically what that location corresponds to.
If the answer is "This is the Close button,"
then we found the button and report its center.
Note that this once again highlights
the distinction between
WM_ and
WM_.
Hit-testing can occur for reasons other than mouse movement.
Exercise:
Why couldn't we use the
IAccessible::
method to figure out which button each child represents?
Because it's localizable.
Guess: The accName will be localized, and have exciting new values in translated versions of Windows, while the program will only look for the English one and conclude that no close button exists.
Why does MS not document the system metrics used by classic/pre-uxtheme windows and common controls? web.archive.org/.../original.aspx is really useful and I wish all of this was actually documented.
@skSdnW: The size of those metrics can vary depending on the DPI settings (otherwise known as "adjust this ruler on your screen control") or if you adjusted the size of the various elements in the Appearances control panel.
They can vary, but knowing when to use which metric is indeed very useful. For example when custom drawing a column in a listview, its not always straightforward to figure out the various alignment issues, and when to use which value.
@MNGoldenEagle: When visual styles are off GetSystemMetrics and SystemParametersInfo are then only things you have to work with and knowing which SM_ values are used where would be useful. Some controls hardcode a pixel value in some places (ListView? Menu?) but most of the time there should be a metric you can use...
I'm surprised you can QueryInterface an IAccessible into an IEnumVARIANT: IEnumXxxxx are one-time used objects; that would mean the IAccessible's children can only be enumerated once...
It could be creating a subobject and returning it when handling the QI. As long as QIing the IEnumVARIANT to IUnknown returns the same IUnknown pointer as QIing the base object to IUnknown it should be legal COM. This just means going from the IEnumVariant -> IUnknown ->IEnumVariant would reset the enumeration.
@Joker_vD: Isn't that what IServiceProvider does? The services it provides don't have to implement QueryService...
Yeah, that's an exciting quirk of COM: while it stands for *Component* Object Model, you actually don't get to see any components! You only see interfaces that you cast one to another, which causes many interesting things to the components behind the scenes. Really, why couldn't we have actual components with QI to dispense interfaces? Then interfaces themselves wouldn't have QI, and I bet that would simplify aggregation tremendously.
@SI, It's barely legal COM, if at all.
If the QueryInterface for IEnumVARIANT returns the same enumerator but resetting it before, then QI is having completely undesired and unreliable side effects, most probably not observable across apartments due to interface pointer caching.
If, on the other hand, it returns a new kind-of-aggregatee enumerator (remember, QI for IUnknown must return the same pointer), given CComQIPtr<IEnumVARIANT> spenum1(spacc) and CComQIPtr<IEnumVARIANT> spenum2(spacc), the calls to spenum1->Next will not affect the calls to spenum2->Next, so it becomes apparent you're violating identity.
Either way, you should always call Clone on such QI'ed IEnumVARIANT, which should provide a fresh, non-aggregated and single-identity enumerator.
Unless, Of Course™, in this instance, Clone itself misbehaves, such as simply resetting the current enumerator and returning it (or one that shares state), because it was most likely implemented by teh the same m̶o̶r̶o̶n̶ person that miscoded QueryInterface.
@Joker_vD, I can't tell if you're being serious. QueryInterface is so essential in IUnknown that, without it, COM wouldn't even get to first base, much less being likened to love.
For instance, what good would an IUnknown pointer be, by itself, without QueryInterface? Or pick your favorite widespread used interface and ask the same question.
Objects would implement an ubiquitous casting interface e.g. IDynamicCast, you'd reduce IUnknown or have a separate interface for reference count e.g. IReferenceCount, and you'd have to decide when it was interesting to pass IDynamicCast or one of its descendants.
You can easily reach the conclusion that IDynamicCast is way (WWAAYY) more interesting, because you can get IReferenceCount, or anything at all from it.
But you'll soon find it hard to properly maintain an object's lifetime. If there was a rule stating that casting doesn't automatically increment the count, you'd have a serious Release race condition on the client. If there was a rule stating that casting to IReferenceCount doesn't increase the count, it would make only pointer to this interface, but such an important one, subject to the Release race condition. If casting would always increase the count, how would to keep the count of casts you've made? Also, how would you allow interfaces to be actual inner instances (e.g. tear-offs) or an aggregatee?
So, you easily reach the conclusion that every interface pointer must have lifetime management. Seems like IUnknown.
@Medinoc, the closest is actually IObjectProvider->QueryObject, because IServiceProvider->QueryService may delegate to a chain or hierarchy of objects. But only IUnknown->QueryInterface requires and guarantees a set of properties, such as object identity, essential to even the most basic purposes. | https://blogs.msdn.microsoft.com/oldnewthing/20140630-00/?p=623 | CC-MAIN-2017-30 | refinedweb | 1,128 | 53.41 |
Hi folks, and thanks for supporting the Slackware Project for all these
years. Here's the latest of a long line of release announcements. I keep
trying to tone down that marketing stuff... one day I'll get it right.
(Hey, we have to keep the lights on here! ;-):
Slackware 11.0 is released
Posted Oct 3, 2006 15:39 UTC (Tue) by JoeF (subscriber, #4486)
[Link]
Bunch of software released the same day?
Posted Oct 3, 2006 20:29 UTC (Tue) by gvy (guest, #11981)
[Link]
It's got a bunch of ancient software (or moderately old one on or near nex-gen release day): XFCE (4.4 is around the corner); glibc (especially funny with 2.5 release); gcc 3.4.6 (4.1.1, no?); Python (2.5 is out); Xorg 6.9 (7.1); the only choice I concur is ancient Apache (although 2.2 branch might be worth a look if its security trail won't be that horrendous as with 2.0).
I'm not a versioman myself, but trading second hand packages for new and shiny and selling slackware to beginners just seems a *real* marketing to me.
/* to save electrons on reiterating on collaboration, quality and manageability, etc */
# include <stdslackflame.h>
PS: ;-)
Posted Oct 3, 2006 21:09 UTC (Tue) by dvandeun (guest, #24273)
[Link]
Posted Oct 4, 2006 20:00 UTC (Wed) by beoba (guest, #16942)
[Link]
Posted Oct 4, 2006 20:45 UTC (Wed) by dlang (subscriber, #313)
[Link]
but mostly it's warm and fuzzies that it's not changeing significantly while 2.6 is continueing to evolve too rapidly for many people's tastes.
Speed of evolution...
Posted Oct 5, 2006 1:14 UTC (Thu) by xoddam (subscriber, #2322)
[Link]
Posted Oct 7, 2006 9:26 UTC (Sat) by oak (subscriber, #2786)
[Link]
Posted Oct 5, 2006 9:34 UTC (Thu) by dvandeun (guest, #24273)
[Link]
Ease of mind.
That, and long filenames on DOS disks of course. :-)
Posted Oct 4, 2006 0:04 UTC (Wed) by kirkengaard (subscriber, #15022)
[Link]
If you're that impatient for current stuff, watch the flux ramp up after this in -current. And consider that it could be worse. You could choose Debian stable releases. I consider this to be a nice happy medium. :)
Posted Oct 4, 2006 0:47 UTC (Wed) by allesfresser (subscriber, #216)
[Link]
Pat makes a system that works, not one built for coolness value. My impression of his standard is that he uses the latest known very-stable version of a package, not necessarily the absolute newest release.
Slackware = VERY stable Linux distribution
Posted Oct 4, 2006 7:17 UTC (Wed) by pr1268 (subscriber, #24648)
[Link]
Amen to that! Kudos to Pat and the entire Slackware Team for a stable distribution.
Thanks also to the fellow posters for enlightening us on why Slackware holds back on the GCC version - I never realized that the 2.4 kernel won't compile on GCC 4.x (I use a vanilla 2.6 myself).
Again, to quote Allesfresser, Slackware just works!
Posted Oct 5, 2006 11:37 UTC (Thu) by lysse (subscriber, #3190)
[Link]
(A dangerou is like a troll, but hairier.)
Posted Oct 9, 2006 0:23 UTC (Mon) by juhl (subscriber, #33245)
[Link]
I'll take "slightly older and stable" over "new and shiney" any day. That's one of the things that has kept me using Slackware through the years - it just works - that's worth quite a lot if you ask me.
Posted Oct 4, 2006 14:16 UTC (Wed) by tjc (subscriber, #137)
[Link]
IIRC I should just be able to boot the installer, mount the partition that contains the packages, and tell the installer where to look for them. I used to install Red Hat like this back in The Good Old Days.
Posted Oct 4, 2006 19:59 UTC (Wed) by Alan_Hicks (subscriber, #20469)
[Link]
Posted Oct 5, 2006 15:21 UTC (Thu) by tjc (subscriber, #137)
[Link]
What pacages do I need for a base install, besides everything in a/? Specifically, do I need anything from l/?
Posted Oct 5, 2006 18:29 UTC (Thu) by Alan_Hicks (subscriber, #20469)
[Link]
The a series is all that is needed for a base install. From that, you can install any other packages you need.
Posted Oct 5, 2006 21:09 UTC (Thu) by tjc (subscriber, #137)
[Link]
I realize that I should be asking these questions on the slackware forum, which is my next step. There's at least one page out there that explains all this, but I can't find it. Either it's gone, or it's google rank is way down.
Posted Oct 5, 2006 22:03 UTC (Thu) by allesfresser (subscriber, #216)
[Link]
Which packages to install
Posted Oct 5, 2006 21:08 UTC (Thu) by pr1268 (subscriber, #24648)
[Link]
Or, if you are like me and want to run Slackware like it were a "pretend" Gentoo distribution, you could install the a packages and d packages (and nothing else), then build all the other desired packages from the source directory, with your own optimizations in the SlackBuild scripts. ;-)
P.S. You might have to install the l packages as well. Be advised that a source install may be an all-day affair.
Posted Oct 5, 2006 22:05 UTC (Thu) by allesfresser (subscriber, #216)
[Link]
Linux is a registered trademark of Linus Torvalds | http://lwn.net/Articles/202580/ | crawl-001 | refinedweb | 905 | 78.59 |
S3SourceAction¶
- class
aws_cdk.aws_codepipeline_actions.
S3SourceAction(*, bucket, bucket_key, output, trigger=None, role=None, action_name, run_order=None, variables_namespace=None)¶
Bases:
aws_cdk.aws_codepipeline_actions.Action
Source that is provided by a specific Amazon S3 object.
Will trigger the pipeline as soon as the S3 object changes, but only if there is a CloudTrail Trail in the account that captures the S3 event.
- Parameters
bucket (
IBucket) – The Amazon S3 bucket that stores the source code.
bucket_key (
str) – The key within the S3 bucket that stores the source code.
-
trigger (
Optional[
S3Trigger]) – How should CodePipeline detect source changes for this Action. Note that if this is S3Trigger.EVENTS, you need to make sure to include the source Bucket in a CloudTrail Trail, as otherwise the CloudWatch Events will not be emitted. Default: S3Trigger.POLL | https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_codepipeline_actions/S3SourceAction.html | CC-MAIN-2020-50 | refinedweb | 128 | 58.08 |
Today, we have 'n' number of IDEs that convert the routine task of writing thousands of lines of code into a meaningful process. IDEs are smart, productive tools that increase the efficiency of developers. Moreover, they are a combination of editor, compiler, and debugger; intelligent enough to identify and auto complete syntax and typical keywords. Hence, Code::Blocks is too leveraging with a smart IDE. It is an open source, free programming language especially designed for C, C++, and FORTRAN. The first stable version 8.02 of Code::Blocks was in 2008. It supports a variety of compilers, including Microsoft C++, Borland, Intel C++, and GCC. Although Code::Blocks is available on the Linux and MAC platforms, this article deals with Code::Blocks for the Windows platform.
Installation
As said earlier, Code::Blocks is an open source programming language. Hence, its binaries for Windows, Linux, and Mac platform can be downloaded freely from its official website,. Identifying the correct package is the first essential task, because there are couple distinct packages available, leveraging dispersed features for both Windows and Linux platforms.
Figure 1: Choosing an installation package
Once you have downloaded the correct package, its installation is quite easy on Windows. It installs like any other typical software. Finally, the Code::Blocks development environments startup window looks like Figure 2.
Figure 2: Code::Blocks IDE's First view
Code::Blocks in Action
After you are done with installation and subsequent configuration, it's time to start coding. You will observe a screen appears right after imitating this software, like in Figure 2, that enables you to create a new project and other functionalities.
To start a new project, click 'Create New Project' on the screen. Here, you will encounter with a huge list of predefined project templates, as in Figure 3. Go ahead and select "Console Application;" this will allow you to write a program for the console.
Figure 3: Step 1, selecting a project template
The other application templates in Figure 3 are for developing more advanced types of applications. After selecting Console Application, click the Go button to begin using the Console Application Wizard. Henceforth, the wizard will ask to choose the programming language between C and C++ for coding like as mentioned in Figure 4.
Figure 4: Step 2, selecting a coding language
The wizard will also prompt you to specify the project name along with its directory location to store and select the default compiler as GNU which the IDE detects automatically as in Figures 5 and 6, respectively.
Because you have chosen C++ as the programming language, there is a file called main.cpp with default "Hello Word!" code automatically generated in the solution as shown in Figure 7. At this point, you can debug and compile this code by pressing the F9 key. After compilation, if there is any error in the arbitrary code, the IDE will reflect a visual indication like other IDEs.
Figure 7: main.cpp file default code
Because the aforesaid is generated automatically, the following code sample is provided to show a more realistic experience in C++ coding with Code::Blocks. In This code, you calculate the Fahrenheit value from Centigrade.
#include <iostream> using namespace std; int main() { float c = 50; float f = (c * 9 / 5) + 30; cout << "Calculated value of F=" << f <<; return 0; }
Listing 1: Centigrade to Fahrenheit conversion code
After successfully compiling and debugging the program, it produces the calculated Fahrenheit value along with other variables, including execution time in the console window, as follows:
Output 1: Calculated value of Fahrenheit
Essential Configuration for Code::Blocks
As claimed in the earlier paragraph, Code::Block supports numerous compilers. I have choose the GNU GCC compiler in this article, so the necessary configuration settings need to be set that pertain to this compiler. This optional setting aids while the program faces some unexpected errors occurring during the execution related to the Linker, compiler, build options, and directories setting. You can fix such glitches through a dialog box that can be access through Setting | Compiler menu, as follows:
Figure 8: Compiler Settings
Moreover, if you have a project with additional existing files, go to the Project menu and select "Add files." This will bring in the files associated with your program. By clicking Add files to your project, you will bring up a window so you can browse to where your files that you wish to add are. Select any additional file you want to add and press Open. The file will then be added to your project.
You also can use build options to ensure that Debug is running. You can use the Project pull-down menu and click Build Options. Here, make sure that the Produce debugging symbols [-g] is checked, as shown in Figure 9.
Figure 9: Debug Settings
Conclusions
This article provided an alternative approach to coding C/C++ programming under a different arena by introducing an open source IDE, Code::Blocks, which supports a wide range of renowned compilers. Although the contents in this article are Windows-centric, things are pretty similar on the inux and Mac platforms, too. I briefly touched some of the essential features of Code::Blocks that might be conducive for you and other developers in terms of improving the efficiency while coding. Moreover, Code::Blocks offers a variety of plug-in and other substantial features to support FORTRAN and assembly language.
References
-
-
-
-
About the Author
Ajay Yadav is an Author, Cyber Security Specialist, SME, Software Engineer, and System Programmer with more than eight years of work experience. He earned a Master and Bachelor Degree in Computer Science, along with numerous premier professional certifications. For several years, he has been researching Reverse Engineering, Secure Source Coding, Advance Software Debugging, Vulnerability Assessment, System Programming, and Exploit Development. He is a regular contributor to programming journals and assists the developer community with blogs, research articles, tutorials, training material, and books on sophisticated technology. His spare time activity includes tourism, movies, and meditation. He can be reached at ajay007[at]gmail[dot]com. | https://mobile.codeguru.com/cpp/cpp/programming-with-codeblocks.html | CC-MAIN-2019-18 | refinedweb | 1,009 | 52.7 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
How to configure IDE to work with OpenERP 7
I am new into pyhton and OpenERP development. I have already install OpenERP 7 and try to create some basic addon (like web_hello) but I don't have autocomplete for openerp core addons. Already on first line
from osv import osv, fields
My IDE tell me: "Unresolved reference 'osv'" nad "Unresolved reference 'fields'".
I use PyCharm 3.4, but have same problem with Eclipse PyDev.
It might be a good idea to point your IDE to the osv directory of your odoo installation (something like odoo/openerp/osv) as an external library. I never worked with PyCharm but in eclipse there is a menuitem like "Pydev - Pythonpath" under your project properties.Pointing this to the appropriate directory might help.
For development ease, it might also be a good idea to make a project of the Odoo branch, so you can easily look up any code in Odoo itself.
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/how-to-configure-ide-to-work-with-openerp-7-54041 | CC-MAIN-2017-22 | refinedweb | 212 | 64.2 |
Prev
Java Threads Experts Index
Headers
Your browser does not support iframes.
Re: Java 7 features
From:
ram@zedat.fu-berlin.de (Stefan Ram)
Newsgroups:
comp.lang.java.programmer
Date:
3 Jul 2007 21:11:14 GMT
Message-ID:
<switches-20070703230341@ram.dialup.fu-berlin.de>
Roedy Green <see_website@mindprod.com.invalid> writes:
There are two JVM instructions to implement a switch. Java's N-way
branch. In the JVM all over the map. It thus pays to keep your
switch values dense.
Still, they might be implemented by if-sequences.
As Ralf Ullrich recently quoted:
?Figure 5 shows that Java dense switches (tableswitches),
when used to implement dynamic dispatch, result in
performance very similar to that of virtual calls on the
IBM JVM, revealing an implementation based on jump tables.
In the HotSpot Client JVM however, both on Pentium III and
UltraSparc III (gures 7 and 8), tableswitch es behave
exactly like if sequences, which indicates an actual
implementation based on sequences of conditional branches.
Table switches are therefore unreliable in terms of
performance across JVMs.?
The source according to Ralf is:
?Evaluation of Control Structures for Dynamic Dispatch in Java?
I just wrote a benchmark, which showed if-sequences to be
actually faster than switches for the special case tested.
import static java.lang.System.nanoTime;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.out;
import static java.lang.System.gc;
import static java.lang.Thread.sleep;
public class Main
{ public static void main( final java.lang.String[] args )
throws java.lang.Throwable
{ int randomizer =( int )( currentTimeMillis() / 947 ); int i1; int i2;
int r0; int r1;
int s;
long d0; long d1; long d2;
long t0, t1, t2, t3, t4, t5;
out.printf
( "Benchmark running - " +
"Please minimize activity of other processes.%n" );
sleep( 3000 );
double a = 0.; double c = 0.;
out.printf
( "The columns" + "%n" +
" Identification number of the outermost iteration" + "%n" +
" Runtime of \"if\" divided by runtime of \"switch\"" + "%n" +
" Average of the preceding column" + "%n" );
for( long l = 0;; ++l )
{ r0 = 0; r1 = 0; s = 0;
d0 = 0; d1 = 0; d2 = 0;
gc();
Thread.sleep( 1000 );
final long n = 100000000L;
{ { t4 = nanoTime();
randomizer +=( int )(( t4 / 7907 )% 611953 );
for( long i = 0; i < n; ++i )
{ randomizer = randomizer * 1103515245 + 12345;
final int random =( randomizer / 65536 )% 10;
s += random; }
t5 = nanoTime();
d2 +=( t5 - t4 ); }
{ t0 = nanoTime();
for( long i = 0; i < n; ++i )
{ randomizer = randomizer * 1103515245 + 12345;
final int random =( randomizer / 65536 )% 10;
{ if( random == 0 )r0 = 20418437;
else if( random == 1 )r0 = 94704581;
else if( random == 2 )r0 = 45898144;
else if( random == 3 )r0 = 49094059;
else if( random == 4 )r0 = 77416885;
else if( random == 5 )r0 = 91322469;
else if( random == 6 )r0 = 40218964;
else if( random == 7 )r0 = 93641667;
else if( random == 8 )r0 = 29822916;
else r0 = 625909; }
s += r0; }
t1 = nanoTime();
d0 +=( t1 - t0 ); }
{ t4 = nanoTime();
for( long i = 0; i < n; ++i )
{ randomizer = randomizer * 1103515245 + 12345;
final int random =( randomizer / 65536 )% 10;
s += random; }
t5 = nanoTime();
d2 +=( t5 - t4 ); }
{ t2 = nanoTime();
for( long i = 0; i < n; ++i )
{ randomizer = randomizer * 1103515245 + 12345;
final int random =( randomizer / 65536 )% 10;
switch( random )
{ case 0: r1 = 16336774; break;
case 1: r1 = 62881795; break;
case 2: r1 = 27998504; break;
case 3: r1 = 9612956; break;
case 4: r1 = 25592297; break;
case 5: r1 = 77114095; break;
case 6: r1 = 23554325; break;
case 7: r1 = 55380051; break;
case 8: r1 = 47971513; break;
default: r1 = 41100793; }
s += r1; }
t3 = nanoTime();
d1 +=( t3 - t2 ); }}
final double q =( d0 - d2 / 2.0 )/( d1 - d2 / 2.0 );
a += q;
out.printf( "%6d; %6.02f; %6.02f%n", l, q, a /( l + 1 ), s ); }}}
/*
Benchmark running - Please minimize activity of other processes.
The columns
Identification number of the outermost iteration
Runtime of "if" divided by runtime of "switch"
Average of the preceding column
0; 0,73; 0,73
1; 0,93; 0,83
2; 0,93; 0,87
3; 0,93; 0,88
4; 0,93; 0,89
5; 0,93; 0,90
6; 0,93; 0,90
*/
Generated by PreciseInfo ™
ussi) | https://preciseinfo.org/Convert/Articles_Java/Threads_Experts/Java-Threads-Experts-070704001114.html | CC-MAIN-2022-33 | refinedweb | 667 | 62.48 |
import tensorflow as tf #
You will use the MS-COCO dataset to train our model. The dataset contains over 82,000 images, each of which has at least 5 different caption annotations. The code below downloads and extracts the dataset automatically.
Caution: large download ahead. You'll use the training set, which/'
Downloading data from 252878848/252872794 [==============================] - 7s 0us/step Downloading data from 13510574080/13510573713 [==============================] - 360) # Shuffle captions and image_names together # Set a random state train_captions, img_name_vector = shuffle(all_captions, all_img_name_vector, random_state=1) # Select,, you extract the features from the lower convolutional layer of InceptionV3 giving us a vector of shape (8, 8, 2048).
-) # you get 1 at the last axis because
->']] * target.shape[0],.1641 Epoch 1 Batch 100 Loss 1.1760 Epoch 1 Batch 200 Loss 1.0655 Epoch 1 Batch 300 Loss 0.9091 Epoch 1 Loss 1.085079 Time taken for 1 epoch 120.04596447944641 sec Epoch 2 Batch 0 Loss 0.8282 Epoch 2 Batch 100 Loss 0.8594 Epoch 2 Batch 200 Loss 0.8003 Epoch 2 Batch 300 Loss 0.7711 Epoch 2 Loss 0.814150 Time taken for 1 epoch 51.84908151626587 sec Epoch 3 Batch 0 Loss 0.7733 Epoch 3 Batch 100 Loss 0.8939 Epoch 3 Batch 200 Loss 0.7514 Epoch 3 Batch 300 Loss 0.7305 Epoch 3 Loss 0.735903 Time taken for 1 epoch 51.83467745780945 sec Epoch 4 Batch 0 Loss 0.7428 Epoch 4 Batch 100 Loss 0.7748 Epoch 4 Batch 200 Loss 0.7225 Epoch 4 Batch 300 Loss 0.7492 Epoch 4 Loss 0.688446 Time taken for 1 epoch 51.909361839294434 sec Epoch 5 Batch 0 Loss 0.7036 Epoch 5 Batch 100 Loss 0.6540 Epoch 5 Batch 200 Loss 0.6554 Epoch 5 Batch 300 Loss 0.6292 Epoch 5 Loss 0.650351 Time taken for 1 epoch 52.05428624153137 sec Epoch 6 Batch 0 Loss 0.6319 Epoch 6 Batch 100 Loss 0.6352 Epoch 6 Batch 200 Loss 0.5756 Epoch 6 Batch 300 Loss 0.6273 Epoch 6 Loss 0.616435 Time taken for 1 epoch 52.29492521286011 sec Epoch 7 Batch 0 Loss 0.5761 Epoch 7 Batch 100 Loss 0.5931 Epoch 7 Batch 200 Loss 0.5976 Epoch 7 Batch 300 Loss 0.5833 Epoch 7 Loss 0.585671 Time taken for 1 epoch 52.13192534446716 sec Epoch 8 Batch 0 Loss 0.5342 Epoch 8 Batch 100 Loss 0.5098 Epoch 8 Batch 200 Loss 0.5168 Epoch 8 Batch 300 Loss 0.5163 Epoch 8 Loss 0.553834 Time taken for 1 epoch 52.0756254196167 sec Epoch 9 Batch 0 Loss 0.5078 Epoch 9 Batch 100 Loss 0.5242 Epoch 9 Batch 200 Loss 0.4885 Epoch 9 Batch 300 Loss 0.5613 Epoch 9 Loss 0.524567 Time taken for 1 epoch 52.11587595939636 sec Epoch 10 Batch 0 Loss 0.5245 Epoch 10 Batch 100 Loss 0.4967 Epoch 10 Batch 200 Loss 0.4655 Epoch 10 Batch 300 Loss 0.4935 Epoch 10 Loss 0.493873 Time taken for 1 epoch 51.99848747253418 sec Epoch 11 Batch 0 Loss 0.4759 Epoch 11 Batch 100 Loss 0.4637 Epoch 11 Batch 200 Loss 0.4303 Epoch 11 Batch 300 Loss 0.4456 Epoch 11 Loss 0.464059 Time taken for 1 epoch 52.14967370033264 sec Epoch 12 Batch 0 Loss 0.4271 Epoch 12 Batch 100 Loss 0.4675 Epoch 12 Batch 200 Loss 0.3673 Epoch 12 Batch 300 Loss 0.4140 Epoch 12 Loss 0.434737 Time taken for 1 epoch 51.999250411987305 sec Epoch 13 Batch 0 Loss 0.4442 Epoch 13 Batch 100 Loss 0.4010 Epoch 13 Batch 200 Loss 0.3925 Epoch 13 Batch 300 Loss 0.4209 Epoch 13 Loss 0.407342 Time taken for 1 epoch 51.98107647895813 sec Epoch 14 Batch 0 Loss 0.3860 Epoch 14 Batch 100 Loss 0.3648 Epoch 14 Batch 200 Loss 0.3829 Epoch 14 Batch 300 Loss 0.3649 Epoch 14 Loss 0.380663 Time taken for 1 epoch 51.98867869377136 sec Epoch 15 Batch 0 Loss 0.4159 Epoch 15 Batch 100 Loss 0.3212 Epoch 15 Batch 200 Loss 0.3454 Epoch 15 Batch 300 Loss 0.3550 Epoch 15 Loss 0.354879 Time taken for 1 epoch 52.12524914741516 sec Epoch 16 Batch 0 Loss 0.3108 Epoch 16 Batch 100 Loss 0.3196 Epoch 16 Batch 200 Loss 0.2848 Epoch 16 Batch 300 Loss 0.3415 Epoch 16 Loss 0.333778 Time taken for 1 epoch 52.17926502227783 sec Epoch 17 Batch 0 Loss 0.3377 Epoch 17 Batch 100 Loss 0.3221 Epoch 17 Batch 200 Loss 0.3216 Epoch 17 Batch 300 Loss 0.2901 Epoch 17 Loss 0.312425 Time taken for 1 epoch 52.19093203544617 sec Epoch 18 Batch 0 Loss 0.3126 Epoch 18 Batch 100 Loss 0.3082 Epoch 18 Batch 200 Loss 0.2854 Epoch 18 Batch 300 Loss 0.2873 Epoch 18 Loss 0.289537 Time taken for 1 epoch 52.18620252609253 sec Epoch 19 Batch 0 Loss 0.3103 Epoch 19 Batch 100 Loss 0.2924 Epoch 19 Batch 200 Loss 0.2763 Epoch 19 Batch 300 Loss 0.2955 Epoch 19 Loss 0.271896 Time taken for 1 epoch 52.26207423210144 sec Epoch 20 Batch 0 Loss 0.2885 Epoch 20 Batch 100 Loss 0.2319 Epoch 20 Batch 200 Loss 0.2464 Epoch 20 Batch 300 Loss 0.2514 Epoch 20 Loss 0.254451 Time taken for 1 epoch 52.17351746559143 sec
plt.plot(loss_plot) plt.xlabel('Epochs') plt.ylabel('Loss') plt.title('Loss Plot') plt.show()
Caption!
- The evaluate function is similar to the training loop, except.random.categorical(predictions, 1)[0])
Real Caption: <start> a window display of some assorted travel bags <end> Prediction Caption: a wedding cake that looks like stacked luggage <end>
>>IMAGE)
Downloading data from 65536/64400 [==============================] - 0s 3us/step Prediction Caption: a man that is riding a surfboard in the water . | https://www.tensorflow.org/tutorials/text/image_captioning?hl=es | CC-MAIN-2019-51 | refinedweb | 1,003 | 98.51 |
Interested in Paris?
We'll send you updates with the latest deals, reviews and articles for Paris each week.
You may also be interested in these hotels within five miles of Paris:
Topics include Dining Scene, France: For Foreign Visitors & more!
TAXIS
Note: Licensed taxis have a sign saying “Taxis parisiens” on them. If you are arranging scheduled transportation, make sure to verify that the company you are dealing with has the proper credentials.
It’s not easy to find a taxi in Paris. Nothing like the yellow cabs in New York City! You are more likely to find them at taxi stands or on large avenues than on small dark street.
Taxis don’t have a common color or type, you’ll recognize them by the taxi sign on top of the car. If it’s lit up, it means that it’s available whereas if the sign is not lit up, it is occupied. There are several taxi companies that you can call: Paris Taxi, Les taxis bleus, Taxis G7… All taxis apply the same rates, which vary according to the time range and the day of the week. There is a starting charge of 2 euros and a minimum fare of 5.20 euros. You don’t have to tip taxi drivers
Main Paris taxi services:
Paris Taxi :
City Cab Paris :
Les taxis bleus:
Taxis G7 :
Royal Cab :
Taxis 75 :
Paris Airport Shuttle:
Paris Taxi:
RENT A CAR: However, renting a car is also really not a good idea in Paris. It is very tough parking in the city and if you find a parking spot, not being a resident, it will cost you a lot. Besides, Paris is a very busy city and you will get nuts in the traffic! Also, the City of Paris has been trying to encourage the use of public transportation for environmental reasons, so they have set up bus lanes almost everywhere which has made the traffic even heavier in the last few years. A car could only be useful if you plan to go around Paris, in places that are nor reachable by train.
You will find car rentals (Avis, Hertz, Rent a Car, Budget, Ada…) in every train station or at the airports. Prices vary from 85 euros (Hertz) to 230 euros (Holidays Auto) for a week-end.
Rental vehicle return
If you intend to drop-off your rental vehicle in Paris, allow a couple of hours driving time just to drive from the outskirts and into the city. The extra day charge for late return (Europcar defines this as being more than 29 minutes late) is over 100 Euros after the processing fee and tax are added.
Van drivers should avoid Gare de l'Est train station for vehicle drop off. When driving to the bottom of five basement levels, the top rear of an unloaded van may scrape the ceiling in the lower levels. If at all possible, insist on returning the van at basement level one where the hire offices are located at this station.
Useful
Useful to visit the rental car brokers, as the deals of major ( THRIFTY, AVIS, EUROPCAR, BUDGET, HERTZ, SIXT, NATIONAL, ALAMO ) and local car rental companies (suppliers) can be compared in one site. They offer online booking possibility, live support and 24 hour hotline. | http://www.tripadvisor.com/Travel-g187147-s304/Paris:France:Taxis.And.Rental.Cars.html | CC-MAIN-2014-52 | refinedweb | 553 | 75.74 |
.11 through 3.0: Since version 1.9, Django
pip install jsonfield
Usage
from django.db import models from jsonfield import JSONField class MyModel(models.Model): json = JSONField()
Advanced Usage
By default python deserializes json into dict objects. This behavior differs from the standard json behavior because python dicts do not have ordered keys.
To overcome this limitation and keep the sort order of OrderedDict keys the deserialisation can be adjusted on model initialisation:
import collections class MyModel(models.Model): json = JSONField(load_kwargs={'object_pairs_hook': collections.OrderedDict})
Other Fields
jsonfield.JSONCharField
If you need to use your JSON field in an index or other constraint, you can use JSONCharField which subclasses CharField instead of TextField. You’ll also need to specify a max_length parameter if you use this field.
Compatibility
django-jsonfield aims to support the same versions of Django currently maintained by the main Django project. See Django supported versions, currently:
- Django 1.11 (LTS) with Python 2.7, 3.5, or 3.6
- Django 2.2 (LTS) with Python 3.6, 3.7, or 3.8
- Django 3.0 with Python 3.6, 3.7, or 3.8
Testing django-jsonfield Locally
To test against all supported versions of Django:
$ docker-compose build && docker-compose up
Or just one version (for example Django 3.0 on Python 3.8):
$ docker-compose build && docker-compose run tox tox -e py38-dj30
Web:
Twitter: @bradjasper
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/jsonfield-joinup/ | CC-MAIN-2021-39 | refinedweb | 263 | 53.68 |
0
Ok, I know C/C++ really well, but just started Java today and am having an issue. I have an assignment where I have to ask the user how many names he wants to enter, and then have him enter all of the names. After all of the names have been entered, they have to be printed back out. I am not worried about the printing part, but I am worried about how to store all of these names. So far I have,
import java.io.*; public class Problem2 { private static BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) ); public static void main(String[] arguments) throws IOException { System.out.println("Welcome. How many names do you wish to enter?"); String input = stdin.readLine(); int nameCount = Integer.parseInt(input); for(int i = 0; i < nameCount; i++) { System.out.print("Enter name: "); //NEED HELP HERE } } }
Thanks for any help you can provide! | https://www.daniweb.com/programming/software-development/threads/110219/array-of-strings | CC-MAIN-2017-09 | refinedweb | 151 | 68.36 |
Type checking Python 2 code¶
For code that needs to be Python 2.7 compatible, function type annotations are given in comments, since the function annotation syntax was introduced in Python 3. The comment-based syntax is specified in PEP 484.
Run mypy in Python 2 mode by using the
--py2 option:
$ mypy --py2 program.py
To run your program, you must have the
typing module in your
Python 2 module search path. Use
pip install typing to install the
module. This also works for Python 3 versions prior to 3.5 that don’t
include
typing in the standard library.
The example below illustrates the Python 2 function type annotation syntax. This syntax is also valid in Python 3 mode:
from typing import List def hello(): # type: () -> None print 'hello' class Example: def method(self, lst, opt=0, *args, **kwargs): # type: (List[str], int, *str, **bool) -> int """Docstring comes after type comment.""" ...
It’s worth going through these details carefully to avoid surprises:
- You don’t provide an annotation for the
self/
clsvariable of methods.
- Docstring always comes after the type comment.
- For
*argsand
**kwargsthe type should be prefixed with
*or
**, respectively (except when using the multi-line annotation syntax described below). Again, the above example illustrates this.
- Things like
Anymust be imported from
typing, even if they are only used in comments.
- In Python 2 mode
stris implicitly promoted to
unicode, similar to how
intis compatible with
float. This is unlike
bytesand
strin Python 3, which are incompatible.
bytesin Python 2 is equivalent to
str. (This might change in the future.)
Multi-line Python 2 function annotations¶
Mypy also supports a multi-line comment annotation syntax. You can provide a separate annotation for each argument using the variable annotation syntax. When using the single-line annotation syntax described above, functions with long argument lists tend to result in overly long type comments and it’s often tricky to see which argument type corresponds to which argument. The alternative, multi-line annotation syntax makes long annotations easier to read and write.
Here is an example (from PEP 484):
def send_email(address, # type: Union[str, List[str]] sender, # type: str cc, # type: Optional[List[str]] bcc, # type: Optional[List[str]] subject='', body=None # type: List[str] ): # type: (...) -> bool """Send an email message. Return True if successful.""" <code>
You write a separate annotation for each function argument on the same
line as the argument. Each annotation must be on a separate line. If
you leave out an annotation for an argument, it defaults to
Any. You provide a return type annotation in the body of the
function using the form
# type: (...) -> rt, where
rt is the
return type. Note that the return type annotation contains literal
three dots.
Note that when using multi-line comments, you do not need to prefix the
types of your
*arg and
**kwarg parameters with
* or
**.
For example, here is how you would annotate the first example using
multi-line comments.
from typing import List class Example: def method(self, lst, # type: List[str] opt=0, # type: int *args, # type: str **kwargs # type: bool ): # type: (...) -> int """Docstring comes after type comment.""" ...
Additional notes¶
- You should include types for arguments with default values in the annotation. The
optargument of
methodin the example at the beginning of this section is an example of this.
- The annotation can be on the same line as the function header or on the following line.
- The type syntax for variables is the same as for Python 3.
- You don’t need to use string literal escapes for forward references within comments.
- Mypy uses a separate set of library stub files in typeshed for Python 2. Library support may vary between Python 2 and Python 3. | http://mypy.readthedocs.io/en/stable/python2.html | CC-MAIN-2017-26 | refinedweb | 623 | 65.93 |
On 16 September 2013 00:46, Andrea Pescetti <pescetti@apache.org> wrote:
> On 15/09/2013 janI wrote:
>
> On 15 September 2013 00:49, janI wrote:
>>
>>> Please correct me, but fedora 19 is not part of our product release ? my
>>> aim is to support what AOO supports.
>>>
>>
> It is a standard Linux system, and OpenOffice should build and run on all
> recent Linux systems. For sure it would be a bug (unrelated to this
> discussion) if our official RPM packages did not run on it.
>
But I don't believe we have "supported" and "unsupported" Linux systems, as
> in general any recent system with standard system tools will work. However,
> I perfectly understand that you must start with something, and starting
> with what the buildbots use is indeed the most reasonable choice. Then, if
> adaptations are needed, we can find the patterns and apply them.
>
>
OK, I simply dont have experience with fedora. I run with ubuntu 12.04, and
the comilers etc. that come with that. I build trunk several times a week
without problems, and of course also l10n40.
But anyhow it must work on other platforms as well.
>
> my configure options are taken from our buildbot:
>>>
>>
> It breaks the same way on my system. I explicitly tried with both
> --with-stlport and --without-stlport since the default here depends on
> whether you build on a 32 bit or 64 bit system.
>
>
> I need to support vc 6.0 since our
>>> buildbot uses that (even though its very outdated). Funny things here is
>>> that VC 6.0 adn 2012 are imcompatible.
>>>
>>
> This is something we can discuss. Supporting an obsolete compiler by being
> incompatible with a newer one is understandable only if there are
> advantages. I believe that other developers encountered this problem
> already; they will be able to give better advice.
The problem I had with VC6 was not access() as I thought, it was the std
namespace and a couple of class constructs I use.
It would be nice if we in general "upped" our compilers to the state of art.
>
>
> function "access" is normally defined in sys/stat.h on linux. You need to
>> see in which include file access is defined on your system, and either add
>> an #ifdef for your system, or extend the include files.
>>
>
> Thanks for investigating. As for the patch, I already included earlier in
> this thread.
>
I have now added a #include <unistd.h>, it seems ubuntu 12.04 includes that
through another file.
>
> Then the build breaks in another file due to a conversion that my gcc does
> not support/admit, but this should be quite unrelated...
Now I have removed all warnings, so this is now one of the few modules
without warnings (actually that would be a good task for a new developer).
R1523556 compiles without warnings on ubuntu 12.04 and windows7 (VC2012).
rgds
jan I.
@ariel wrote:
You should try to avoid all that system calls, the URE libraries have
a system abstraction layer to write portable code; vid.
This would not be a good idea, the tool is specifically written so it is
indendent of all AOO libraries, thereby it can be placed anywhere in the
build stream. Using the URE libraries will as far as I can see add quite a
lot of dependencies.
>
>
> Regards,
> Andrea.
>
> ------------------------------**------------------------------**---------
> To unsubscribe, e-mail: dev-unsubscribe@openoffice.**apache.org<dev-unsubscribe@openoffice.apache.org>
> For additional commands, e-mail: dev-help@openoffice.apache.org
>
> | http://mail-archives.apache.org/mod_mbox/openoffice-dev/201309.mbox/%3CCAK2iWdSUBb7SLtveCxXbs3DgO4oZmygjUwJGPb1s6MoviD8Sog@mail.gmail.com%3E | CC-MAIN-2018-17 | refinedweb | 578 | 67.04 |
import "github.com/grailbio/bigslice/internal/slicecache"
type Cacheable interface { Cache() ShardCache }
Cacheable indicates a slice's data should be cached.
FileShardCache is a ShardCache backed by files. A nil *FileShardCache has no cached data.
NewShardCache constructs a ShardCache. It does O(numShards) parallelized file operations to look up what's present in the cache.
func (c *FileShardCache) CacheReader(shard int) sliceio.Reader
CacheReader returns a reader that reads from the cache. If the shard is not cached, returns a reader that will always return an error.
func (c *FileShardCache) IsCached(shard int) bool
func (c *FileShardCache) RequireAllCached()
WritethroughReader returns a reader that populates the cache. reader should read computed data.
type ShardCache interface { IsCached(shard int) bool WritethroughReader(shard int, reader sliceio.Reader) sliceio.Reader CacheReader(shard int) sliceio.Reader }
ShardCache accesses cached data for a slice's shards.
var Empty ShardCache = empty{}
Empty is an empty cache.
Package slicecache imports 9 packages (graph) and is imported by 2 packages. Updated 2020-05-29. Refresh now. Tools for package owners. | https://godoc.org/github.com/grailbio/bigslice/internal/slicecache | CC-MAIN-2020-29 | refinedweb | 171 | 53.47 |
<stdio.h>: Standard IO facilities −
Macros
#define FILE struct __file
*))
#include <stdio.h>
Introduction == ’0) ’, stream);
uart_putchar(’
Note 1:.
Note 2: == ’0) ’);
uart_putchar(’
loop_until_bit_is_set(UCSRA, UDRE);
UDR = c;
return 0;
}
Note.
#define _FDEV_EOF (-2)
Return code for an end-of-file condition during device read.
To be used in the get function of fdevopen().
#define _FDEV_ERR (-1)
Return code for an error condition during device read.
FILE struct __file
FILE is the opaque structure that is passed around between the various standard IO functions.
.
void clearerr (FILE *__stream)
Clear the error and end-of-file flags of stream.
int).
FILE* fdevopen (int(*)(char, FILE *)put, int(*)(FILE *)get)
This..
int sscanf_P (const char *__buf, const char *__fmt, ...)
Variant of sscanf() using a fmt string in program memory.
int.
int:
• ‘0x’ (or ‘0:
-Wl,-u,vfprintf -lprintf_min
If the full functionality including the floating point conversions is required, the following options should be used:
-Wl,-u,vfprintf -lprintf_flt -lm
Limitations:
The specified width and precision can be at most 255.
Notes:.
int vfprintf_P (FILE *__stream, const char *__fmt, va_list__ap)
Variant of vfprintf() that uses a fmt string that resides in program memory.
int vfscanf (FILE *stream, const char *fmt, va_listap), of everything except close bracket, zero through nine, and hyphen. The string ends with the appearance of a character not in the (or, with a circumflex, in) set or when the field width runs out. Note that usage of this conversion enlarges the stack expense.
p Matches a pointer value (as printed by p in:
-Wl,-u,vfscanf -lscanf_flt -lmap)ap)
Variant of vsnprintf() that uses a fmt string that resides in program memory.
int vsprintf (char *__s, const char *__fmt, va_listap)
Like sprintf() but takes a variable argument list for the arguments.
int vsprintf_P (char *__s, const char *__fmt, va_listap)
Variant of vsprintf() that uses a fmt string that resides in program memory.
Generated automatically by Doxygen for avr-libc from the source code. | http://man.sourcentral.org/ubuntu1310/3+printf | CC-MAIN-2018-09 | refinedweb | 324 | 64.3 |
Pitrov Secondary5,119 Points
I made this game differently, is my code ok?
I made this game, It works fine, but Kenneth made the game differently. is my code OK, or how could I make it better? Here's my code: unpacking_list(list): ') move = move.upper() if move == 'QUIT': break if any(move in s for s in get_moves(player)): player = move_player(player, move) player = [tuple(player)] else: print('\n\nError. It may be that you went out of the grid, or you wrote wrong\n') if player == door: winstreak += 1 print('GJ you won! How big winstreak can you get\nWinstreak: {}'.format(winstreak)) player = None start_message continue if player == monster: winstreak += 0 print('Nooo, you met the monster. You lost, your winstreak stopped, but keep trying!\nWinsteak: 0') player = None start_message continue
it's long, so it's maybe easier if you copy it over to your text editor.
6 Answers
Pedro Cabral22,426 Points
Few observations from my side:
1. Your method unpack_list(list) is redundant as you can do the same with * for example write the following and see the results:
print(*["a","b","c"])
- Avoid using reserved keywords as function arguments such as list.
2. This line print('. . . . .\n. . . . .\n. . . . . \n. . . . . \n. . . . .\n\n\n\n\n\n\n\n\n\n\n\n') would me more readable if you would use a string literal/triple-quotes:
print( """. . . . . . . . . . . . . . . . . . . . . . . . .""")
3. Python is a very human-readable language, in my opinion comments like this:
#start of loop ===============================
just clutter the code, anyone reading
while True
will understand that that's the start of a loop.
4. Your winning streak logic is faulty, if I win 2 times straight, fail 1 and then win 1, my winning streak should be 2 but it shows as 3. So at the moment is showing how many times I have won instead of the biggest streak.
5. This does nothing.
winstreak += 0
It's the same as winstreak = winstreak + 0, so you are setting the variable value to the value that it already holds. After that you follow it with the following line:
print('Nooo, you met the monster. You lost, your winstreak stopped, but keep trying!\nWinsteak: 0')
Which is also not true, if the winstreak is 2, the print will "lie" saying it's zero when it's not. For accurate information use the value that the variable holds instead of trying to guess as you might run into bugs such as this.
6. Finally you have a few typos.
Jeff MudayTreehouse Moderator 23,580 Points
Pedro Cabral has some excellent suggestions.
I like your code-- that you took the time to show it is a great step! Keep up the good work and maybe starting posting your code to GitHub.
Pedro and I would probably agree that on comments: never sacrifice clarity for brevity. I thought it was appropriate to comment where your main program loop was-- get in the habit of planning, commenting, and refactoring. At some point you'll be presenting a GitHub or Bitbucket portfolio to a potential employer; thoughtful descriptions/comments in your README and in-code notes may become interview topics.
Here's a pretty funny/true article (while it's about PHP, it might as well be about any other language):
Jeff MudayTreehouse Moderator 23,580 Points
Github and Bitbucket are repositories and can be used as a code versioning system. And now, Github in particular, can be used as a website for code (there is a trend to use Github site as part of an aspiring developer's portfolio and sometimes as an entire resume website). Treehouse has instruction on Github-- I recommend you take it!
One cool Github feature is you can "follow" a developer. That is, you can get notifications of some of their high-level Github actions/activities.
Here is Kenneth Love's site:
In essence, a developer will put their code up there to show/share with others and sometimes work on a team project (I contribute to several projects). More than that, Github can be used during the development process to maintain consistent versioning among team members. Github also will allow an individual to "fork" code of others. By "fork", we mean one can copy an entire project and begin a new branch of the code to improve or change it while leaving the original code version unchanged.
Bitbucket is similar to Github, it is not as full-featured, but the advantage of Bitbucket is you can keep your code private (for free). With Github you have to pay to keep your code secret. I hide quite a bit of my code that I write because it was written for my employers or side projects and wasn't intended to be in the public domain.
Pitrov Secondary5,119 Points
Thank you, Pedro Cabral and Jeff Muday. You taught me much, I didn't know that I could unpack lists with a *, and I will start using comments better.
I've heard about GitHub, but I've never tried it. How does Github work? Do people just help me with my code?
<noob />16,678 Points
Hi, can u explain what this line of code do?
f player_position[0][1] == 0: del moves[2] if player_position[0][1] == 4: del moves[3] if player_position[0][0] == 4: del moves[1] if player_position[0][0] == 0: del moves[0] return moves
how exactly ur accessing the cells? how u determine which direction is it?
Jeff MudayTreehouse Moderator 23,580 Points
dskellth theSmartGuy is the programmer of this version, so with luck he will respond to you! Being able to explain your code to others really is a good step toward mastery of Python.
Pitrov Secondary5,119 Points
noob developer. First, of, I am sorry that my code is white, I don't know how to make it with colors. My function get_moves(player_position) checks all the possible directions my player can go. It takes the position of my player as a parameter, which is 'player'. 'Player' is a list of a tuple like [(1, 0)] for example. In the first line, I checked if player_position[0][1] is equal to 0. player_position[0][1] is just the first list and the second item in the tuple. if it is 0 like it is in the example, then I can't go up, so I delete the 3rd item in the list 'moves'. which has an index of 2. then I check if playerposition[0][1] is 4. if it was then I couldn't go down. I would have had to delete the 4th item in the list 'moves', which has the index of 3. Then I do the same to the first item in the tuple. Lastly, I return moves, which now contains moves that the player can go, so that he doesn't fall out of the map.
I hope you understand what I am talking about.
def get_moves(player_position): moves = ['LEFT', 'RIGHT', 'UP', 'DOWN',] if player_position[0][1] == 0: del moves[2] if player_position[0][1] == 4: del moves[3] if player_position[0][0] == 4: del moves[1] if player_position[0][0] == 0: del moves[0] return moves
Jeff MudayTreehouse Moderator 23,580 Points
To make your code syntax colored, use three backticks the word python and then end code segment with three backticks. Keep up the good work!
def get_moves(player_position): moves = ['LEFT', 'RIGHT', 'UP', 'DOWN',] if player_position[0][1] == 0: del moves[2] if player_position[0][1] == 4: del moves[3] if player_position[0][0] == 4: del moves[1] if player_position[0][0] == 0: del moves[0] return moves
Pitrov Secondary5,119 Points
Pitrov Secondary5,119 Points
Thanks for the comment Jeff Muday, I maybe watch through the Github course. | https://teamtreehouse.com/community/i-made-this-game-differently-is-my-code-ok | CC-MAIN-2019-51 | refinedweb | 1,296 | 71.34 |
ok let me put the codes first because I might be stating everything as bizarre as i see it
Code :
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; public class DoubleCallToRepaintWithNimbusPLAFBizzareProblem { private java.util.List<String> words; private boolean stopSlide; private int wordX; private int head; private int tail; private JButton slide; public DoubleCallToRepaintWithNimbusPLAFBizzareProblem() { words = new ArrayList<String>(); initWordList(); tail = words.size() - 1; stopSlide = true; } public void initWordList() { words.add("F I R S T S L I D E"); words.add("S E C O N D S L I D E"); words.add("T H I R D S L I D E"); words.add("F O U R T H S L I D E"); } public void showWindow() { Panel p = new Panel(); JFrame f = new JFrame(); slide = new JButton("Slide"); slide.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopSlide = false; slide.setEnabled(false); } }); p.add(slide); p.setPreferredSize(new Dimension(700, 450)); f.getContentPane().add(p); f.pack(); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setResizable(false); f.setVisible(true); } private class Panel extends JPanel implements Runnable { private Thread runner; private boolean stopThread; public Panel() { runner = new Thread(this); runner.start(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setFont(new Font("Monospaced", Font.BOLD, 35)); g2d.drawString(words.get(head), wordX, 220); g2d.drawString(words.get(tail), wordX + 900, 220); } @Override public void run() { while (!stopThread) { try { Thread.sleep(5); if (!stopSlide) { if (wordX >= -900) { wordX -= 5; } if (wordX < -900 && !stopSlide) { wordX = 0; head = tail; tail--; stopSlide = true; // set enabled again, and i see in the API // there is a call to repaint() inside of it slide.setEnabled(true); // when tail becomes negative 1, // make it the size() - 1 of the list // imediately before the repaint() call below if (tail < 0) { tail = words.size() - 1; } } } repaint(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } } } } public static void main(String[] args) { try { for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } new DoubleCallToRepaintWithNimbusPLAFBizzareProblem().showWindow(); } }
i tried to reproduce the thing i encoutered as small as possible , so this is a far as it goes.
- when i do a slide, the int values(head and tail) that calls the values in the word lists, decrements from size() - 1 to 0,
- when it reaches the critical point -1 (tail variable), inside the run method, i have an if part that turns the tail into a positive value that i want immediately before the call to repaint() below it, so i will be able to avoid a -1 out of bounds exception.
- why do i get a -1 exception?
- i tried to debug it for a couple of hours then i pin-point the problem(first assessment)
FIRST ASSESSMENT:
- every time I slide, I disable the slide button when a sliding is occuring, for every succesfull slide animations, i enable the slide button again, as you can see, i put that setEnabled(true) call inside the run() method, JUST BEFORE the if-part that turns the tail variable to something positive before a repainting again, repaint()
- from there i manage to see that there is another repaint() call inside the JComponent setEnabled() method - I dig in
- and from there i realize that when i have a -1 tail, that setEnabled() call calls a repaint() inside of it that repaints everything, and i thought that it might affect the other painting events(my sliding words), thats why i get a -1 outOfBounds(ONCE. only ONCE) it proceeds on the if-part that sets the tail a positive value(not a -1), then proceed to my own painting(the repaint() below of it) and good to go again.
- what i did is i placed the call to .setEnabled() (slide.setEnabled(true)) below the if-part that sets the tail to something positive value, and everything works fine, thats why i am, somehow confident with my understanding that there is a 2 call to repaint() that affects everything. one is inside the setEnabled() of JComponent and the other one is that i have
- now i tried to reproduce again the problem WITHOUT THE NIMBUS PLAF INSTALLATION, and everything i said above doesnt happen
- now the second assesment goes
SECOND ASSESSMENT:
- lets go back to square 1, all those things i said above, removing the installed NIMBUS PLAF, no error has occured
what is going on?, i might be wrong on something(maybe all) and i admit that Im doing a concurrency in an appropriate way. But please.. i need some assitance. Is using Nimbus plaf or installing another PLAF is risky? or calling a swing instance method with a repaint() inside of it in a run method with another repaint() is dangerous? , please ask me if my statements are hard to understand. ill try to explain as more clearly as possible. thank you in advance | http://www.javaprogrammingforums.com/%20awt-java-swing/17155-nimbus-plaf-double-call-repaint-inside-runnable-interface-printingthethread.html | CC-MAIN-2014-49 | refinedweb | 844 | 54.63 |
Maps that are hash tables are normally implemented
using a hash function which maps a data item (the key) into
an indexing table. The hash function takes the key and uses some
algorithm to convert it to an index value into an array. For example,
the hash function from the Java SDK
HashMap class:
int index = (key.hashCode() & 0x7FFFFFFF) % table.length;
This hash function extracts some bits from the hashcode of the key
object (to quickly convert the hashcode to some positive number), and
then uses the remainder, after division by the table length, to get an
index that fits into the
HashMap internal array. A hash
function cannot generally guarantee every data item maps to a
different index, so the structure of a hash table is complicated by
needing to maintain a list at every index, allowing multiple objects
to be held at any index. Having multiple objects at the same index is
inefficient since the collection at that index must be searched every
time an element from that collection is required.
A perfect hash function is one that maps every key to a
different index.
Map implementations with perfect hash
functions are much simpler than using generic hash functions; they
consist of two arrays, one for the keys and one to hold all
corresponding values. The array elements do not need to hold
collections since only one object is ever located at each index,
making processing easier and faster. (Note that the hash function does
not have to map a key into every index, i.e. some indexes can be
empty. A hash function which maps each key to a unique index
and leaves no empty entries in the table is called a
minimal perfect hash function). But how can you get a perfect
hash function?
Recently I came across an interesting performance problem. The
application used a number of objects, which were at core
Maps with known key objects (not
Strings). There were several kinds of
Maps,
and each kind was allowed to contain only one specific set of key
objects. For example, suppose the key objects were defined simply
as
public class Key { int id; public Key(int id) {this.id = id;} }
Then the first kind of
Map might be allowed to have
keys with ids of 5, 10, 11, and 27, while another kind of
Map must contain only keys with ids 10, 11 and 15,
etc. There could be multiple instances of each kind of map, but every
instance could only contain its defined keys.
In this application these
Map objects were accessed
and updated often. The key lookup needed to be as fast as
possible. Note the information we have about the
Map
data: the key set was restricted and known before construction for
every
Map, and the keys had associated numerical values
which were unique to each key. Because the key data was restricted and
known, my first thought was that the these
Maps were
ideal for optimization using perfect hash functions.
Creating optimized classes for these
Maps is
straightforward except for the hash function. To keep the code clear
and optimized for
Key object keys, I won't implement the
Map interface precisely -- converting the following class
to a standard implementation of
Map is easy enough.
public class PerfectKeyHashMap { Key[] keys; Object[] values; public void put(Key key, Object value) { //The following line is the currently unknown hash function int index = someHashFunctionOn(key); keys[index] = key; values[index] = values; } public Object get(Key key) { //The following line is the currently unknown hash function int index = someHashFunctionOn(key); //keys assumed to be entered on map creation with null values. //no validation done on key, but if needed, that could be //if(keys[index].id != key.id) throw new Exception //("invalid key"); return values[index]; } ... }
Now how do we get our perfect hash function? We want it to be quick
so we should use as few simple operations as possible. The
HashMap function manipulates bits and uses the remainder
operator. Remainder looks like it could be quite a useful operation
for our hash function. It will help map arbitrary numbers into a small
table, and it can be used with a variable argument. So let's try
it.
We have a known maximum number of keys in the hashtable. We also know that we want each of those keys to map to a different index. So clearly our remainder operator argument must be a number greater than or equal to the number of keys we have. Let's try out some tests to get a feel for the data. Using some examples, including the ones we had earlier, what would work using the remainder operator? We'll start with the list of key values and apply the remainder operator to each value. Then we use the argument that starts with the size of the key set, which increments by one each time until we get a result set of unique keys (the repeated values in each column are marked with a *):
For each of these three examples, we eventually gained a set of indexes which were unique and would map to a fairly small table. This method of obtaining indexes by successively increasing the remainder argument will definitely lead to a set of unique value for any set of non-repeated keys. This is because the value of one plus the largest key in the set for the remainder operator argument is guaranteed to produce a unique set of integers. For the last example this argument would be 1112 as shown in this table:
So our perfect hash map needs an extra instance variable to hold the remainder appropriate for its set of keys. The hash function is just
int index = key.id % remainder;
What. | http://www.onlamp.com/lpt/a/563 | CC-MAIN-2014-15 | refinedweb | 962 | 59.64 |
You can subscribe to this list here.
Showing
2
results of 2
Next question.
I have a *spyce.include* inside a file that is itself *spyce-include*'d.
I've accepted the necessity of using *include.vars* to access data in my
included file (sadly... I wish they were just added to the included file's
local namespace, but oh well), but it would be nice if *include.context* was
automagically added to the context dict when including another file.
Basically, if file A includes file B which includes file C, I'd like to
access A.foo in C via *include.vars.foo*.
Or am I missing something obvious (for the umpteenth time)?
Jason Persampieri
Programmer
Boston College - Bioinformatics Dept.
I guess the core problem is that the python code (eg *execfile*) and spyce
code (eg *include.spyce*) seem to use two different working directories. If
these could be sync'ed, it would feel smoother. Obviously, this would break
too much other code to consider... ah well :)
_jason
On Dec 11, 2007 3:11 PM, Jonathan Ellis <jonathan@...> wrote:
> For most use cases it's more convenient to treat the path as a "path"
> the way the browser would interpret it. That's the only reason it works
> the way it does. If I were to revisit this for spyce 2.2 I would
> probably do it the way you suggest and just have the user use
> util.url2file if they want the docroot-relative path, but in earlier
> versions it's enough extra verbosity to import spyceUtil and do that
> that it wasn't worth it.
>
> -Jonathan
>
> On Tue, 11 Dec 2007 14:44:25 -0500, "Jason Persampieri"
> <spyce-discussion@...> said:
> > Howdy folks. Spyce newbie here.
> >
> > I have noticed an oddity in the *include.spyce* behavior.
> >
> > If the argument is a relative path - *include.spyce('../include.spy')* -
> > everything works fine.
> >
> > But if I pass an absolute path -
> > *include.spyce('/cluster/home/user/public_html/share/include.spy')
> > *- it looks like spyce prepends the spyce home directory (which in this
> > case
> > is the same as the http home) on to the path - * spyceNotFound:
> > spyceNotFound exception: could not find
> > "/common/www/html/cluster/home/user/public_html/share/include.spy"
> >
> > *While the absolute path behavior seems consistent with the
> > documentation,
> > this is incredibly odd. If I specify an absolute path, shouldn't it
> > assume
> > I'm pointing to exactly what I want?
> >
> > this whole thing is especially annoying since I need to *execfile *a
> > file
> > in the same directory (which *only* takes absolute paths seemingly) and
> > hence need to keep both a relative and absolute path reference. Piddly
> > to
> > be sure, but annoying.
> >
> > That said, Spyce is really rocking my world, and is *exactly* the right
> > solution for my project.
> >
> > Jason Persampieri
> > Programmer
> > Boston College Bioinformatics Dept.
> | http://sourceforge.net/p/spyce/mailman/spyce-users/?viewmonth=200712&viewday=12 | CC-MAIN-2016-07 | refinedweb | 465 | 68.16 |
I need to create a Point and Rectangle class for a homework assignment and I'm unsure if I have the right idea with what im trying to do. In my Point class it much have a accesor and mutator, and also a distance method which is what im haveing trouble with.
public class Point { private int x; private int y; public Point ( int x, int y ){ this.x = x; this.y = y; } public int getX(){ return x; } public int getY(){ return y; } // not sure if this will work yet public double distance ( Point otherPoint) { double dx = getX() - otherPoint.getX(); double dy = getY() - otherPoint.getY(); double dist = Math.sqrt(dx*dx + dy*dy); return dist; } }
I am given that the method must be structured as "public double distance (Point otherPoint)" but I don't fully understand how this method should work with the point objects. I will use these point methods in my Rectangle class in order create a getLength() getWidth() getPerimeter() and getArea() methods. So everything builds off of getting the Point() class working correctly. | https://www.daniweb.com/programming/software-development/threads/435408/point-and-rectangle-class | CC-MAIN-2017-09 | refinedweb | 176 | 71.55 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.