User defined axes¶
Example 20 - User labelling of axes¶
import cf
import cfplot as cfp
f=cf.read('cfplot_data/Geostropic_Adjustment.nc')[0]
cfp.con(f.subspace[9])
In the following plot the axes were labelled with the axes command before making a contour map of the data. The xticklabels and yticklabels options can be used to fine tune the axis labels.
import cf
import cfplot as cfp
import numpy as np
f=cf.read('cfplot_data/Geostropic_Adjustment.nc')[0]
cfp.con(f.subspace[9], title='test data', xticks=np.arange(5)*100000+100000,
yticks=np.arange(7)*2000+2000, xlabel='x-axis', ylabel='z-axis')


Alex Davies
Home
About
Portfolio
Alex Davies
QA Consulting Training
Scroll to see some of the amazing projects!
Project List


| 004:115 Khan | : |
And whoever contradicts and opposes the Messenger (Muhammad SAW) after the right path has been shown clearly to him, and follows other than the believers' way. We shall keep him in the path he has chosen, and burn him in Hell - what an evil destination. |
| 004:115 Maulana | : |
And whoever acts hostilely to the Messenger after guidance has become manifest to him and follows others than the way of the believers, We turn him to that to which he (himself) turns and make him enter hell; and it is an evil resort. |
| 004:115 Pickthal | : |
And whoso opposeth the messenger after the guidance (of Allah) hath been manifested unto him, and followeth other than the believer's way, We appoint for him that unto which he himself hath turned, and expose him unto hell - a hapless journey's end! |
| 004:115 Rashad | : |
As for him who opposes the messenger, after the guidance has been pointed out to him, and follows other than the believers' way, we will direct him in the direction he has chosen, and commit him to Hell; what a miserable destiny! |
| 004:115 Sarwar | : |
Whoever gives the Messenger a hard time, even after having received clear guidance, and follows a path other than that of the believers, will be left alone. We will cast him into hell, a terrible destination. |
| 004:115 Shakir | : |
And whoever acts hostilely to the Messenger after that guidance has become manifest to him, and follows other than the way of the believers, We will turn him to that to which he has (himself) turned and make him enter hell; and it is an evil resort. |
| 004:115 Sherali | : |
And whoso opposes the Messenger after guidance has become manifest to him, and follows a way other than that of the believers, WE shall let him pursue the way he is pursuing and shall cast him into Hell, and an evil destination it is. |
| 004:115 Yusufali | : |
If anyone contends with the Messenger even after guidance has been plainly conveyed to him, and follows a path other than that becoming to men of Faith, We shall leave him in the path he has chosen, and land him in Hell,- what an evil refuge! |
Concepts/Themes Covered: أركان الإسلام > التوحيد > توحيد الله تعالي > إنذار من لا يعترف بتوحيد الله تعالي بالانتقام Pillars of Islam> Islamic> Oneness of Allah>A Warning to all who do not Acknowledge his Glory Oneness that He'll take Retribution from them أركان الإسلام > التوحيد > توحيد الله تعالي > الوعد والوعيد Pillars of Islam> Islamic> Oneness of Allah> Promise and Threat أركان الإسلام > (محمد (صلى الله عليه وسلم > جزاء من يشاقق الرسول Pillars of Islam> The Blessed Muhammad(PBUH)> The Penalty of Those who Distress Him الإيمان > الغيب > النار > أصحاب النار Faith> The Unseen World> Hell-Fire>Hell Fellows
This tool uses eight English parallel translations for the Holy Quran imported from Mr. Clay Smith. You can also visit Qurany Concepts for browsing the Quran themes or topics. If you want to search the Holy Quran for keywords, please visit Qurany Keywords.


{% extends 'base.html' %} {% block content %}
Without cache, the page will need more than 1 second (1000.00ms) to load, every time.
Refresh the page to view the change.
Check the Time column in debug toolbar →
>>> time.sleep(1)
{% endblock %}


Search Me.
Search
Search Me.
Search
Check out
BootstrapBoogie.com
for more Bootstrap tips and
Bootstrap themes
.


In which color belongs to primary color
Option one is this and that—be sure to include why it's great
Option two can be something else and selecting it will deselect option one
Option two can be something else and selecting it will deselect option one
Option two can be something else and selecting it will deselect option one
Sumbit


I've had a few experiences with Salvia before this one, but none quite as powerful. I met with my friend E. at his apartment, sat on his bedroom floor, and dimmed the lights. After he had his experience, I proceeded to smoke a couple of leaves out of the hooka I brought, which I use exclusively for Salvia (I don't do pot or any other drugs anymore).
All of a sudden, the room was covered with a fractal cell/leaf like membrane which swirled and focused towards the space that we both occupied. It was like the universe focussed on us and was trying to communicate with me. I saw my friend, and he was a cricket, a friendly smiling hairy cricket. I wasn't frightened by the sight. It seemed quite normal. I looked at him and he looked at me with a big wonderful smile. Then I felt the Salvia entity contacting me. I've had this feeling before and I recognized the entity from past experiences. It has a definite female character to it and very loving and protecting (Although in my first couple of experiences, it was a bit frightening since she seemed to possess me, pull me off the floor and out of the room). I started to ask questions and she was answering me, but I do not remember either the questions or answers. Then I came back to reality.
Feeling like the experience was not quite finished, I smoked some more.  I saw some floating islands in this space and on the islands were children being taught by a motherly salvia entity. Then I realized I was on one of these islands myself and the salvia entity was teaching me, answering all my questions. I was quiet this time, just listening. Then I came back...
I was still not satisfied, there was communication but it wasn't clear. I knew there was more to be said. I smoked again and now I distinctly felt the entity taking my hand and leading me through a series of rooms. In each room I was incarnated into a different person in a different situation. They were all me, but I hadn't recognized myself. I was a college student in a dorm while somebody was knocking at my door. I was a child. I was an old man. I was an old lady. I was a young girl. It was like reality had many levels which run simultaneously and I inhabited all of them simultaneously, but was not aware of it untill this moment, and neither were my incarnations.
After the salvia dissipated I felt a tremendous sense of happiness and well being. It was the most comfortable I had felt with salvia so far. I could trust it now and it would show me wondrous things.
Experience Reports are the writings and opinions of the individual authors who submit them.
Some of the activities described are dangerous and/or illegal and none are recommended by Erowid.


Texas sees first pediatric flu death of season in unvaccinated child, 5
by Madeline FarberTexas health officials late last week reported the first pediatric flu death of the 2019-2020 season
GET PAID TO GET THE FLU: STUDY LOOKING FOR VOLUNTEERS WILLING TO GET SICK
The child, who was not identified, was a 5-year-old from the Rio Grande area, according to a Friday tweet from the Texas Department of State Health Services (DSHS). He or she had not been vaccinated against the virus, officials said.
No other information on the death was provided.
In its flu activity report released on Friday, the Texas DSHS said flu activity in the state “continues to rise and is at an above-average level.” The agency warned that young children — particularly those 6 months to 5 years of age — are especially vulnerable to the virus as well as “serious flu-related complications, including death.”
CLICK HERE TO GET THE FOX NEWS APP
The news comes after Connecticut health officials last week confirmed two flu-related deaths in two adults over the age of 65. The fatalities marked the state’s first of this year's flu season.


MemeFluent is a catalyst for people to rediscover communication through images
At our core, MemeFluent operates on imagination, inclusivity, and inspiration
We deliver engaging and hilarious conversations, ranting, and perspective to our audience
At MemeFluent, we make magic. We dream it, and pursue it together in innovating the impossible


--- layout: page status: publish published: true title: 'SAMPLE: Enumerating 16-bit Processes under WinNT' author: display_name: Tomas Restrepo login: tomasr email<EMAIL_ADDRESS>url: http://winterdom.com/ author_login: tomasr author_email<EMAIL_ADDRESS>author_url: http://winterdom.com/ wordpress_id: 1130 wordpress_url: http://winterdom.com/?page_id=1130 date: '2009-04-28 02:52:52 +0000' date_gmt: '2009-04-28 02:52:52 +0000' categories: - Uncategorized tags: [] comments: [] ---
If you've ever fooled around with the PSAPI library under
Windows NT to build a list of processes running on the system (using the
EnumProcesses() API), you probably know that you won't get the 16-bit Windows Applications that way. Instead, all you'll
get is the list of NTVDM.EXE instances on the system.
Well, there's a [relatively] simple way to get around that
limitation, but the answer is not some hidden functions on PSAPI or the
Performance Counters in the registry. The answer is to look for the Win16
debugging facilities built onto NT itself. The thing goes like this:
The WinNT NTVDM subsystem provides a set of services that allow
a Win32 process to debug 16-bit Windows applications running on the system. For
this, there's a library called VDMDBG.DLL, for which all functions are exported
through the vdmdbg.h and vdmdbg.lib files you'll find in the Platform SDK. Among
those are some calls that allow us to get the list of 16-bit processes running
under a Virtual Machine in the NT subsystem. Most of this function are
documented in VDMDbg.hlp, which comes with the SDK, with one notable exception
noted later.
Briefly, What you have to do is call the VDMEnumProcessWOW()
function, which will call a CALLBACK function in your program for every process
on the machine which are Win16 subsystems, which are usually instances of
NTVDM.EXE. On the first version of NT, there could only be one Win16 subsystem
executing on the machine, but on later releases, there can be more than one,
which provides address space separation. For each Win16 Subsystem, you have to
enumerate the 16-bit processes running inside them, which are referred to as Tasks.
For this, we can use the VDMEnumTaskWOW() call.
The problem with this function is that in the callback procedure
we only get the Thread ID in the Win16 subsystem under which the task is
running, as well as win16 handles to the process and the task. To be able to get
the filename of the running executable, you would need to call VDMModuleFirst().
The problem is that to be able to call this functions, WOWDEB.EXE needs to be
running inside the win16 subsystem that runs the application. Getting
this to work is a pain the a**, and I really couldn't do it.
However, it turned out that there was an even easier way.
There's an undocumented call that appears on vdmdbg.h, called VDMEnumTaskWOWEx()
which works just like the original, with the notable exception that the callback
also receives the module name and the full path of the executable as parameters.
To show how this is done, I built a simple, dialog based
application written in plan C. It's small, and doesn't do anything interesting
besides showing the 16-bit processes running on the system, but it does show how
to do it in a clear manner.
You can download a zipped file with the project
files (written on VC++ 6.0) from here.
And finally,
here's a snapshot of the sample's screen:


This analysis is to study the conversations on Twitter in the light of the Coronavirus epidemic. We hope to provide accessibility into the ongoing discussions and Tweets surrounding the epidemic. This is a step towards our current research on misinformation analysis to make social media platforms safe and reliable.
Follow our work on misinformation analysis and social networks! Check out our research on misinformation and the Melady Lab for more information on machine learning for social network analysis.
The USC Melady Lab focuses on machine learning for real world applications. We develop machine learning and data mining algorithms for solving problems involving data with special structure, including time series, spatiotemporal data, and relational data. We work closely with domain experts to solve challenging problems and make significant impacts in computational biology, healthcare, social media analysis, climate modeling, and business intelligence.
University of Southern California
3710 McClintock Ave
RTH 321
Los Angeles, CA 90089
krsharma at usc dot edu


Get ANDI
ANDI Drag to your bookmarks toolbar.
Runs on desktop browsers:
Installation Help |
How to Show Bookmarks Bar
Meet ANDI.
ANDI (Accessible Name & Description Inspector) is a free accessibility testing tool.
ANDI is a "favelet" or "bookmarklet" that will:
- Provide automated detection of accessibility issues
- Reveal what a screen reader should say for interactive elements (the accessible name computation)
- Give practical suggestions to improve accessibility and check 508 compliance
Installation Help
Select your browser below for details.
Chrome
To show the Bookmarks Bar in Chrome, press Ctrl + Shift + B.
To Install ANDI on Chrome using the keyboard:
- Press Ctrl + Shift + O to bring up Bookmark Manager.
- Select the kebob menu button (three vertical dots) in the top right of the Bookmark Manager to open a context menu.
- Select "Add New Bookmark".
- Name the bookmark "ANDI".
- Copy and paste the ANDI JavaScript URL:
- Press Save.
Edge
To show the Favorites Bar in Edge (Chromium), press Ctrl + Shift + B.
To Install ANDI on Edge (Chromium) using the keyboard:
- In the Edge address bar, navigate to: edge://favorites/
- Select "Add Favorite" button.
- Name the bookmark "ANDI".
- Copy and paste the ANDI JavaScript URL:
- Press Save.
Firefox
To show the Bookmarks Bar in Firefox, Press (Alt + V), select Toolbars, then "Bookmarks Toolbar".
To Install ANDI on Firefox using the keyboard:
- Right click this link Ctrl + Shift + F10: ANDI
- Select "Bookmark This Link"
Internet Explorer
To show the Favorites Bar in Internet Explorer, Press Alt + V, select Toolbars, then "Favorites Bar".
To Install ANDI on Internet Explorer using the keyboard:
- Right click this link Ctrl + Shift + F10: ANDI
- Select "Add to favorites bar"
Safari
To show the Favorites Bar in Safari, Press Command + Shift + B.
Unfortunately, Safari does not offer a simple keyboard accessible alternative to set a JavaScript favelet link as a favorite.
Launch ANDI
Launch ANDI by clicking on the favorite/bookmark labelled "ANDI" that was added to the Favorites/Bookmarks Bar in the browser's toolbar. ANDI will analyze the test page and appear on the page.
For thorough documentation of all features, visit: ANDI's User Guide.
Looking for a site to demo ANDI? Visit our demonstration page.
Benefits of ANDI
ANDI is like having an expert at your side, helping you ensure your website is meeting accessibility standards. Include ANDI in screenshots during your manual accessibility review. Use ANDI during development to help you build accessible websites.
Whether you're an accessibility expert or you're new to Section 508 compliance, ADA compliance, or WCAG standards, you should definitely check out ANDI.
Updates
No need to reinstall or upgrade. ANDI updates itself automatically.
View ANDI on GitHub to see version history.
How To Uninstall
To uninstall ANDI simply delete the favorite/bookmark that was created in installation.
Open Source on GitHub
ANDI is an open source project created by the Accessible Solutions Branch of the Social Security Administration. The source code is available for contribution on GitHub.
If your organization wishes to host a local instance of ANDI, the accessibility testing tool, refer to this guide.


In fact, its rumoured he has 4 balls.


During the day I've been working in the wireless industry for 18 years but during the night I like to wear my cape and pretend to be batman.
I have a 11 year old daughter who is huge, she is over 5 feet 5 inches tall
when I use to ski race I use to break my thumbs on the racing gates 2 to 3 times a year. Now my hands look just like the man on scary movie 2. My dip!


There Was An Error Fetching The Projects Content. The Server May Be Experiencing Unexpected Difficulties. Click here to go back to the home page
{{ link.name }}
{{ paragraph }}


This session introduces methods and events to control and interact with the camera of the device enabling users to take pictures. See the example below:
In this example, the camera is turned on and off according to the events show and hide of the modal. Refer to bootstrap documentation for more details about the modal plugin.
@@include('includes/code-examples/device-controls/camera/camera.html')
@@include('includes/code-examples/device-controls/camera/camera.js')
IE 11 and below currently does not support getUserMedia
.
However, there is some polyfills available that you can explore.
Options can be passed via data attributes:
| Option | Type | Default | Description |
|---|---|---|---|
data-size |
string | 320x240 | The size of the picture. Invalid size will be converted to default size. |
A few methods are available to control the camera:
| Method | Description |
|---|---|
camera('play') |
Starts the camera. Triggers the event camera:play or camera:error . |
camera('stop') |
Stop the camera. Triggers the event camera:stop . |
camera('snapshot') |
Take a picture from the camera. Triggers the event camera:snapshot . |
Events triggered from the camera can be listened to write custom logic:
| Event | Description |
|---|---|
camera:play |
Triggered after the camera starts to play. |
camera:error |
Triggered if any error occur during the start of the camera. |
camera:notSupported |
Triggered if the browser does not support camera. |
camera:stop |
Triggered after the camera stop. |
camera:snapshot |
Triggered after a picture is taken. Blob and data URL are ready. |


Complexity Analysis of Algorithm
Sudhanshu Dubey
D3 CSE B1 | 1706523
What !?
What’s an Algorithm?
It’s a
well defined
sequence of steps
to solve a problem.
Or basically instructions for the dumbest person in the world, the computer.
… and Complexity?
the state of being difficult to understand
Complexity of Algorithm
Analysis helps us to understand
how difficult it is for the computer to understand/implement the algorithm
.
Why !?
Why complexity analysis?
A problem maybe solved using various algorithms.
We need to find the best way of solving the problem so that minimum resources are used up.
… even with superfast computers?
Absolutely!!!
Let’s take an example. A problem can be solved using these algorithms:
So it’s clear from above that using a more efficient algorithm is much more benificial than having a faster processor.
How !?
How to find complexity?
There are 2 types of complexities that we are intrested in:
Space Complexity
Time Complexity
Both of these complexities can be evaluated using various criteria, but we will be focusing on the
rate of growth
.
Rate of growth is basically how much the complexity changes w.r.t the input size.
How to find rate of growth?
We have to realize that the idea of complexity is an abstract one and no value can be actually associated with it.
We can only relatively compare the growth of our algorithms with the growth of some mathematical function.
And for this comparison, we use
Asymptotic Notations
.
Thanks


"CORAL" Hebrews ramoth, meaning “heights;” i.e., “high-priced” or valuable things, or, as some suppose, “that which grows high,” like a tree(Job 28:18; Ezekiel 27:16), according to the Rabbins, red coral, which was in use for ornaments. The coral is a cretaceous marine product, the deposit by minute polypous animals of calcareous matter in cells in which the animal lives. It is of numberless shapes as it grows, but usually is branched like a tree. Great coral reefs and coral islands abound in the Red Sea, whence probably the Hebrews derived their knowledge of it. It is found of different colours, white, black, and red. The red, being esteemed the most precious, was used, as noticed above, for ornamental purposes.
"CORAL" Hebrews ramoth, meaning “heights;” i.e., “high-priced” or valuable things, or, as some suppose, “that which grows high,” like a tree(Job 28:18; Ezekiel 27:16), according to the Rabbins, red coral, which was in use for ornaments.
The coral is a cretaceous marine product, the deposit by minute polypous animals of calcareous matter in cells in which the animal lives. It is of numberless shapes as it grows, but usually is branched like a tree. Great coral reefs and coral islands abound in the Red Sea, whence probably the Hebrews derived their knowledge of it. It is found of different colours, white, black, and red. The red, being esteemed the most precious, was used, as noticed above, for ornamental purposes.


Diet Problem Solver
About me
Hi! I'm Raven John M. Lagrimas. 2010-43168. You can find me at
https://github.com/ravenjohn
https://facebook.com/ven.lagrimas
Pick your food!
Type anywhere to search...
Results
Simplexify
Objective Function :
Add Constraint
Maximize
Minimize


Are you worried about the safety and security of your child? Amber Alert GPS is the best product that will help you keep track of your child no matter where he or she is. It is a tiny devise that your child can wear or you can attach it to his book bag or clothing. Use the latest in GPS and Cellular technology for your peace of mind. Keep your child safe and secure with the use of Amber Alert GPS. It was rated four out of five by editor’s choice on GPS magazine.com and also got reviewed on MSNBC television. Check it out on Amber Alert GPS.com and use our discount coupon to get a discount on this must have item.
Amber Alert GPS is the world’s smallest and most powerful tracking devise. Once you put it on your child or pocket, purse, book bag or car you can track your child’s movements on your computer or cell phone. You can call the amber alert GPS and it will immediately send you text messages giving you the address and map of where your child is. Check it out online now.
 Amber Alert GPS also has an SOS button, temperature alert, and speed alert where you will receive an alert if the child is in a high speed car or in a very hot or cold place. You can also listen into what is happening to your child in any emergency situation without your child or anyone with him knowing. These are great emergency and security features of the Amber Alert GPS. It is a great devise for all ages. Get it today.


We strive to create a unique design for your project that will help your business or individual enterprise stand out.
We are an expert at creating designed websites to fit your needs. We strive to create a unique design for your website that will help your business, corporation, or individual enterprise stand out. If you're looking for a corporate presence website, e-commerce, or even just a landing page, our team is happy to help.
We strive to create a unique design for your project that will help your business or individual enterprise stand out.
We are an expert at creating designed websites to fit your needs. We strive to create a unique design for your website that will help your business, corporation, or individual enterprise stand out. If you're looking for a corporate presence website, e-commerce, or even just a landing page, our team is happy to help.


Description
The Set Canvas Sample demonstrates alignment of Open Class objects on vertical and horizontal set canvases. In addition, horizontal and vertical split canvases, and tab movement between different groups.
Concept
Sample program demonstrates ISetCanvas and ISplitCanvas.
Task
The three left canvases have vertical orientation and the right canvases have horizontal orientation. Each canvas has a different number of controls to demonstrate the arrangement differences.
Supported
Supported
Supported


These are some of the latest skills and technologies that I have been studying and implementing from past few months.
Nanotechnology is a field of research and innovation concerned with building 'things' - generally, materials and devices - on the scale of atoms and molecules. A nanometre is one-billionth of a metre.
Web design encompasses many different skills and disciplines in the production and maintenance of websites. The different areas of web design include web graphic design, UI, UX design and search engine optimization.
To oversee and maintain their computer hardware and software systems. Their skills are an asset to the company, as they assist in resolving technical issues concerning customer's accounts or company software infrastructure.
It is the protection of internet-connected systems and data from cyberthreats. The practice is used by individuals and enterprises to protect against unauthorized access to data centers and other computerized systems.
This is a website for searching the availability of any stationary product in the nearby stationary stores of the user and placing orders in any of those stores. This is mainly made up of HTML, CSS, JavaScript, PHP and SQL. This project is under development stage and will be soon developed using React framework.
This is a website from which we can navigate to specifies waterpark websites and book the tickets. In future it may be implemented as a booking website where all the parks will be in patnership and will provide discounts on booking from this website.
Developed a Machine Learning App which can recognize images and categorize them efficiently with an accuracy of 0.89 using SVM Regressor.
This project was basically made for The Google's Solution Challenge 2021. This is a e-commerce webiste where we can buy items that is very much in need in this pandemic period. It is completely mad with ReactJS and in-built integrated payment gateway system with Debit/Credit card enabled.
It is my first ever android project where I had developed a full functional fish game. It is made with all backend services and java encoded. It was built on Android Studio.
This team works efficiently with all the web development tools and techniques, and creates different website designes according to customer's requirement, using latest frameworks like ReactJS and AngularJS.
Whatsapp Us


More Interesting Examples with f2py#
Let us now look at some more interesting examples using f2py. We will implement a simple iterative method for solving laplace’s equation in a square. Actually, this implementation is taken from http://www.scipy.org/PerformancePython?highlight=%28performance%29 page on the scipy website. It has lots of information on implementing numerical algorithms in python.
The following fortran code implements a single iteration of a relaxation method for solving Laplace’s equation in a square.
%fortran
subroutine timestep(u,n,m,dx,dy,error)
double precision u(n,m)
double precision dx,dy,dx2,dy2,dnr_inv,tmp,diff
integer n,m,i,j
cf2py intent(in) :: dx,dy
cf2py intent(in,out) :: u
cf2py intent(out) :: error
cf2py intent(hide) :: n,m
dx2 = dx*dx
dy2 = dy*dy
dnr_inv = 0.5d0 / (dx2+dy2)
error = 0d0
do 200,j=2,m-1
do 100,i=2,n-1
tmp = u(i,j)
u(i,j) = ((u(i-1,j) + u(i+1,j))*dy2+
& (u(i,j-1) + u(i,j+1))*dx2)*dnr_inv
diff = u(i,j) - tmp
error = error + diff*diff
100 continue
200 continue
error = sqrt(error)
end
If you do
timestep?
You find that you need pass timestep a numpy array u, and the grid spacing dx,dy and it will return the updated u, together with an error estimate. To apply this to actually solve a problem use this driver code
import numpy
j=complex(0,1)
num_points=50
u=numpy.zeros((num_points,num_points),dtype=float)
pi_c=float(pi)
x=numpy.r_[0.0:pi_c:num_points*j]
u[0,:]=numpy.sin(x)
u[num_points-1,:]=numpy.sin(x)
def solve_laplace(u,dx,dy):
iter =0
err = 2
while(iter <10000 and err>1e-6):
(u,err)=timestep(u,dx,dy)
iter+=1
return (u,err,iter)
Now call the routine using
(sol,err,iter)=solve_laplace(u,pi_c/(num_points-1),pi_c/(num_points-1))
This solves the equation with boundary conditions that the right and left edge of the square are half an oscillation of the sine function. With a 51x51 grid that we are using I find that it takes around .2 s to solve this requiring 2750 iterations. If you have the gnuplot package installed (use optional packages() to find its name and install package to install it), then you can plot this using
import Gnuplot
g=Gnuplot.Gnuplot(persist=1)
g('set parametric')
g('set data style lines')
g('set hidden')
g('set contour base')
g('set zrange [-.2:1.2]')
data=Gnuplot.GridData(sol,x,x,binary=0)
g.splot(data)
To see what we have gained by using f2py let us compare the same algorithm in pure python and a vectorized version using numpy arrays.
def slowTimeStep(u,dx,dy):
"""Takes a time step using straight forward Python loops."""
nx, ny = u.shape
dx2, dy2 = dx**2, dy**2
dnr_inv = 0.5/(dx2 + dy2)
err = 0.0
for i in range(1, nx-1):
for j in range(1, ny-1):
tmp = u[i,j]
u[i,j] = ((u[i-1, j] + u[i+1, j])*dy2 +
(u[i, j-1] + u[i, j+1])*dx2)*dnr_inv
diff = u[i,j] - tmp
err += diff*diff
return u,numpy.sqrt(err)
def numpyTimeStep(u,dx,dy):
dx2, dy2 = dx**2, dy**2
dnr_inv = 0.5/(dx2 + dy2)
u_old=u.copy()
# The actual iteration
u[1:-1, 1:-1] = ((u[0:-2, 1:-1] + u[2:, 1:-1])*dy2 +
(u[1:-1,0:-2] + u[1:-1, 2:])*dx2)*dnr_inv
v = (u - u_old).flat
return u,numpy.sqrt(numpy.dot(v,v))
You can try these out by changing the timestep function used in our driver routine. The python version is slow even on a 50x50 grid. It takes 70 seconds to solve the system in 3000 iterations. It takes the numpy routine 2 seconds to reach the error tolerance in around 5000 iterations. In contrast it takes the f2py routine around .2 seconds to reach the error tolerance using 3000 iterations. I should point out that the numpy routine is not quite the same algorithm since it is a jacobi iteration while the f2py one is gauss-seidel. This is why the numpy version requires more iterations. Even accounting for this you can see the f2py version appears to be around 5 times faster than the numpy version. Actually if you try this on a 500x500 grid I find that it takes the numpy routine 30 seconds to do 500 iterations while it only takes about 2 seconds for the f2py to do this. So the f2py version is really about 15 times faster. On smaller grids each actual iteration is relatively cheap and so the overhead of calling f2py is more evident, on larger examples where the iteration is expensive, the advantage of f2py is clear. Even on the small example it is still very fast. Note that a 500x500 grid in python would take around half an hour to do 500 iterations.
To my knowledge the fastest that you could implement this algorithm in matlab would be to vectorize it exactly like the numpy routine we have. Vector addition in matlab and numpy are comparable. So unless there is some trick I don’t know about, using f2py you can interactively write code 15 times faster than anything you could write in matlab (Please correct me if I’m wrong). You can actually make the f2py version a little bit faster by using intent(in,out,overwrite) and creating the initial numpy array using order=’FORTRAN’. This eliminates the unnecessary copying that is occurring in memory.


When running an Express app behind a reverse proxy, some of the Express
APIs may return different values than expected. In order to adjust for
this, the trust proxy
application setting may be used to
expose information provided by the reverse proxy in the Express APIs. The
most common issue is express APIs that expose the client’s IP address may
instead show an internal IP address of the reverse proxy.
When configuring the trust proxy
setting, it is important
to understand the exact setup of the reverse proxy. Since this setting
will trust values provided in the request, it is important that the
combination of the setting in Express matches how the reverse proxy
operates.
The application setting trust proxy
may be set to one of the
values listed in the following table.
| Type | Value |
|---|---|
| Boolean |
If
If
When setting to |
| IP addresses |
An IP address, subnet, or an array of IP addresses and subnets to trust as being a reverse proxy. The following list shows the pre-configured subnet names:
You can set IP addresses in any of the following ways:
req.socket.remoteAddress is trusted. If so, then each
address in X-Forwarded-For is checked from right to
left until the first non-trusted address.
|
| Number |
Use the address that is at most When using this setting, it is important to ensure there are not multiple, different-length paths to the Express application such that the client can be less than the configured number of hops away, otherwise it may be possible for the client to provide any value. |
| Function |
Custom trust implementation. |
Enabling trust proxy
will have the following impact:
X-Forwarded-Host
header, which can be set by the client or
by the proxy.
X-Forwarded-Proto
can be set by the reverse proxy to tell
the app whether it is https
or http
or even an
invalid name. This value is reflected by
req.protocol.
X-Forwarded-For
header, starting at the first untrusted
address.
The trust proxy
setting is implemented using the
proxy-addr package.
For more information, see its documentation.


Northside Youth Soccer League
RULES OF PLAY & POLICIES
FIFA rules shall govern NYSL play except as modified herein.
-
SPORTSMANSHIP
- The common interest that members of the Association share is to inspire youth to practice the ideals of sportsmanship and fair play. Any player, coach, team, parent, spectator, administrator or referee whose behavior detracts from this purpose is subject to disciplinary action regardless of technical soccer background, expertise, accomplishments or standing.
-
FIFA FIELD REGULATIONS
- DIMENSIONS.FIFA Law 1 provides for flexible external field dimensions within a given maximum and minimum width and length. These dimensions should be adhered to for all fields used by teams under 12 and older.
- COMPETITION FIELDS. Fields used within the competition program must be a minimum of 100 x 60 yards.Leagues, districts or associations participating in the state competition program that are unable to provide a field that meets these minimum requirements must advise the State Competition Board which will assign its Fields Committee to inspect the field and recommend to the Board whether or not a waiver of the minimum dimensions should be granted. Teams from leagues, districts or associations that are unable to provide an acceptable field may be required to play all their games away.
-
FIELDS USED BY YOUNG AGE GROUPS
- U-6 play on a field approximately 20 X 40 yards with no penalty areas. Fields for older age groups should be progressively larger.
- U-8 plays on a field 40-50 yards in length and 20-30 yards width.
- U-10 play on a field 70-80 yards in length and 40-50 yards in width.
- In addition, fields used by young age groups may have their internal dimensions and size of goal similarly modified.
-
ALL-PLAY
-
All-play means that every recreation player on every team shall play atleast fifty percent of each game. Coaches in the competition program are encouraged to play their players 50% of each game.
- A Coach shall be permitted to not play a player 50% of each game under special circumstances, e.g., unexcused absences from practice and/or games, ungentlemanly conduct at practice and/or games, and injuries
-
All-play means that every recreation player on every team shall play atleast fifty percent of each game. Coaches in the competition program are encouraged to play their players 50% of each game.


Goal
Responsive image that zooms in on hover
Research solution options and document pros and cons
Alternative approach can be found here where the image is being used as background image
Research - High level approach
img tag within a container
add a transition to the image on hover
Pro: usage of srcset will be better for performance
Research - Tranformation
- usage of transform will make use of hardware acceleration which will make the animation look smooth
Demo
Flex grid item 1
The following image will be listed first on mobile
Flex grid item 4
Flex grid item 4
Flex grid item 5
The following image will be listed first on mobile
Flex grid item 7
Flex grid item 7


CocoaHeadsNYC - June 9, 2016
Don Coleman - Chariot Solutions
0000FF10-0000-1000-8000-00805F9B34FB
0000FF11-0000-1000-8000-00805F9B34FB
0000FF12-0000-1000-8000-00805F9B34FB
(not Core Bluetooth)
Don Coleman
Slides http://don.github.io/slides/
Code http://github.com/don/cocoaheadsnyc
Bluetooth Low Energy for iOS by Don Coleman is licensed under a Creative Commons Attribution 4.0 International License.


Find out when the International Space station will streak across the sky at your location
Powered by the open project Open-Notify
See the power yourself
Get the next pass texted to your mobile
When?!
Don't want a text? Get the next 5 passes in email
Please!
should be stuff here eventually. Pictures with links i think...


A Bar chart capable of drilldown
This goes in the documents header:
<script src="RGraph.common.core.js"></script>
<script src="RGraph.common.effects.js"></script>
<script src="RGraph.common.dynamic.js"></script>
<script src="RGraph.drawing.text.js"></script>
<script src="RGraph.bar.js"></script>
Put this where you want the chart to show up:
<canvas id="cvs" width="600" height="250">
[No canvas support]
</canvas>
This is the code that generates the chart - it should be placed AFTER the canvas tag(s):


This report is from At&T Business Network's web site.
|
|
||||||||
BOAT BUILDING AND REPAIRING INDUSTRY : SIC 3732Establishments primarily engaged in building and repairing boats. Rubber and nonrigid plastics boats are classified under rubber and plastic products. marinas which perform incidental boat repair are classified in 4493; membership yacht clubs are classified in 7997; and outboard motor repair is classified in 7699.
|
||||||||
Market SizeEstimated number of U.S. establishments: 2,804
|
||||||||
Market Share Analysis |
||||||||
| Num. of Employees | Num. of Bus. | % of Bus. | Total Sales | Market Share | ||||
|---|---|---|---|---|---|---|---|---|
| 1 | 442 | 15.8% | 63.3 | 1.0% | ||||
| 2 to 4 | 1273 | 45.4% | 570.0 | 8.6% | ||||
| 5 to 9 | 430 | 15.3% | 762.8 | 11.5% | ||||
| 10 to 24 | 286 | 10.2% | 1393.5 | 21.0% | ||||
| 25 to 49 | 135 | 4.8% | 365.7 | 5.5% | ||||
| 50 to 99 | 85 | 3.0% | 532.4 | 8.0% | ||||
| 100 to 249 | 70 | 2.5% | 1167.5 | 17.6% | ||||
| 250 to 499 | 40 | 1.4% | 836.0 | 12.6% | ||||
| 500 to 999 | 11 | 0.4% | 696.8 | 10.5% | ||||
| 1,000 to 9,999 | 3 | 0.1% | 94.1 | 1.4% | ||||
| unknown | 29 | 1.0% | 148.7 | 2.2% | ||||
| Totals/Averages | 2804 | 100.0% | 6630.8 | 100.0% | ||||
|
|
||||||||
|
Note: Only market segments with a 3% or larger market share are labeled in the chart. Sales figures are in millions.
|
||||||||
Market Analysis by Company Size |
||||||||
| Num. of Employees | Num. of Bus. | Total Emp. | Total Sales | Avg. Emp. | Avg. Sales | |||
| 1 | 442 | 442 | 63.3 | 1 | 0.1 | |||
| 2 to 4 | 1,273 | 3,625 | 570.0 | 2 | 0.4 | |||
| 5 to 9 | 430 | 2,712 | 762.8 | 6 | 1.8 | |||
| 10 to 24 | 286 | 4,166 | 1,393.5 | 14 | 5.2 | |||
| 25 to 49 | 135 | 4,429 | 365.7 | 32 | 3.0 | |||
| 50 to 99 | 85 | 5,803 | 532.4 | 68 | 7.6 | |||
| 100 to 249 | 70 | 9,913 | 1,167.5 | 141 | 24.8 | |||
| 250 to 499 | 40 | 13,675 | 836.0 | 341 | 41.8 | |||
| 500 to 999 | 11 | 6,664 | 696.8 | 605 | 139.3 | |||
| 1,000 to 9,999 | 3 | 3,250 | 94.1 | 1,083 | 94.1 | |||
| unknown | 29 | N/A | 148.7 | N/A | 37.1 | |||
| Totals/Averages | 2,804 | 54,679 | 6,630.8 | 19 | 2.5 | |||
|
Note: Sales figures are in millions.
|
||||||||
Market Analysis by Geography |
||||||||
State | Num. of Bus. | Total Emp. | Total Sales | Avg. Emp. | Avg. Sales | |||
| Alabama | 26 | 185 | 6.2 | 7 | 0.2 | |||
| Alaska | 36 | 114 | 6.3 | 3 | 0.1 | |||
| Arizona | 28 | 338 | 9.4 | 12 | 0.3 | |||
| Arkansas | 43 | 1,660 | 162.9 | 41 | 4.1 | |||
| California | 326 | 2,875 | 328.9 | 8 | 1.0 | |||
| Colorado | 8 | 25 | 1.5 | 3 | 0.2 | |||
| Connecticut | 31 | 124 | 13.5 | 4 | 0.4 | |||
| Delaware | 4 | 6 | 0.4 | 1 | 0.1 | |||
| Washington, D.C. | 1 | 2 | 0.2 | 2 | 0.2 | |||
| Florida | 494 | 11,046 | 928.8 | 22 | 2.0 | |||
| Georgia | 35 | 970 | 75.8 | 27 | 2.2 | |||
| Hawaii | 24 | 73 | 5.8 | 3 | 0.2 | |||
| Idaho | 20 | 80 | 9.1 | 4 | 0.5 | |||
| Illinois | 35 | 2,114 | 100.4 | 62 | 3.2 | |||
| Indiana | 40 | 2,610 | 207.1 | 66 | 6.6 | |||
| Iowa | 10 | 230 | 7.6 | 23 | 0.8 | |||
| Kansas | 10 | 301 | 41.3 | 30 | 4.1 | |||
| Kentucky | 22 | 553 | 38.7 | 25 | 1.7 | |||
| Louisiana | 91 | 3,761 | 82.1 | 41 | 1.0 | |||
| Maine | 125 | 1,212 | 101.4 | 9 | 0.8 | |||
| Maryland | 82 | 703 | 26.3 | 8 | 0.3 | |||
| Massachusetts | 86 | 531 | 29.9 | 6 | 0.3 | |||
| Michigan | 109 | 2,104 | 135.0 | 19 | 1.4 | |||
| Minnesota | 54 | 1,878 | 1,301.5 | 34 | 26.5 | |||
| Mississippi | 17 | 356 | 19.4 | 20 | 1.3 | |||
| Missouri | 39 | 2,722 | 123.3 | 69 | 3.6 | |||
| Montana | 7 | 16 | 0.9 | 2 | 0.1 | |||
| Nebraska | 7 | 556 | 396.0 | 79 | 66.0 | |||
| Nevada | 8 | 141 | 54.7 | 17 | 6.8 | |||
| New Hampshire | 10 | 37 | 3.5 | 3 | 0.3 | |||
| New Jersey | 50 | 1,304 | 115.0 | 26 | 2.3 | |||
| New Mexico | 2 | 6 | 0.2 | 3 | 0.1 | |||
| New York | 74 | 491 | 319.7 | 6 | 4.5 | |||
| North Carolina | 103 | 2,549 | 109.8 | 25 | 1.1 | |||
| North Dakota | 1 | 55 | 3.9 | 55 | 3.9 | |||
| Ohio | 29 | 651 | 75.7 | 22 | 3.0 | |||
| Oklahoma | 26 | 401 | 12.4 | 15 | 0.5 | |||
| Oregon | 76 | 746 | 49.2 | 9 | 0.6 | |||
| Pennsylvania | 17 | 105 | 4.3 | 6 | 0.2 | |||
| Rhode Island | 49 | 1,210 | 115.4 | 24 | 2.4 | |||
| South Carolina | 32 | 732 | 48.9 | 22 | 1.6 | |||
| Tennessee | 59 | 3,193 | 949.8 | 55 | 19.7 | |||
| Texas | 141 | 1,198 | 72.8 | 8 | 0.5 | |||
| Utah | 14 | 53 | 3.0 | 4 | 0.2 | |||
| Vermont | 13 | 92 | 9.4 | 7 | 0.8 | |||
| Virginia | 36 | 269 | 16.5 | 7 | 0.5 | |||
| Washington | 201 | 2,014 | 124.0 | 10 | 0.6 | |||
| West Virginia | 1 | 4 | 0.2 | 4 | 0.2 | |||
| Wisconsin | 52 | 2,283 | 382.7 | 44 | 8.1 | |||
| Totals/Averages | 2,804 | 54,679 | 6,630.8 | 19 | 2.5 | |||
|
Note: If multiple branch offices exist, each branch office is considered an independent establishment. Sales figures are in millions.
|
||||||||
Market Analysis by Specialty |
||||||||
Specialty | Num. of Bus. | Total Emp. | Total Sales | Avg. Emp. | Avg. Sales | |||
| Boatbuilding and repairing | 1,571 | 20,377 | 1,744.3 | 13 | 1.2 | |||
| Motorized boat, building and repairing | 71 | 799 | 740.8 | 12 | 11.3 | |||
| Fishing boats: lobster, crab, oyster, etc.: small | 109 | 1,657 | 180.7 | 15 | 1.7 | |||
| Houseboats, building and repairing | 36 | 788 | 59.6 | 21 | 1.8 | |||
| Hydrofoil boats | 4 | 579 | 2.2 | 144 | 1.1 | |||
| Jet skis | 15 | 1,274 | 483.7 | 84 | 34.5 | |||
| Motorboats, inboard or outboard: building and repairing | 161 | 5,600 | 894.9 | 34 | 5.9 | |||
| Tenders (small motor craft), building and repairing | 4 | 11 | 0.8 | 2 | 0.2 | |||
| Non-motorized boat, building and repairing | 24 | 357 | 22.6 | 14 | 1.0 | |||
| Canoes, building and repairing | 53 | 859 | 116.0 | 16 | 2.2 | |||
| Dinghies, building and repairing | 6 | 22 | 0.8 | 3 | 0.1 | |||
| Dories, building and repairing | 3 | 8 | 0.4 | 2 | 0.1 | |||
| Kayaks, building and repairing | 27 | 335 | 25.8 | 12 | 0.9 | |||
| Lifeboats, building and repairing | 4 | 70 | 16.0 | 17 | 16.0 | |||
| Rowboats, building and repairing | 12 | 50 | 2.9 | 4 | 0.2 | |||
| Sailboats, building and repairing | 109 | 3,865 | 275.7 | 35 | 2.8 | |||
| Skiffs, building and repairing | 3 | 21 | 1.1 | 7 | 0.3 | |||
| Boat kits, not models | 15 | 51 | 3.4 | 3 | 0.2 | |||
| Boats, fiberglass: building and repairing | 383 | 12,923 | 1,584.1 | 34 | 4.4 | |||
| Boats, rigid: plastics | 10 | 213 | 11.3 | 21 | 1.2 | |||
| Pontoons, except aircraft and inflatable | 33 | 1,055 | 96.0 | 31 | 3.0 | |||
| Yachts, building and repairing | 151 | 3,765 | 367.7 | 24 | 2.5 | |||
| Totals/Averages | 2,804 | 54,679 | 6,630.8 | 19 | 2.5 | |||
|
Note: Not all establishments have a specialty. Sales figures are in millions. |
Return to Recreational Boat Building Industry Home Page


---
layout: post
title: High carbohydrate lunch set
date: '2006-11-02T08:50:00.002Z'
author: tknv
tags:
- oosaka
- food
modified_time: '2009-07-09T19:28:10.044Z'
blogger_id: tag:blogger.com,1999:blog-11459759.post-116245758294253123
blogger_orig_url: http://phichyudebow.blogspot.com/2006/11/high-carbohydrate-lunch-set.html
---
Okonomi-yaki,Yaki-soba and Rice with Miso soup.
at Osaka


We fund nonprofit organizations that provide vital health and human services, aid people in need, and strengthen the infrastructure that supprts a healthy society. IT operations staff can monitor and manage private and public cloud services. And the CIO can enforce configuration compliance across the entire hybrid estate
As organizations seek innovation by adopting public, private, and hybrid clouds, many of them are running up against formidable barriers. In some cases they find that the promised innovations of cloud computing are slow to materialize. Running multiple cloud services is difficult and can cause confusion within the IT department.
Hybrid cloud uptake is on the rise, and the challenges of managing business-driven IT environments, in which public and private clouds can thrive, are becoming increasingly important and critical. How can you manage a hybrid cloud as one cohesive entity when the journey to cloud is so complex? How do you enable lines of business to consume IT services on-demand when you have competing stakeholder priorities?
With businesses moving at a rapid pace, CIOs are tasked with transforming IT to drive innovation. They want their teams to manage on-premises and cloud services in a cohesive way, with dynamic workload migration, unified DevOps processes, and adherence to corporate compliance standards. Meanwhile, software development managers are clamoring for control over IT resources.


Wire up a click handler to the CREATE ADDRESS button such that the form can be submitted and the data is pulled from the
form for processing.
Every time a new registration is submitted: the data must be displayed in the right-hand column using the example html.
The fields that have drop downs should have their text values displayed (ie. state should
show "CA" and not "1")
After the new address is appended, the form must be reset back to it's original state (i.e. all fields empty and the dropdown
should says "Please Select").
Add a red delete button for each individual address in the right-hand column. when clicked this button should remove only
that one address from the list.
When you click anywhere on an address item in the right column, you should populate the form on the left with the data in
the given address. So if you were to click on the "400 Corporate Pointe" address element (anywhere
in that div) the text book for "Line 1" should change to "400 Corporate Pointe".
After clicking submit on the button (after you clicked on an address) the address in question should be updated instead of
creating a new address in the list.
If the user does not select a state you should show an alert that tells them to select a state
The image should show the address as the example does. this is done by manipulating the src attribute of the image. So if
you add an address your house, it should show your house on the map not the address that is currently
shown.
While we are looking for working pages, however you can make that happen, we would like to see code with:
JavaScript Namespacing
No inline functions unless absolutely required
Functional pages are the #1 priorty though.
400 Corporate Pointe
Apt/Suite#:
B1010
Culver City,CA90230
United States
100 Corporate Pointe
Apt/Suite#:
300
Culver City,CA90230
United States
Sign in to your account
If you have an account with us, please enter your details below.


School: Jose Marti STEM Academy
School: Lincoln Park Middle School
School: Orange Preparatory Academy


--- layout: post status: publish published: true title: Ivy Envy author: display_name: Corey Fineran login: Corey email<EMAIL_ADDRESS>url: '' author_login: Corey author_email<EMAIL_ADDRESS>wordpress_id: 4 wordpress_url: http://ivyenvy.wordpress.com/?p=4 date: '2008-04-09 21:21:19 +0000' date_gmt: '2008-04-09 21:21:19 +0000' categories: - Uncategorized tags: - Introduction - Ivy Envy comments: [] ---
Welcome to Ivy Envy.
We are a group of guys that are lifelong Cubs fans. At this time, there are six authors. Five of us are from Illinois and one is a Californian. We are using this forum to discuss everything Cubs-related. This will not be where you go for up-to-the-second news from the clubhouse, but we do hope to inform and entertain. You will get six opinions and points of view.
This site will change over time, and perhaps in the matter of days. Things will improve and we’ll be able to add features to make it more of a "one stop shop".
To start this blog, I have asked the authors to introduce themselves and tell you about their experience with the Cubs.
Make yourself at home and we encourage you to participate.


title=CRUD's Not The Answer date=2009-09-10 type=post tags=blog status=published ~~~~~~
I was really glad to see Udi Dahan's, "Don't Delete. Just Don't." I wholely agree with the main premise - that deletion is rarely, if ever, a valid business state and that care should be taken in dealing with it. He cites various examples, saying, "The real world doesn't cascade." His example is of a marketing department that deletes an item from the catalog. Should all orders containing that item then be unlinked? Should they redo the company's profit and loss statments?
His example's a perfect
illustration of a valid case where care needs to be taken both in
modeling the case and dealing with it in code. I fear a lot of people
have gotten hooked on instant-models or CRUD "frameworks." The idea
that you can annotate a few entity classes and suddenly you have a
model and business logic all taken care. A lot of this became popular
with Ruby on Rails and has only gotten worse in the JEE world. It's
now common to expose EntityManager
s to the web tier (both
the Seam and Spring Web Flow examples, not to mentino the Open Session
in View pattern itself, speak to this) and to let web frameworks
handle the lifecycle of entities and committing transactions on that
EntityManager to persist those entities. We now think of record
creation and managment as so mundane that we've automated it and
surrounded it in scaffolding.
Unfortuntately, this misses the true value. Objects in a system have state that has dependencies. Just because an entity has a (required) no-args constructor, it doesn't mean that you should not write a constructor with dependencies. A lot of this stems from the "active objects" or "naked objects" pattern, where objects are open books whose state can be mutated on the UI tier directly and those changes propagated directly. We tell ourselves that we can apply Hibernate validations (or validations in any other ORM framework) and that we'll guarantee valid business constraints thus, but it rarely works out that way. Prescribing the valid creation and destruction of an object is critical.
The most insidious part of this abuse is that it rarely ever occurs in the first iterations of a project, only in maintenance. People "forget" how an object is created, or destroyed. They forget details. Consistancy with other parts of the system is forsaken because, after all, how much could there be to it? This happens more often than you'd expect: new people come on to the team and are assigned to rework an existing feature and screen in a system. Institutional knowledge is important but it's not always easily transferred, so safe-guards need to be taken.
Plus, as business evolves, object creation is often only part and
parcel with a larger process. If a new customer is added to a
database, and nobody does anything with it, did it really get added?
Put another way: if a new customer gets added to a database, there's
an implied lifecycle that customer must follow. Perhaps a trial period
window and then a follow up email? Perhaps a monthly subscriptio fee?
Who knows, but the act of instantiating a Customer
object
and then issuing entityManager.persist( customer )
will
rarely, if ever, be enough.
Indeed, I've seen many projects
build their models using only a GenericDao<T>
variant. This is dangerous. Transitions from one state to another
for an entity can often cost money.
Do things the old fashioned way, building services that handle the business operations, not merely Create, Read,Update and Delete objects. Using Dao's in a view tier is almost as ghastly a sin as making JDBC calls from the view, and encourages the same kind of copy-n-paste code reuse we prided ourselves on having moved away from.
While the services approach isn't exactly code-generation friendly, it can pay off in the long run.  It's easier to build services that express every dependency as a method parameter. There are several reasons why this works out. While web service support is getting better, object marshalling is still the number one headache. Most toolkits make interoping with primitives a brease, though. It may seem like your losing ground by not taking advantage of the POJO you have floating around in the view tier, but in point of fact it's rarely that big a burden to unmarshal the relevant fields and use those instead. On the services side, reloading the relevant record is painless because the entity's usually cached and thus refetching it is cheap.
Take for example the idea of a shopping cart which surfaces methods for adding line items to orders, orders to shopping carts and shopping carts to customers. A clean version of this might look like:
public interface ShoppingCartService {
ShoppingCart createShoppingCartForCustomer( long customerId,
Date
whenShoppingSessionStarted ) ;
Order createOrderForShoppingCart( long shoppingCart ) ;
LineItem createLineItemForOrder( long orderId, long productId,
int quantity) ;
void removeLineItemFromOrder( long orderId, long lineItem ) ;
void startOrderFulfillment( long orderId ) ;
/* other methods for loading and removing the various
objects, as appropriate
*/
}
In these methods, you can do sanity checks,
care for business cases, handle the state of the various objects and
not worry about having a transactional resource like an
EntityManager
or Hibernate Session open in the client thread.
In this example, you might imagine the Order
won't
officially be fulfilled until it's paid for, at which point it'll move
to the PAID
state. Simialarly, adding a
LineItem
might require a check to an inventory,
decrementing how many of those Product
s are in stock. The
same is true of the inverse operation:
removeLineItemFromOrder
should appropriately restore the
inventory count and update the totalPrice
field on the
Order
.
EntityManager
from your Seam backing bean and executed
the logic there, except now the logic's codified and reusable.


Halima moves into driver's seat at Dangote Group of Companies
Halima moves into driver’s seat at Dangote Group of Companies
Alhaji Aliko Dangote’s daughter, Halima, has finally assumed the driver’s seat of her father’s businesses. The word is everywhere that she has taken over as the Group Executive Director of Commercial Operations of Dangote Industries Limited, one of Africa’s largest and most diversified business conglomerates.
Read Also: Sylva hails Dangote refinery project
Halima Dangote is also a trustee of the philanthropic arm of the Group known as Aliko Dangote Foundation. She has worked in different arms of the Group, setting new standards and influencing performance in the area of profit.
She is the President of the Board of the African Centre in New York and a member of The Women Corporate Directors.
Halima Dangote is coming into this new position with a lot of cutting-edge experience, having studied in Ivy League schools across the globe.


Tanmay Parikh
19
Years Old
<EMAIL_ADDRESS>Professional
simpleweather.co
Professional
tanallnight
GitHub
@TANninginMAY
Twitter
+TanmayParikh
Google Plus
tanmay-parikh
Linkedin
Language
English
Language of Education
Hindi
Native Language
Mechatronics Engineer / Android Developer
Work Experience
Sept 2014 - Present
Independent Android Developper
Toronto, Canada
Simple Weather
10k+ downloads
April 2014 - Sept 2014
Lead UI/UX Developer @InforMeApps
Toronto, Canada
InforMe (Ryerson)
500+ Downloads
Feb 2012 - June 2012
Tool & Die Maker
@Cantech Machine & Tool Co.
Mississauga, Canada
Education
2013 - Present
Bachelors of Engineering
@Ryerson University
Toronto, Canada
Mechatronics Engineering w/ minor in Information Technology Management
2010 - 2013
High School Diploma
@Port Credit Secondary School
Mississauga, Canada
Specialist High Skills Major in Manufacturing
Professional Skills
Mobile
Android (Java)
Web / Server
PHP, HTML, Javascript
Design
Photoshop, Illustrator
Mechanical Design
SolidWorks/SolidEdge, AutoCAD
Other
WebService (REST, JSON, XML)


Testing Actor Systems
As with any piece of software, automated tests are a very important part of the development cycle. The actor model presents a different view on how units of code are delimited and how they interact, which has an influence on how to perform tests.
Akka comes with a dedicated module akka-testkit for supporting tests at different levels, which fall into two clearly distinct categories:
- Testing isolated pieces of code without involving the actor model, meaning without multiple threads; this implies completely deterministic behavior concerning the ordering of events and no concurrency concerns and will be called Unit Testing in the following.
- Testing (multiple) encapsulated actors including multi-threaded scheduling; this implies non-deterministic order of events but shielding from concurrency concerns by the actor model and will be called Integration Testing in the following.
There are of course variations on the granularity of tests in both categories, where unit testing reaches down to white-box tests and integration testing can encompass functional tests of complete actor networks. The important distinction lies in whether concurrency concerns are part of the test or not. The tools offered are described in detail in the following sections.
Note
Be sure to add the module akka-testkit to your dependencies.
Synchronous Unit Testing with TestActorRef
Testing the business logic inside Actor classes can be divided into two parts: first, each atomic operation must work in isolation, then sequences of incoming events must be processed correctly, even in the presence of some possible variability in the ordering of events. The former is the primary use case for single-threaded unit testing, while the latter can only be verified in integration tests.
Normally, the ActorRef shields the underlying Actor instance from the outside, the only communications channel is the actor's mailbox. This restriction is an impediment to unit testing, which led to the inception of the TestActorRef. This special type of reference is designed specifically for test purposes and allows access to the actor in two ways: either by obtaining a reference to the underlying actor instance, or by invoking or querying the actor's behaviour (receive). Each one warrants its own section below.
Note
It is highly recommended to stick to traditional behavioural testing (using messaging to ask the Actor to reply with the state you want to run assertions against), instead of using TestActorRef whenever possible.
Warning
Due to the synchronous nature of TestActorRef it will not work with some support traits that Akka provides as they require asynchronous behaviours to function properly. Examples of traits that do not mix well with test actor refs are PersistentActor and AtLeastOnceDelivery provided by Akka Persistence.
Obtaining a Reference to an Actor
Having access to the actual Actor object allows application of all traditional unit testing techniques on the contained methods. Obtaining a reference is done like this:
import akka.testkit.TestActorRef
val actorRef = TestActorRef[MyActor]
val actor = actorRef.underlyingActor
Since TestActorRef is generic in the actor type it returns the underlying actor with its proper static type. From this point on you may bring any unit testing tool to bear on your actor as usual.
Testing Finite State Machines
If your actor under test is a FSM, you may use the special TestFSMRef which offers all features of a normal TestActorRef and in addition allows access to the internal state:
import akka.testkit.TestFSMRef
import akka.actor.FSM
import scala.concurrent.duration._
val fsm = TestFSMRef(new TestFsmActor)
val mustBeTypedProperly: TestActorRef[TestFsmActor] = fsm
assert(fsm.stateName == 1)
assert(fsm.stateData == "")
fsm ! "go" // being a TestActorRef, this runs also on the CallingThreadDispatcher
assert(fsm.stateName == 2)
assert(fsm.stateData == "go")
fsm.setState(stateName = 1)
assert(fsm.stateName == 1)
assert(fsm.isTimerActive("test") == false)
fsm.setTimer("test", 12, 10 millis, true)
assert(fsm.isTimerActive("test") == true)
fsm.cancelTimer("test")
assert(fsm.isTimerActive("test") == false)
Due to a limitation in Scala’s type inference, there is only the factory method shown above, so you will probably write code like TestFSMRef(new MyFSM) instead of the hypothetical ActorRef-inspired TestFSMRef[MyFSM]. All methods shown above directly access the FSM state without any synchronization; this is perfectly alright if the CallingThreadDispatcher is used and no other threads are involved, but it may lead to surprises if you were to actually exercise timer events, because those are executed on the Scheduler thread.
Testing the Actor's Behavior
When the dispatcher invokes the processing behavior of an actor on a message, it actually calls apply on the current behavior registered for the actor. This starts out with the return value of the declared receive method, but it may also be changed using become and unbecome in response to external messages. All of this contributes to the overall actor behavior and it does not lend itself to easy testing on the Actor itself. Therefore the TestActorRef offers a different mode of operation to complement the Actor testing: it supports all operations also valid on normal ActorRef. Messages sent to the actor are processed synchronously on the current thread and answers may be sent back as usual. This trick is made possible by the CallingThreadDispatcher described below (see CallingThreadDispatcher); this dispatcher is set implicitly for any actor instantiated into a TestActorRef.
import akka.testkit.TestActorRef
import scala.concurrent.duration._
import scala.concurrent.Await
import akka.pattern.ask
val actorRef = TestActorRef(new MyActor)
// hypothetical message stimulating a '42' answer
val future = actorRef ? Say42
val Success(result: Int) = future.value.get
result should be(42)
As the TestActorRef is a subclass of LocalActorRef with a few special extras, also aspects like supervision and restarting work properly, but beware that execution is only strictly synchronous as long as all actors involved use the CallingThreadDispatcher. As soon as you add elements which include more sophisticated scheduling you leave the realm of unit testing as you then need to think about asynchronicity again (in most cases the problem will be to wait until the desired effect had a chance to happen).
One more special aspect which is overridden for single-threaded tests is the receiveTimeout, as including that would entail asynchronous queuing of ReceiveTimeout messages, violating the synchronous contract.
Note
To summarize: TestActorRef overwrites two fields: it sets the dispatcher to CallingThreadDispatcher.global and it sets the receiveTimeout to None.
The Way In-Between: Expecting Exceptions
If you want to test the actor behavior, including hotswapping, but without involving a dispatcher and without having the TestActorRef swallow any thrown exceptions, then there is another mode available for you: just use the receive method on TestActorRef, which will be forwarded to the underlying actor:
import akka.testkit.TestActorRef
val actorRef = TestActorRef(new Actor {
def receive = {
case "hello" => throw new IllegalArgumentException("boom")
}
})
intercept[IllegalArgumentException] { actorRef.receive("hello") }
Use Cases
You may of course mix and match both modi operandi of TestActorRef as suits your test needs:
- one common use case is setting up the actor into a specific internal state before sending the test message
- another is to verify correct internal state transitions after having sent the test message
Feel free to experiment with the possibilities, and if you find useful patterns, don't hesitate to let the Akka forums know about them! Who knows, common operations might even be worked into nice DSLs.
Asynchronous Integration Testing with TestKit
When you are reasonably sure that your actor's business logic is correct, the next step is verifying that it works correctly within its intended environment (if the individual actors are simple enough, possibly because they use the FSM module, this might also be the first step). The definition of the environment depends of course very much on the problem at hand and the level at which you intend to test, ranging for functional/integration tests to full system tests. The minimal setup consists of the test procedure, which provides the desired stimuli, the actor under test, and an actor receiving replies. Bigger systems replace the actor under test with a network of actors, apply stimuli at varying injection points and arrange results to be sent from different emission points, but the basic principle stays the same in that a single procedure drives the test.
The TestKit class contains a collection of tools which makes this common task easy.
import akka.actor.ActorSystem
import akka.actor.Actor
import akka.actor.Props
import akka.testkit.{ TestActors, TestKit, ImplicitSender }
import org.scalatest.WordSpecLike
import org.scalatest.Matchers
import org.scalatest.BeforeAndAfterAll
class MySpec() extends TestKit(ActorSystem("MySpec")) with ImplicitSender
with WordSpecLike with Matchers with BeforeAndAfterAll {
override def afterAll {
TestKit.shutdownActorSystem(system)
}
"An Echo actor" must {
"send back messages unchanged" in {
val echo = system.actorOf(TestActors.echoActorProps)
echo ! "hello world"
expectMsg("hello world")
}
}
}
The TestKit contains an actor named testActor which is the entry point for messages to be examined with the various expectMsg... assertions detailed below. When mixing in the trait ImplicitSender this test actor is implicitly used as sender reference when dispatching messages from the test procedure. The testActor may also be passed to other actors as usual, usually subscribing it as notification listener. There is a whole set of examination methods, e.g. receiving all consecutive messages matching certain criteria, receiving a whole sequence of fixed messages or classes, receiving nothing for some time, etc.
The ActorSystem passed in to the constructor of TestKit is accessible via the system member. Remember to shut down the actor system after the test is finished (also in case of failure) so that all actors—including the test actor—are stopped.
Built-In Assertions
The above mentioned expectMsg is not the only method for formulating assertions concerning received messages. Here is the full list:
expectMsg[T](d: Duration, msg: T): T
The given message object must be received within the specified time; the object will be returned.
expectMsgPF[T](d: Duration)(pf: PartialFunction[Any, T]): T
Within the given time period, a message must be received and the given partial function must be defined for that message; the result from applying the partial function to the received message is returned. The duration may be left unspecified (empty parentheses are required in this case) to use the deadline from the innermost enclosing within block instead.
expectMsgClass[T](d: Duration, c: Class[T]): T
An object which is an instance of the given Class must be received within the allotted time frame; the object will be returned. Note that this does a conformance check; if you need the class to be equal, have a look at expectMsgAllClassOf with a single given class argument.
expectMsgType[T: Manifest](d: Duration)
An object which is an instance of the given type (after erasure) must be received within the allotted time frame; the object will be returned. This method is approximately equivalent to expectMsgClass(implicitly[ClassTag[T]].runtimeClass).
expectMsgAnyOf[T](d: Duration, obj: T*): T
An object must be received within the given time, and it must be equal ( compared with ==) to at least one of the passed reference objects; the received object will be returned.
expectMsgAnyClassOf[T](d: Duration, obj: Class[_ <: T]*): T
An object must be received within the given time, and it must be an instance of at least one of the supplied Class objects; the received object will be returned.
expectMsgAllOf[T](d: Duration, obj: T*): Seq[T]
A number of objects matching the size of the supplied object array must be received within the given time, and for each of the given objects there must exist at least one among the received ones which equals (compared with ==) it. The full sequence of received objects is returned.
expectMsgAllClassOf[T](d: Duration, c: Class[_ <: T]*): Seq[T]
A number of objects matching the size of the supplied Class array must be received within the given time, and for each of the given classes there must exist at least one among the received objects whose class equals (compared with ==) it (this is not a conformance check). The full sequence of received objects is returned.
expectMsgAllConformingOf[T](d: Duration, c: Class[_ <: T]*): Seq[T]
A number of objects matching the size of the supplied Class array must be received within the given time, and for each of the given classes there must exist at least one among the received objects which is an instance of this class. The full sequence of received objects is returned.
expectNoMsg(d: Duration)
No message must be received within the given time. This also fails if a message has been received before calling this method which has not been removed from the queue using one of the other methods.
receiveN(n: Int, d: Duration): Seq[AnyRef]
n messages must be received within the given time; the received messages are returned.
fishForMessage(max: Duration, hint: String)(pf: PartialFunction[Any, Boolean]): Any
Keep receiving messages as long as the time is not used up and the partial function matches and returns false. Returns the message received for which it returned true or throws an exception, which will include the provided hint for easier debugging.
In addition to message reception assertions there are also methods which help with message flows:
receiveOne(d: Duration): AnyRef
Tries to receive one message for at most the given time interval and returns null in case of failure. If the given Duration is zero, the call is non-blocking (polling mode).
receiveWhile[T](max: Duration, idle: Duration, messages: Int)(pf: PartialFunction[Any, T]): Seq[T]
Collect messages as long as
- they are matching the given partial function
- the given time interval is not used up
- the next message is received within the idle timeout
- the number of messages has not yet reached the maximum
All collected messages are returned. The maximum duration defaults to the time remaining in the innermost enclosing within block and the idle duration defaults to infinity (thereby disabling the idle timeout feature). The number of expected messages defaults to Int.MaxValue, which effectively disables this limit.
awaitCond(p: => Boolean, max: Duration, interval: Duration)
Poll the given condition every interval until it returns true or the max duration is used up. The interval defaults to 100 ms and the maximum defaults to the time remaining in the innermost enclosing within block.
awaitAssert(a: => Any, max: Duration, interval: Duration)
Poll the given assert function every interval until it does not throw an exception or the max duration is used up. If the timeout expires the last exception is thrown. The interval defaults to 100 ms and the maximum defaults to the time remaining in the innermost enclosing within block.The interval defaults to 100 ms and the maximum defaults to the time remaining in the innermost enclosing within block.
ignoreMsg(pf: PartialFunction[AnyRef, Boolean])
ignoreNoMsg
The internal testActor contains a partial function for ignoring messages: it will only enqueue messages which do not match the function or for which the function returns false. This function can be set and reset using the methods given above; each invocation replaces the previous function, they are not composed.
This feature is useful e.g. when testing a logging system, where you want to ignore regular messages and are only interested in your specific ones.
Expecting Log Messages
Since an integration test does not allow to the internal processing of the participating actors, verifying expected exceptions cannot be done directly. Instead, use the logging system for this purpose: replacing the normal event handler with the TestEventListener and using an EventFilter allows assertions on log messages, including those which are generated by exceptions:
import akka.testkit.EventFilter
import com.typesafe.config.ConfigFactory
implicit val system = ActorSystem("testsystem", ConfigFactory.parseString("""
akka.loggers = ["akka.testkit.TestEventListener"]
"""))
try {
val actor = system.actorOf(Props.empty)
EventFilter[ActorKilledException](occurrences = 1) intercept {
actor ! Kill
}
} finally {
shutdown(system)
}
If a number of occurrences is specific—as demonstrated above—then intercept will block until that number of matching messages have been received or the timeout configured in akka.test.filter-leeway is used up (time starts counting after the passed-in block of code returns). In case of a timeout the test fails.
Note
Be sure to exchange the default logger with the TestEventListener in your application.conf to enable this function:
akka.loggers = [akka.testkit.TestEventListener]
Timing Assertions
Another important part of functional testing concerns timing: certain events must not happen immediately (like a timer), others need to happen before a deadline. Therefore, all examination methods accept an upper time limit within the positive or negative result must be obtained. Lower time limits need to be checked external to the examination, which is facilitated by a new construct for managing time constraints:
within([min, ]max) {
...
}
The block given to within must complete after a Duration which is between min and max, where the former defaults to zero. The deadline calculated by adding the max parameter to the block's start time is implicitly available within the block to all examination methods, if you do not specify it, it is inherited from the innermost enclosing within block.
It should be noted that if the last message-receiving assertion of the block is expectNoMsg or receiveWhile, the final check of the within is skipped in order to avoid false positives due to wake-up latencies. This means that while individual contained assertions still use the maximum time bound, the overall block may take arbitrarily longer in this case.
import akka.actor.Props
import scala.concurrent.duration._
val worker = system.actorOf(Props[Worker])
within(200 millis) {
worker ! "some work"
expectMsg("some result")
expectNoMsg // will block for the rest of the 200ms
Thread.sleep(300) // will NOT make this block fail
}
Note
All times are measured using System.nanoTime, meaning that they describe wall time, not CPU time.
Ray Roestenburg has written a great article on using the TestKit: http://roestenburg.agilesquad.com/2011/02/unit-testing-akka-actors-with-testkit_12.html. His full example is also available here.
Accounting for Slow Test Systems
The tight timeouts you use during testing on your lightning-fast notebook will invariably lead to spurious test failures on the heavily loaded Jenkins server (or similar). To account for this situation, all maximum durations are internally scaled by a factor taken from the Configuration, akka.test.timefactor, which defaults to 1.
You can scale other durations with the same factor by using the implicit conversion in akka.testkit package object to add dilated function to Duration.
import scala.concurrent.duration._
import akka.testkit._
10.milliseconds.dilated
Resolving Conflicts with Implicit ActorRef
If you want the sender of messages inside your TestKit-based tests to be the testActor simply mix in ImplicitSender into your test.
class MySpec() extends TestKit(ActorSystem("MySpec")) with ImplicitSender
with WordSpecLike with Matchers with BeforeAndAfterAll {
Using Multiple Probe Actors
When the actors under test are supposed to send various messages to different destinations, it may be difficult distinguishing the message streams arriving at the testActor when using the TestKit as a mixin. Another approach is to use it for creation of simple probe actors to be inserted in the message flows. To make this more powerful and convenient, there is a concrete implementation called TestProbe. The functionality is best explained using a small example:
import scala.concurrent.duration._
import scala.concurrent.Future
import akka.actor._
import akka.testkit.TestProbe
class MyDoubleEcho extends Actor {
var dest1: ActorRef = _
var dest2: ActorRef = _
def receive = {
case (d1: ActorRef, d2: ActorRef) =>
dest1 = d1
dest2 = d2
case x =>
dest1 ! x
dest2 ! x
}
}
val probe1 = TestProbe()
val probe2 = TestProbe()
val actor = system.actorOf(Props[MyDoubleEcho])
actor ! ((probe1.ref, probe2.ref))
actor ! "hello"
probe1.expectMsg(500 millis, "hello")
probe2.expectMsg(500 millis, "hello")
Here a the system under test is simulated by MyDoubleEcho, which is supposed to mirror its input to two outputs. Attaching two test probes enables verification of the (simplistic) behavior. Another example would be two actors A and B which collaborate by A sending messages to B. In order to verify this message flow, a TestProbe could be inserted as target of A, using the forwarding capabilities or auto-pilot described below to include a real B in the test setup.
If you have many test probes, you can name them to get meaningful actor names in test logs and assertions:
val worker = TestProbe("worker")
val aggregator = TestProbe("aggregator")
worker.ref.path.name should startWith("worker")
aggregator.ref.path.name should startWith("aggregator")
Probes may also be equipped with custom assertions to make your test code even more concise and clear:
final case class Update(id: Int, value: String)
val probe = new TestProbe(system) {
def expectUpdate(x: Int) = {
expectMsgPF() {
case Update(id, _) if id == x => true
}
sender() ! "ACK"
}
}
You have complete flexibility here in mixing and matching the TestKit facilities with your own checks and choosing an intuitive name for it. In real life your code will probably be a bit more complicated than the example given above; just use the power!
Warning
Any message send from a TestProbe to another actor which runs on the CallingThreadDispatcher runs the risk of dead-lock, if that other actor might also send to this probe. The implementation of TestProbe.watch and TestProbe.unwatch will also send a message to the watchee, which means that it is dangerous to try watching e.g. TestActorRef from a TestProbe.
Watching Other Actors from Probes
A TestProbe can register itself for DeathWatch of any other actor:
val probe = TestProbe()
probe watch target
target ! PoisonPill
probe.expectTerminated(target)
Replying to Messages Received by Probes
The probes keep track of the communications channel for replies, if possible, so they can also reply:
val probe = TestProbe()
val future = probe.ref ? "hello"
probe.expectMsg(0 millis, "hello") // TestActor runs on CallingThreadDispatcher
probe.reply("world")
assert(future.isCompleted && future.value == Some(Success("world")))
Forwarding Messages Received by Probes
Given a destination actor dest which in the nominal actor network would receive a message from actor source. If you arrange for the message to be sent to a TestProbe probe instead, you can make assertions concerning volume and timing of the message flow while still keeping the network functioning:
class Source(target: ActorRef) extends Actor {
def receive = {
case "start" => target ! "work"
}
}
class Destination extends Actor {
def receive = {
case x => // Do something..
}
}
val probe = TestProbe()
val source = system.actorOf(Props(classOf[Source], probe.ref))
val dest = system.actorOf(Props[Destination])
source ! "start"
probe.expectMsg("work")
probe.forward(dest)
The dest actor will receive the same message invocation as if no test probe had intervened.
Auto-Pilot
Receiving messages in a queue for later inspection is nice, but in order to keep a test running and verify traces later you can also install an AutoPilot in the participating test probes (actually in any TestKit) which is invoked before enqueueing to the inspection queue. This code can be used to forward messages, e.g. in a chain A --> Probe --> B, as long as a certain protocol is obeyed.
val probe = TestProbe()
probe.setAutoPilot(new TestActor.AutoPilot {
def run(sender: ActorRef, msg: Any): TestActor.AutoPilot =
msg match {
case "stop" ⇒ TestActor.NoAutoPilot
case x ⇒ testActor.tell(x, sender); TestActor.KeepRunning
}
})
The run method must return the auto-pilot for the next message, which may be KeepRunning to retain the current one or NoAutoPilot to switch it off.
Caution about Timing Assertions
The behavior of within blocks when using test probes might be perceived as counter-intuitive: you need to remember that the nicely scoped deadline as described above is local to each probe. Hence, probes do not react to each other's deadlines or to the deadline set in an enclosing TestKit instance:
val probe = TestProbe()
within(1 second) {
probe.expectMsg("hello")
}
Here, the expectMsg call will use the default timeout.
Testing parent-child relationships
The parent of an actor is always the actor that created it. At times this leads to a coupling between the two that may not be straightforward to test. There are several approaches to improve testability of a child actor that needs to refer to its parent:
- when creating a child, pass an explicit reference to its parent
- create the child with a TestProbe as parent
- create a fabricated parent when testing
Conversely, a parent's binding to its child can be lessened as follows:
- when creating a parent, tell the parent how to create its child
For example, the structure of the code you want to test may follow this pattern:
class Parent extends Actor {
val child = context.actorOf(Props[Child], "child")
var ponged = false
def receive = {
case "pingit" => child ! "ping"
case "pong" => ponged = true
}
}
class Child extends Actor {
def receive = {
case "ping" => context.parent ! "pong"
}
}
Introduce child to its parent
The first option is to avoid use of the context.parent function and create a child with a custom parent by passing an explicit reference to its parent instead.
class DependentChild(parent: ActorRef) extends Actor {
def receive = {
case "ping" => parent ! "pong"
}
}
Create the child using TestProbe
The TestProbe class can in fact create actors that will run with the test probe as parent. This will cause any messages the the child actor sends to context.parent to end up in the test probe.
"A TestProbe serving as parent" should {
"test its child responses" in {
val parent = TestProbe()
val child = parent.childActorOf(Props[Child])
parent.send(child, "ping")
parent.expectMsg("pong")
}
}
Using a fabricated parent
If you prefer to avoid modifying the parent or child constructor you can create a fabricated parent in your test. This, however, does not enable you to test the parent actor in isolation.
"A fabricated parent" should {
"test its child responses" in {
val proxy = TestProbe()
val parent = system.actorOf(Props(new Actor {
val child = context.actorOf(Props[Child], "child")
def receive = {
case x if sender == child => proxy.ref forward x
case x => child forward x
}
}))
proxy.send(parent, "ping")
proxy.expectMsg("pong")
}
}
Externalize child making from the parent
Alternatively, you can tell the parent how to create its child. There are two ways to do this: by giving it a Props object or by giving it a function which takes care of creating the child actor:
class DependentParent(childProps: Props) extends Actor {
val child = context.actorOf(childProps, "child")
var ponged = false
def receive = {
case "pingit" => child ! "ping"
case "pong" => ponged = true
}
}
class GenericDependentParent(childMaker: ActorRefFactory => ActorRef) extends Actor {
val child = childMaker(context)
var ponged = false
def receive = {
case "pingit" => child ! "ping"
case "pong" => ponged = true
}
}
Creating the Props is straightforward and the function may look like this in your test code:
val maker = (_: ActorRefFactory) => probe.ref
val parent = system.actorOf(Props(classOf[GenericDependentParent], maker))
And like this in your application code:
val maker = (f: ActorRefFactory) => f.actorOf(Props[Child])
val parent = system.actorOf(Props(classOf[GenericDependentParent], maker))
Which of these methods is the best depends on what is most important to test. The most generic option is to create the parent actor by passing it a function that is responsible for the Actor creation, but the fabricated parent is often sufficient.
CallingThreadDispatcher
The CallingThreadDispatcher serves good purposes in unit testing, as described above, but originally it was conceived in order to allow contiguous stack traces to be generated in case of an error. As this special dispatcher runs everything which would normally be queued directly on the current thread, the full history of a message's processing chain is recorded on the call stack, so long as all intervening actors run on this dispatcher.
How to use it
Just set the dispatcher as you normally would:
import akka.testkit.CallingThreadDispatcher
val ref = system.actorOf(Props[MyActor].withDispatcher(CallingThreadDispatcher.Id))
How it works
When receiving an invocation, the CallingThreadDispatcher checks whether the receiving actor is already active on the current thread. The simplest example for this situation is an actor which sends a message to itself. In this case, processing cannot continue immediately as that would violate the actor model, so the invocation is queued and will be processed when the active invocation on that actor finishes its processing; thus, it will be processed on the calling thread, but simply after the actor finishes its previous work. In the other case, the invocation is simply processed immediately on the current thread. Futures scheduled via this dispatcher are also executed immediately.
This scheme makes the CallingThreadDispatcher work like a general purpose dispatcher for any actors which never block on external events.
In the presence of multiple threads it may happen that two invocations of an actor running on this dispatcher happen on two different threads at the same time. In this case, both will be processed directly on their respective threads, where both compete for the actor's lock and the loser has to wait. Thus, the actor model is left intact, but the price is loss of concurrency due to limited scheduling. In a sense this is equivalent to traditional mutex style concurrency.
The other remaining difficulty is correct handling of suspend and resume: when an actor is suspended, subsequent invocations will be queued in thread-local queues (the same ones used for queuing in the normal case). The call to resume, however, is done by one specific thread, and all other threads in the system will probably not be executing this specific actor, which leads to the problem that the thread-local queues cannot be emptied by their native threads. Hence, the thread calling resume will collect all currently queued invocations from all threads into its own queue and process them.
Limitations
Warning
In case the CallingThreadDispatcher is used for top-level actors, but without going through TestActorRef, then there is a time window during which the actor is awaiting construction by the user guardian actor. Sending messages to the actor during this time period will result in them being enqueued and then executed on the guardian’s thread instead of the caller’s thread. To avoid this, use TestActorRef.
If an actor's behavior blocks on a something which would normally be affected by the calling actor after having sent the message, this will obviously dead-lock when using this dispatcher. This is a common scenario in actor tests based on CountDownLatch for synchronization:
val latch = new CountDownLatch(1)
actor ! startWorkAfter(latch) // actor will call latch.await() before proceeding
doSomeSetupStuff()
latch.countDown()
The example would hang indefinitely within the message processing initiated on the second line and never reach the fourth line, which would unblock it on a normal dispatcher.
Thus, keep in mind that the CallingThreadDispatcher is not a general-purpose replacement for the normal dispatchers. On the other hand it may be quite useful to run your actor network on it for testing, because if it runs without dead-locking chances are very high that it will not dead-lock in production.
Warning
The above sentence is unfortunately not a strong guarantee, because your code might directly or indirectly change its behavior when running on a different dispatcher. If you are looking for a tool to help you debug dead-locks, the CallingThreadDispatcher may help with certain error scenarios, but keep in mind that it has may give false negatives as well as false positives.
Thread Interruptions
If the CallingThreadDispatcher sees that the current thread has its isInterrupted() flag set when message processing returns, it will throw an InterruptedException after finishing all its processing (i.e. all messages which need processing as described above are processed before this happens). As tell cannot throw exceptions due to its contract, this exception will then be caught and logged, and the thread’s interrupted status will be set again.
If during message processing an InterruptedException is thrown then it will be caught inside the CallingThreadDispatcher’s message handling loop, the thread’s interrupted flag will be set and processing continues normally.
Note
The summary of these two paragraphs is that if the current thread is interrupted while doing work under the CallingThreadDispatcher, then that will result in the isInterrupted flag to be true when the message send returns and no InterruptedException will be thrown.
Benefits
To summarize, these are the features with the CallingThreadDispatcher has to offer:
- Deterministic execution of single-threaded tests while retaining nearly full actor semantics
- Full message processing history leading up to the point of failure in exception stack traces
- Exclusion of certain classes of dead-lock scenarios
Tracing Actor Invocations
The testing facilities described up to this point were aiming at formulating assertions about a system’s behavior. If a test fails, it is usually your job to find the cause, fix it and verify the test again. This process is supported by debuggers as well as logging, where the Akka toolkit offers the following options:
Logging of exceptions thrown within Actor instances
This is always on; in contrast to the other logging mechanisms, this logs at ERROR level.
Logging of message invocations on certain actors
This is enabled by a setting in the Configuration — namely akka.actor.debug.receive — which enables the loggable statement to be applied to an actor’s receive function:
import akka.event.LoggingReceive
def receive = LoggingReceive {
case msg => // Do something ...
}
def otherState: Receive = LoggingReceive.withLabel("other") {
case msg => // Do something else ...
}
If the aforementioned setting is not given in the Configuration, this method will pass through the given Receive function unmodified, meaning that there is no runtime cost unless actually enabled.
The logging feature is coupled to this specific local mark-up because enabling it uniformly on all actors is not usually what you need, and it would lead to endless loops if it were applied to event bus logger listeners.
Logging of special messages
Actors handle certain special messages automatically, e.g. Kill, PoisonPill, etc. Tracing of these message invocations is enabled by the setting akka.actor.debug.autoreceive, which enables this on all actors.
Logging of the actor lifecycle
Actor creation, start, restart, monitor start, monitor stop and stop may be traced by enabling the setting akka.actor.debug.lifecycle; this, too, is enabled uniformly on all actors.
All these messages are logged at DEBUG level. To summarize, you can enable full logging of actor activities using this configuration fragment:
akka {
loglevel = "DEBUG"
actor {
debug {
receive = on
autoreceive = on
lifecycle = on
}
}
}
Different Testing Frameworks
Akka’s own test suite is written using ScalaTest, which also shines through in documentation examples. However, the TestKit and its facilities do not depend on that framework, you can essentially use whichever suits your development style best.
This section contains a collection of known gotchas with some other frameworks, which is by no means exhaustive and does not imply endorsement or special support.
When you need it to be a trait
If for some reason it is a problem to inherit from TestKit due to it being a concrete class instead of a trait, there’s TestKitBase:
import akka.testkit.TestKitBase
class MyTest extends TestKitBase {
implicit lazy val system = ActorSystem()
// put your test code here ...
shutdown(system)
}
The implicit lazy val system must be declared exactly like that (you can of course pass arguments to the actor system factory as needed) because trait TestKitBase needs the system during its construction.
Warning
Use of the trait is discouraged because of potential issues with binary backwards compatibility in the future, use at own risk.
Specs2
Some Specs2 users have contributed examples of how to work around some clashes which may arise:
- Mixing TestKit into org.specs2.mutable.Specification results in a name clash involving the end method (which is a private variable in TestKit and an abstract method in Specification); if mixing in TestKit first, the code may compile but might then fail at runtime. The work-around—which is actually beneficial also for the third point—is to apply the TestKit together with org.specs2.specification.Scope.
- The Specification traits provide a Duration DSL which uses partly
the same method names as scala.concurrent.duration.Duration, resulting in ambiguous
implicits if scala.concurrent.duration._ is imported. There are two workarounds:
- either use the Specification variant of Duration and supply an implicit conversion to the Akka Duration. This conversion is not supplied with the Akka distribution because that would mean that our JAR files would depend on Specs2, which is not justified by this little feature.
- or mix org.specs2.time.NoTimeConversions into the Specification.
- Specifications are by default executed concurrently, which requires some care when writing the tests or alternatively the sequential keyword.
Configuration
There are several configuration properties for the TestKit module, please refer to the reference configuration.
Contents


Mobile Software Engineer, Living in Brisbane, Australia. Most experienced in Native iOS development but have a keen interest in everything Mobile. I have worked for Australia's #1 mobile development shop and have been part of some of the biggest apps in Australia.
Started developing iOS apps in 2011 for iOS 3, apps that I have been involved in have been installed on 1 in 3 iPhones in Australia. Here is some of my best work. Some of these applications have been nominated or won design awards.