text
stringlengths 20
1.01M
| url
stringlengths 14
1.25k
| dump
stringlengths 9
15
⌀ | lang
stringclasses 4
values | source
stringclasses 4
values |
|---|---|---|---|---|
Content-type: text/html
XmTextFieldShowPosition - A TextField function that forces text at a given position to be displayed
#include <Xm/TextF.h>
void XmTextFieldShowPosition (widget, position)
Widget widget;
XmTextPosition position;
XmTextFieldShowPosition forces text at the specified position to be displayed. If the XmNautoShowCursorPosition resource is True, the application should also set the insert cursor to this position. Specifies the TextField widget ID Specifies the character position to be displayed. This is an integer number of characters from the beginning of the text buffer. The first character position is 0.
For a complete definition of TextField and its associated resources,
see
XmTextField(3X).
XmTextField(3X)
|
https://backdrift.org/man/tru64/man3/XmTextFieldShowPosition.3X.html
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
Set-Dfsn
Server Configuration
Syntax
Set-DfsnServerConfiguration [-ComputerName] <String> [[-SyncIntervalSec] <UInt32>] [[-EnableSiteCostedReferrals] <Boolean>] [[-EnableInsiteReferrals] <Boolean>] [[-LdapTimeoutSec] <UInt32>] [[-PreferLogonDC] <Boolean>] [[-UseFqdn] <Boolean>] [-CimSession <CimSession[]>] [-ThrottleLimit <Int32>] [-AsJob] [-WhatIf] [-Confirm] [<CommonParameters>]
Description
The Set-DfsnServerConfiguration cmdlet changes settings for a Distributed File System (DFS) namespace root server. A DFS namespace root server hosts one or more namespace root targets.
You can use this cmdlet to enable in-site referrals or to use cost in organizing referrals for targets in a site. You can also change the synchronization interval for servers that connect to a primary domain controller (PDC) emulator and change the Lightweight Directory Access Protocol (LDAP) time-out. You can specify whether referrals prefer the logon domain controller. You can also specify whether the server provides referrals as fully qualified domain names (FQDN) or NETBios names.
To see current values for these settings, use the Get-DfsnServerConfiguration cmdlet.
Examples
Example 1: Set LDAP time-out for a DFS namespace server
PS C:\> Set-DfsnServerConfiguration -ComputerName "localhost" -LdapTimeoutSec 60
This command sets an LDAP time-out value of 60 seconds for the local computer, which is a DFS namespace server.
Required Parameters
Specifies the host name or FQDN for the DFS namespace server for which the cmdlet modifies settings. whether this server provides only in-site referrals. If you assign a value of $True, the server returns only referrals for targets in the same site as the client. If you assign a value of $False, the server returns in-site referrals and other referrals.
Indicates whether the server can use cost-based selection. If you specify a value of $True, the DFS namespace server provides referrals for folder targets to clients in the following order:
- Folder targets in the same site as a client, in random order.
- Folder targets for which the DFS namespace server has information. The referrals for the nearest site are first, in random order, followed by the next nearest site, in random order.
- Targets for which DFS namespace server has no site information, in random order.
If you specify a value of $False, the DFS namespace server provides referrals for folder targets to clients in the following order:
- Folder targets in the same site as the client, in random order.
- Other folder targets, in random order.
Specifies a time-out value, in seconds, for Lightweight Directory Access Protocol (LDAP) requests for the DFS namespace server.
Indicates whether to prefer the logon domain controller in referrals. If you specify a value of $True for this parameter, the DFS namespace server places referrals to the computer that hosts the logon domain controller at the top of the list of referrals.
Specifies an interval, in seconds. This interval controls how often domain-based DFS namespace root servers and domain controllers connect to the PDC emulator to get updates of DFS namespace metadata..
Indicates whether a DFS namespace server uses FQDNs in referrals. If this parameter has a value of $True, the server uses FQDNs in referrals. If this parameter has a value of $False, the server uses NetBIOS names. The default for DFS namespace servers is to use NetBIOS names in referrals.
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Outputs
Microsoft.Management.Infrastructure.CimInstance#MSFT_DfsNamespaceServerConfig
|
https://docs.microsoft.com/en-us/powershell/module/dfsn/set-dfsnserverconfiguration?view=win10-ps
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
RationalWiki:Bots
Bots (short for "robots") are (usually small) computer programs/scripts created to perform repetitive tasks or to ease routine maintenance of a website.
On wikis Bot is a class of user which is usually such a program, although some users have Bot alteregos so that repetitive tasks won't clog up Special:RecentChanges.
A current list of RW's bots can be found here (there are 47). Any of these which are generally applicable should have usage instructions on their user page.
Contents
Active bots[edit]
Archivist[edit]
Archives talkpages. See userpage for full instructions and details -- including how to run it, if FuzzyCatPotato ever disappears.
Old bots[edit]
How to make your own[edit]
You can talk to the API at. See the MediaWiki help pages.
Pywikibot[edit]
It's probably easiest to use a framework like Pywikibot. You want to use the new "core" version, not the old "compat".
Getting started[edit]
Follow the installation instructions to install Pywikibot & dependencies (note: some systems also have packages for Pywikibot: [1] [2]).
Now create the
rationalwiki family; this will tell Pywikibot how to interact with the RationalWiki API:
python3.4 generate_family_file.py rationalwiki
will give you a family file in
pywikibot/families/rationalwiki_family.py. The default will do fine for most cases.
You'll need to edit the
user-config.py:
mylang = 'en' family = 'rationalwiki' usernames['rationalwiki']['en'] = 'MummificationBot'
Finally, test your setup with
python pwb.py login, which should prompt for the login password for your bot, and then output
Logged in on somewiki:lang as bot username. The password should be remembered.
Multiple accounts[edit]
Pywikibot only supports a single account name; for separate accounts you could use something along the lines of this in your
user-config.py:
import os, sys mylang = 'en' family = 'rationalwiki' user = os.getenv('RW_USER')
valid = { 'MummificationBot': 'store password here if you want', 'RedirectBot': 'store password here if you want', } if user not in valid.keys(): print('No such user; valid users: {}'.format(valid.keys())) sys.exit(1) print(user) usernames['rationalwiki']['en'] = user del user del valid
Now just set the
RW_USER environment variable before running the script:
RW_USER=MummificationBot python pwb.py login
An alternative is using separate Pywikibot directories (this is the documented way, but a bit silly).
|
https://rationalwiki.org/wiki/RationalWiki:Bots
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
On Fri, Sep 21, 2007 at 10:45:14PM +0200, Andi Kleen wrote:> From: Mike Frysinger <vapier@gentoo.org>> > This brings x86_64 into line with all other architectures by only defining> cond_syscall() when __KERNEL__ is defined.> > Signed-off-by: Mike Frysinger <vapier@gentoo.org>> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>> Signed-off-by: Andi Kleen <ak@suse.de>> Index: linux/include/asm-x86_64/unistd.h> ===================================================================> --- linux.orig/include/asm-x86_64/unistd.h> +++ linux/include/asm-x86_64/unistd.h> @@ -676,6 +676,7 @@ asmlinkage long sys_rt_sigaction(int sig> #endif /* __KERNEL__ */This is the previous __KERNEL__ block.> #endif /* __NO_STUBS */And this one shouldn't extent iver the declarations of sys_iopland sys_rt_sigactions I think. If it should be there at all.So please make this file at least semi-clean while you're at it insteadof much worse.The __KERNEL__ block should also be extended over the various __ARCH_WANT_definitions because they're not for userspace at all.-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
|
http://lkml.org/lkml/2007/9/22/46
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
Affine transforms consist of 6 numbers which are typically represented in a 3x3 matrix where multiplying the transform T by the vector V results in V'.
[V'] = [T][V] or [x'] [m00 m01 m02] [x] [m00x + m01y + m02] [y'] = [m10 m11 m12] [y] = [m10x + m11y + m12] [1 ] [ 0 0 1] [1] [1]The documentation for ZTransformGroup explains affine transforms in more detail. ZTransformGroup has several methods for modifying aspects of the transform, such as scale, rotate, and translate. It is also possible to animate those changes over time with those methods - or to specify the new transform with a standard Java2D AffineTransform.
In Jazz, ZVisualComponent which is used to represent visual elements, do not have the ability to be transformed. Instead, a transform node must be inserted above the node that contains the visual component. The transform applies to the entire subtree of that node. So, if there are several children of that node, a single transform node will apply to all of those children. Note that a single visual component can be reused in several places in the scenegraph. If those places are each transformed differently, a single visual component can appear in multiple places.
There are two equally valid ways of thinking about the effects of transforms. The first (and typical) way of thinking about transforms is that the transform changes the place within the global coordinate system that the affected objects appear at. For instance, if you have a transform node 'transformNode', and you call:
transformNode.translate(50.0f, 0.0f);The result is that the children of 'transformNode' (and their descendants) all get translated 50 units to the right.
Alternatively, you can think of transforms as representing nested coordinate systems. Then, that same call to translate would result in 'transformNode' being associated with a new coordinate system that is shifted 50 units to the right of the global coordinate system. Then, the visual component associated with transformNode and all of its children would appear at their normal places within the new coordinate system, but to find out where those objects are in global coordinates, you would have to transform the local coordinate system to global coordinates.
Jazz has several utility methods for converting between different coordinate systems. By definition, we say that the root of the Jazz scenegraph is in global coordinates. Every other node is in its own local coordinate system. These utility methods (such as ZNode.localToGlobal and ZNode.globalToLocal) convert points and rectangles from one coordinate system to the other.
The key thing to keep in mind here is that transforming internal nodes have the effect of moving objects within the scenegraph while transforming the camera doesn't affect the scenegraph, but instead changes where a particular camera looks onto the world represented by the scenegraph.
To support applications in managing these sets of nodes, Jazz has a utility called an "editor" that manages these "edit groups". Lets start by thinking about a single node that an application knows about and wants to manipulate. The application first decides that it wants to add a transform to that node. It does this by getting the editor for that node, and requesting a transform:
ZTransformGroup transformNode = node.editor().getTransformGroup();This will create a new transform node, and insert it above the node. Editors are careful in managing these extra nodes, and the next time you ask for the transform of that node, it will return the same transform. We use the terminology that the node that we start with is called the "primary node", all the extra nodes that are created by the editor are called "edit nodes", and the collection of primary and edit nodes altogether are called an "edit group". Given any member of an edit group, you can access the primary node with editor.getNode(), and you can access the top-most member of the edit group with editor.getTop().
The editor manages these edit nodes types:
Jazz provides a default editor with ZSceneGraphEditor. An instance of the editor is created whenever node.editor() is called. However, an application can extend or change the definition of th editor by specifying that a different editor should be used. This is done by defining an application-specific editor, and calling the static method ZNode.setEditorFactory(), and specifying a factory that creates that special editor.
Finally, the visual element is responsible for creating itself and for supporting manipulation of itself. We must look at the details of manipulating an object in some detail. This is because Jazz determines when to render an component based on its bounds, and because components are responsible for indicating to Jazz when they have changed through the repaint() and reshape() methods.
Every visual component must maintain a "model", or an internal data structure that represents the object. For a circle, this may be as simple as a center point, radius, and pen color. For other objects, the model may be more complex. Typical components will support methods that modify itself. The circle may have methods, for instance, to modify its pen width or pen color. It is the responsibility of these methods to indicate they have changed by calling repaint() if the object needs repainting, but the bounds have not changed (i.e., see ZCircle.setPenColor below) - or by calling reshape() if their bounds have changed (i.e., see ZCircle.setPenWidth below).
import java.awt.*; import java.awt.geom.*; import edu.umd.cs.jazz.*; import edu.umd.cs.jazz.util.*; public class ZCircle extends ZVisualComponent { // default values for variables static final public Color penColor_DEFAULT = Color.blue; static final public Color fillColor_DEFAULT = Color.yellow; static final public float penWidth_DEFAULT = 5.0f; // member variables protected Color penColor = penColor_DEFAULT; protected Color fillColor = fillColor_DEFAULT; protected float penWidth = penWidth_DEFAULT; protected Ellipse2D.Float circle; /***************************** Constructors **********************************/ // creates circle at (0,0) with radius = 0 public ZCircle () { circle = new Ellipse2D.Float(); reshape(); } // creates circle with center (x,y) and radius = r public ZCircle(float x, float y, float r) { float half = r / 2; circle = new Ellipse2D.Float(x - half, y - half, r, r); reshape(); } // creates circle within bounding box defined by // point (x,y) with width and height public ZCircle(float x, float y, float width, float height) { float smallerDim = (width < height ? width : height); circle = new Ellipse2D.Float(x, y, smallerDim, smallerDim); reshape(); } /*********** Get/Set functions for variables specific to the circle *********/ public float getPenWidth() { return penWidth; } public void setPenWidth(float p) { penWidth = p; reshape(); // Changing the pen width results in the bounds changing } public Color getPenColor() { return penColor; } public void setPenColor(Color c) { penColor = c; repaint(); // Changing the pen color does not result in a bounds change } public Color getFillColor() { return fillColor; } public void setFillColor(Color c) { fillColor = c; repaint(); // Changing the fill color does not result in a bounds change } public Point2D getCenter() { if (circle.getWidth() != circle.getHeight()) { System.out.println("ERROR: This is not a circle"); } double x = circle.getX() + (circle.getWidth() / 2); double y = circle.getY() + (circle.getHeight() / 2); return (new Point2D.Float((float)x, (float)y)); } /******************* paint, computeBounds, pick **************************/ // tell Jazz how to paint yourself public void paint(Graphics2D g2) { g2.setStroke(new BasicStroke(penWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER)); if (fillColor != null) { g2.setColor(fillColor); g2.fill(circle); } if (penColor != null) { g2.setColor(penColor); g2.draw(circle); } } // tell Jazz how big you are protected void computeBounds() { // expand bounds to accomodate penWidth float p = penWidth; float p2 = 0.5f * penWidth; Rectangle2D rect = circle.getBounds2D(); bounds.setRect((float)(rect.getX() - p2), (float)(rect.getY() - p2), (float)(rect.getWidth() + p), (float)(rect.getHeight() + p)); } // tell Jazz how to pick you // this function does not need to be overloaded // but it is a good idea to do so public boolean pick(Rectangle2D rect, ZSceneGraphPath path) { boolean picked = false; if (fillColor != null) { // If there is a fill color, then pick the inside of the circle picked = circle.contains(rect); } else if (penColor != null) { // Else, if there is a pen color, pick just the perimeter of the circle float px = (float)(rect.getX() + (0.5f * rect.getWidth())); float py = (float)(rect.getY() + (0.5f * rect.getHeight())); Point2D pt = new Point2D.Float(px, py); double distance = pt.distance(getCenter()); double radius = circle.getWidth() / 2; if ((distance >= (radius - penWidth/2)) && (distance <= (radius + penWidth/2))) { picked = true; } } return picked; } }
With this percolation model, applications can write an event handler for a specific node by putting the event handler on that node. Or, it can write an event handler for all nodes by putting the event handler at the root of the tree. Finally, an application can write a different event handler for each camera by putting the event handler on the node that contains the camera.
Jazz has several standard event handlers which can be used directly by applications. They are:
panEventHandler = new ZPanEventHandler(cameraNode); zoomEventHandler = new ZoomEventHandler(cameraNode); panEventHandler.setActive(true); zoomEventHandler.setActive(true);Obviously, it will become necessary to provide your own event handlers for the many things that you will want your application to do. Thus Jazz provides ZEventHandler which is an interface that may be implemented when defining Jazz event handlers. Although the use of ZEventHandler is not required, it is useful because that way a single object can be marked as being an event handler, and it can be passed around, and made active or inactive.
When writing per-node Jazz event handlers, it is important to understand the algorithm that Jazz follows to fire event handlers when events arrive. For each mouse or mouse motion event, Jazz calls ZDrawingSurface.pick which identifies the object that the pointer was over. The path returned by the pick call is used to identify event handlers as follows:
Starting at the end of the path, the first node is found and
import java.awt.*; import java.awt.geom.*; import java.awt.event.*; import edu.umd.cs.jazz.*; import edu.umd.cs.jazz.util.*; import edu.umd.cs.jazz.event.*; import edu.umd.cs.jazz.component.*; public class SquiggleEventHandler implements ZEventHandler, ZMouseListener, ZMouseMotionListener { private boolean active = false; // True when event handlers are attached to a node private ZNode node = null; // The node the event handlers are attached to private ZGroup drawingLayer; // The node under which to add the new squiggle private ZPolyline polyline; // The polyline currently being drawn private Point2D pt; // A reusable point public SquiggleEventHandler(ZGroup drawingLayer, ZNode node) { this.drawingLayer = drawingLayer; this.node = node; pt = new Point2D.Float(); } /** * Specifies whether this event handler is active or not. * @param active True to make this event handler active */ public void setActive(boolean active) { if (this.active && !active) { // Turn off event handlers this.active = false; node.removeMouseListener(this); node.removeMouseMotionListener(this); } else if (!this.active && active) { // Turn on event handlers this.active = true; node.addMouseListener(this); node.addMouseMotionListener(this); } } public boolean isActive() { return active; } public void mousePressed(ZMouseEvent e) { if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK) { // Left button only ZSceneGraphPath path = e.getPath(); ZCamera camera = path.getTopCamera(); pt.setLocation(e.getX(), e.getY()); path.screenToGlobal(pt); polyline = new ZPolyline(pt); ZVisualLeaf leaf = new ZVisualLeaf(polyline); polyline.setPenWidth(5.0f); polyline.setPenColor(Color.red); drawingLayer.addChild(leaf); } } public void mouseDragged(ZMouseEvent e) { if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK) { // Left button only ZSceneGraphPath path = e.getPath(); pt.setLocation(e.getX(), e.getY()); path.screenToGlobal(pt); polyline.add(pt); } } public void mouseReleased(ZMouseEvent e) { if ((e.getModifiers() & MouseEvent.BUTTON1_MASK) == MouseEvent.BUTTON1_MASK) { // Left button only polyline = null; } } /** * Invoked when the mouse enters a component. */ public void mouseEntered(ZMouseEvent e) { } /** * Invoked when the mouse exits a component. */ public void mouseExited(ZMouseEvent e) { } /** * Invoked when the mouse has been clicked on a component. */ public void mouseClicked(ZMouseEvent e) { } /** * Invoked when the mouse button has been moved on a node * (with no buttons no down). */ public void mouseMoved(ZMouseEvent e) { } }
An excellent starting point for learning about threads is to read what Sun has written about Swing and threads. Almost all of their solutions for multi-threaded code work for Jazz as well. Here are links to three major articles. Threads and Swing, Using a SwingWorker Thread, and The Last Word in Swing Threads.
One specific issue raised in these articles that often causes people problems is that the method
public static void main(String[] args)used to start a java program, is called from a thread that is not the primary event dispatch thread. As a result, once events begin accessing the Jazz scenegraph (ie. when the ZCanvas has been made visible), this main thread (as well as any other) should not modify the scenegraph. This includes animation, changing transforms, adding or deleting nodes, etc.
There are a few good reasons where it may be appropriate to run some code in a separate thread, such as with asynchronous animation. The following code will zoom in while the rest of the application is still active, and responds to events. The trick is that scaling the camera is always called in the primary Swing event dispatch thread.
import javax.swing.SwingUtilities; import edu.umd.cs.jazz.*; public class AnimTest { private boolean zooming = false; // True during animated zooming private ZCamera camera = null; // Caller must specify camera animation should occur within public AnimTest(ZCamera camera) { this.camera = camera; } // Start the animation public void startZooming() { zooming = true; zoomOneStep(); } // Stop the animation public void stopZooming() { zooming = false; } // This gets called to zoom one step public void zoomOneStep() { if (zooming) { camera.scale(1.1f, 0.0f, 0.0f); try { // The sleep here is necessary. Otherwise, there won't be // time for the primary event thread to get and respond to // input events. Thread.sleep(20); // If the sleep was interrupted, then cancel the zooming, // so don't do the next zooming step SwingUtilities.invokeLater(new Runnable() { public void run() { AnimTest.this.zoomOneStep(); } }); } catch (InterruptedException e) { zooming = false; } } } }This is a summary of the reasons we chose to build Jazz to run within a single thread:
One Swing widget that requires special attention in Jazz is the JPopupMenu. Unfortunately, this also affects JMenu and JComboBox as these both maintain an instance of JPopupMenu. The fundamental problem with JPopupMenu is that it is always potentially heavyweight (for instance, the popup can extend outside the bounds of its parent window). Consequently, care must be excercised when using a JPopupMenu in Jazz. A JPopupMenu should likely be managed at the level of the ZCanvas rather than at the level of embedded Swing widgets. JMenu and JComboBox should also not be used with ZSwing. Instead, use ZMenu and ZComboBox exactly as you would their Swing counterparts, then add them to a ZSwing.
To address this problem of incompatible file formats, Jazz also supports a custom file format which is more (although not completely) version resistant. It is a more bulky and also text-based file format. We expect that after Jazz stabilizes, we may introduce an XML based file format, and will eliminate this special format. This special file format is directly analogous to Java Serialization. Jazz classes implement the ZSerializable method and has similar readObject and writeObject methods that can be used just like Serializable objects.
Note that one difference between Java Serialization and Jazz ZSerialization is that Serialization follows all internal references, and thus if you try to write out any single node, all the pointers will be followed, and it will end up writing out the entire scenegraph including the cameras. ZSerialization, on the other hand, does not write out "up" pointers, and so if you write out a node with ZSerialization, it will only write out the sub-tree rooted at the node you specify. If you want to accomplish this functionality using Serialization, your best bet is to disconnect that subtree from the rest of the scenegraph with "getParent().removeChild(this);", write it out, and then add the subtree back.
Unlike Java Serialization, Jazz ZSerialization is not completely automated. In order to make a class ZSerializable, the class must implement the ZSerializable. interface, and it must write out and read the slots it cares about. It does not automatically write out non-transient slots like Serialization does. In addition, A ZSerializable must have a public no-arg constructor, or it will generate a ClassCastException when being read back in.
The class hierarchy of the Jazz scenegraph objects.
Nodes are of two basic types: leaves and groups. A leaf node is one that has no children. A group node has children. Some leaves (ZVisualLeaf) and some groups (ZVisualGroup) can render visual components. Other node types do not cause any actual rendering, but can provide functionality in other ways. For instance, a ZTransformGroup modifies the transform for all of its children. Let us look at each node type.
|
http://www.cs.umd.edu/hcil/piccolo/learn/jazz/doc-1.3/tutorial/Chapter2.html
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
Backup Examples¶
Getting a node from a compute driver and enabling backup¶
This example shows how to get a node using a remote Azure datacenter, enable backup and backup the node.
Note
This example works with Libcloud version 0.20.0 and above.
import time from pprint import pprint from libcloud.backup.types import BackupTargetJobStatusType from libcloud.backup.types import Provider as BackupProvider from libcloud.backup.providers import get_driver as get_backup_driver from libcloud.compute.providers import get_driver as get_compute_driver from libcloud.compute.types import Provider as ComputeProvider backup_driver = get_backup_driver( BackupProvider.DIMENSIONDATA)('username', 'api key') compute_driver = get_compute_driver( ComputeProvider.DIMENSIONDATA)('username', 'api key') nodes = compute_driver.list_nodes() # Backup the first node in the pool selected_node = nodes[0] print('Enabling backup for node') new_target = backup_driver.create_target_from_node(selected_node) print('Starting backup of node') job = backup_driver.create_target_job(new_target) print('Waiting for job to complete') while True: if job.status != BackupTargetJobStatusType.RUNNING: break else: job = backup_driver.get_target_job(job.id) print('Job is now at %s percent complete' % (job.progress)) time.sleep(20) print('Job is completed with status- %s' % (job.status)) print('Getting a list of recovery points') recovery_points = backup_driver.list_recovery_points(new_target) pprint(recovery_points)
|
https://libcloud.readthedocs.io/en/latest/backup/examples.html
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
Raspberry Pi-Arduino Based Simple Blind Navigation Device (AIDA2)
Introduction: Raspberry Pi-Arduino Based Simple Blind Navigation Device (AIDA2)
This is a very brief and simple instructable on how to make a small wrist navigation device to help blind people walk.
I wanted to upgrade what I previously made here so I added a raspberry pi 3 to make the device actually talk to the blind person through headphones. I called the device AIDA2 since it's the 2nd version & hopefully I will improve it further in the future. If you found this instructable useful or if you found any other limitations to it please let me know. If you can improve it that would be great too :)
The previous version only produced a buzzer sound when it faced an obstacle. This one talks (or to be more precise plays a MP3 file with recorded talking in it) to the blind person thus specifying exactly what's in front of them. The theory of operation here is simple, the ultrasonic sensor sends a signal from the Arduino board to the Raspberry Pi Computer whenever he sees an obstacle and the Raspberry Pi responds by playing A sound file telling the blind person through the headphones that they wear that an obstacle/obstruction is ahead of them. During the making process of this idea I did suffer a small glitch which I'll explain later but first I want to elaborate that I did try to use Arduino MP3 shield since it's much cheaper than using a raspberry pi but it failed miserably! So if you actually managed to do it using the shield and without the pi that would be much better than what I did here, if that's the case let me know. Also one of the problems of using a raspberry pi (other than the cost) is that it requires a lot of power so either use a smart phone power supply (which limits the motion obviously not what we want!) or buy a USB battery pack for raspberry pi like this one or if you have the time and/or can't afford buying a battery pack (like me) build one using a simple AA battery box (or even without it) and connect its wires to a 5v regulator and solder the regulator wires to the wires of the smart phone charger cable (the end that goes to the plug) and connect the end that goes inside the raspberry pi and it will work just as good (more on that later)
What you will need for this is :
- Arduino board (I tested it on Arduino Uno but you can try it on Mega will also work)
- USB Cable - Standard A-B (for connecting the Arduino to the Raspberry Pi)
- Raspberry Pi 3 (You can use 2 if you want)
- Micro SD Card for Raspberry Pi (8 GB or more)
- SD Card Reader (I'm assuming some knowledge in Raspberry Pi, but if that's not the case I've included all what you need to get started just in case)
- Smart Phone Charger Power Supply for Raspberry Pi (Option 1 - not very practical)
- 5v Regulator + 4 x AA battery box + some solder wire and some duct tape & a wire cutter/stripper for connecting the wire between the Raspberry Pi jack and the regulator and the battery box which will need some soldering and covering the soldered parts with duct tape (Option 2 - In case you want to make a portable power source by yourself, a picture of one I did I put here)
- 4 x AA batteries (In case you are going with option 2)
- USB battery pack for Raspberry pi (Option 3 - It will save you some time and easier to charge so it's more sustainable than Option 2 + Portable So for sure better than Option 1). I never got one but I think you can buy one from here I suppose
- Headphones to be connected to the raspberry pi audio jack (I prefer the big ones since they are more comfortable to the ears)
- Ultrasonic Sensor Module for Arduino (HC-SR04)
- Breadboard
- Jumper Wires
- A single glove or an oven mitten or an industrial protection glove (that will serve as the talking hand)
- A Shoelace or a string or a small rope for tying up every thing together (this pretty optional, you can use a glue if you want but since this project has a glitch I wouldn't advise you to do that)
Step 1: Connecting the Device
Before starting it' worth mentioning that you could just connect the ultrasonic sensor to the GPIO pins of the Raspberry Pi directly and not use an Arduino at all. But for some unknown reason that didn't work with mey so I had to add Arduino until I know what the problem is.
use the wires to connect the parts of the Arduino UNO as follows :
For the ultrasonic sensor :
Echo pin to pin 12 on the Arduino, Trig pin to pin 11 on the Arduino, Vcc to Vin, GND to GND and finally the USB Cable to the USB hub. Here's a picture showing the actual connections on the breadboard.
For the Raspberry Pi :
I'm assuming you have some knowledge of setting up the Raspberry Pi, formatting the SD Card, burning an ISO image of Raspbian OS on it using the SD Card reader and then powering up the Raspberry Pi using one of the power Supply options mentioned above then configuring the Raspberry Pi for the first time after connecting the display, keyboard & mouse to the pi,...etc. If you don't know how to do all that I suggest you stop reading this right now and check links like these : , and do some searching on each of the brief steps I mentioned above.
After successfully configuring the Raspberry Pi we move on to the next step.
Step 2: The Code
Start by programming the Arduino by connecting the USB Cable to your PC and opening the IDE and enter the following code. make sure to adjust your IDE before connecting the board to your PC depending on the type of Arduino board you're using, then connect it and write down the following code. I tried to explain as much of the code as possible in the comments, I even added some options in case you want to test the sensor first on the serial monitor (as I did) in case something isn't clear please leave a comment and I will try to answer.
The code to be written & uploaded to the Arduino board is as follows :-
/* AIDA 2 : Blind Navigation Device
HC-SR04 Ping distance sensor:
VCC to Arduino Vin
GND to Arduino GND
Echo to Arduino pin 12
Trig to Arduino pin 11
USB Cable To Raspberry Pi */
#include <NewPing.h> //downloaded from the internet & unzipped in libraries folder in Arduino Directory
#include <Time.h> //downloaded from the internet and installed in the Arduino\libraries to enable interfacing with the raspberry pi
#include <TimeLib.h>
#define TRIGGER_PIN 11 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 12 // Arduino pin tied to echo pin on the ultrasonic sensor.
int maximumRange = 70; // Maximum range needed
int minimumRange = 35; // Minimum range needed
long duration, distance; // Duration used to calculate distance
void setup()
{
Serial.begin (115200);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop()
{
// The following trigPin/echoPin cycle is used to determine the distance of the nearest object through reflecting soundwaves off of it (like a Bat!)
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = (duration/2) / 29.1; //formula to convert the value measured by the ultrasonic sensor into centimeters
if (distance >= maximumRange || distance <= minimumRange)
{
Serial.println("0"); // 0 => Clear Path
}
else
{
Serial.println("1"); //1 => Obstruction Ahead
}
delay(50); //Delay 50ms before next reading.
}
After Programming the Arduino board (which is connected to the Ultrasonic sensor) , we need to program the Python code on the Raspberry Pi to determine what will it do once it recieves and processes the data sent to it from the Ardiuno. But before we start Programming the Pi, we need to add some sound files to the Raspberry Pi, these are the sound files to be played when the ultrasonic sensor faces an obstruction. I used a text-to-speech software () and I have made the sound files I made available (they speak in both English and Arabic) but you can use/create any MP3 files of your choosing (you'll have to change the name of the file in the python code off course).
Here's a screenshot of the home directory of the Raspberry Pi after I moved the MP3 sound files to it using a USB.
From the Raspberry Pi start menu choose 'programming' and choose IDLE and write the following python code :-
import serial
import RPi.GPIO as GPIO #import GPIO library
import sys #import sys module
import os #import os module
from subprocess import Popen #import subprocess module, Popen command
from subprocess import call #import subprocess module, call command
import time #import time library to allow us to use the sleep function
import multiprocessing
import datetime
GPIO.setmode(GPIO.BOARD) #activate all pins
GPIO.setwarnings(False) #disable Warning Messages from the compiler
arduinoSerialData = serial.Serial('/dev/ttyACM0', 115200, timeout = 0.1)
def main():
while True:
time.sleep(0.01)
if(arduinoSerialData.inWaiting()>0):
myData = arduinoSerialData.readline().rstrip()
print (myData)
if (myData == b'1'): #since this is written in python 2, 1 was made string print('Obstruction Ahead')
os.system('omxplayer AVoiceFemale.mp3') #Arabic Female Sound File
#os.system('omxplayer EVoiceFemale.mp3') #English Female Sound File
#the previous line sends a command to the terminal to play a MP3 file
else:
print('Clear Path')
#os.system('omxplayer Silence02s.mp3) #this was an attempt to solve the glitch
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt: #In case you want to debug, use Ctrl + C
print >> sys.stderr, '\nExiting by user request. \n'
sys.exit(0)
NOTE : Due to formatting issues when copying the code here the indents were not made properly. PLEASE MIND THE INDENTS OTHERWISE THE CODE WON'T WORK !
Step 3: Connecting the Raspberry Pi and the Arduino Together
Put the USB cable which is connected from on end already to the Arduino you just programmed to one of the USB hubs in the Raspberry Pi. Put your headphones on your ears & run the code from IDLE (or any other python interpreter if you prefer) using F5 and start moving the breadboard where the ultrasonic sensor and the Arduino Board are connected, point the Ultrasonic sensor to a place where a nearby obstruction exists and notice the change on the IDLE interactive shell and the sound you're hearing through the headphones. You can mount the whole thing (breadboard + Arduino ultrasonic circuit + Raspberry Pi) on a thick glove or an oven mitten and tie it all together using a shoelace as shown in the pictures here. Or to make it more stable and possibly permanent use a glue (not recommended due to the glitch)
THE GLITCH: If you've tried the steps above, you might have noticed by now that for some reason the program freezes after facing the obstacle. I have spent a lot of time trying to fix that with no success until I decided I'll just publish it as is. If you know how to fix this (maybe something is wrong with the coding I did) please let me know, thanks in advance.
A few Important notes :
1-You may wanna test the sound system on your pi first by playing the MP3 file separate from any other process just to make sure the Pi and the headphones are working well before running the program. This is a useful link in case you faced any problems in that area ().
2- In case you want to make the Python program we just wrote above run as soon as the Raspberry Pi is turned on (If it weren't for the glitch I would recommend it but it's just an option for now) here are some useful links explaining how to do that if you don't already know () , ()
|
http://www.instructables.com/id/Raspberry-Pi-Arduino-Based-Simple-Blind-Navigation/
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
Results 1 to 1 of 1
Import a character style to InDesign
- Member Since
- May 30, 2008
- 8
- Specs:
- Intel 10.5.8
I want to select a group of Indesign docs & import 1 character style called Moon from the source document. So far what I have is the looping thru different ID docs can anyone guide me? I can see in the ID dictionary that is possible but I'm still learning don't how to put it together:
Code:
set source_folder to choose file with prompt "Select folder containing InDesign Docs to have a Sku's report" with multiple selections allowed without invisibles tell application "Finder" to set item_list to every item of source_folder --loop thru all ID docs repeat with this_item in item_list set doc_kind to kind of (info for this_item as alias) if doc_kind contains "Indesign" then tell application "Adobe InDesign CS4" activate set user interaction level of script preferences to never interact set import styles from ??? set set myCharacterStyle to import styles --XXXXXXXXXXX The guts import Moon character style --close document 1 saving no end tell end if end repeat
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Similar Threads
swapping from old style to new style?By deacon87 in forum Apple NotebooksReplies: 5Last Post: 02-25-2009, 03:53 PM
import issue: only showing imovie 08:last import ... unable to locate previous importBy DAIDAI in forum Movies and VideoReplies: 0Last Post: 12-25-2008, 02:03 PM
Where Can I Find This Style of VWhere Can I Find This Style of VisualizerBy PaulMoretti in forum Music, Audio, and PodcastingReplies: 0Last Post: 08-11-2008, 02:01 PM
IWork files import into indesign?By ghsusaxa75 in forum Images, Graphic Design, and Digital PhotographyReplies: 0Last Post: 03-08-2008, 10:32 PM
|
http://www.mac-forums.com/forums/os-x-development-darwin/284340-import-character-style-indesign.html
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
How to use ecj compiler in Netbeans
If you have read my post about why sometimes Eclipse ECJ compiler does not work nicely with other compilers then you maybe also need some cure for that issue.
Few days later I’ve found some, maybe not very nice, solution to get ECJ working with Netbeans IDE. Had no spare time to write about it, but i have few free minutes now and maybe someone needs that stuff also.
I’ve downloaded sources for Netbeans launcher C code (thanks God for Open Source) and modified it so it launches ECJ main class.
Then added one line in main project build.xml file:
<property name="platform.javac" value="<path_to>/ecjexec.exe"/>
(just change <path_to> to where you have saved your launcher)
This will make ant (default Netbeans build system) use ecjexec (thus ECJ) instead of javac.
Oh, you need to do one more thing: add ecj.jar to your system CLASSPATH variable.
Here is some quick’n’dirty C code you can add to Netbeans launcher to make it launch ECJ instead (sorry, no way i can attach exec here):
#include <stdlib.h> #include <iostream> #include "jvmlauncher.h" /* * */ int main(int argc, char** argv) { std::list<std::string> progArgs; std::list<std::string> opts; for (int i = 1; i < argc; i++) { char* arg = argv[i]; progArgs.push_back(arg); } //opts.push_back("-classpath d:/Libs/ecj/ecj.jar"); JvmLauncher launcher; launcher.initialize("1.5"); std::string javapath; bool java_exists = launcher.getJavaPath(javapath); std::cout << "Java: " << java_exists << " " << javapath << std::endl; launcher.start("org.eclipse.jdt.internal.compiler.batch.Main", progArgs, opts, true, 0); return (0); }
You can get original code here: (use platf_launcher, looks like it’s the same code I’ve downloaded few months ago)
Hope it help’s you in some way. Just remember to open/edit launcher in Netbeans 🙂
Pingback: JavaPins
|
https://jdevel.wordpress.com/2010/07/02/how-to-use-ecj-compiler-in-netbeans/
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
import "go.aporeto.io/trireme-lib/controller/pkg/connection"
const ( // RejectReported represents that flow was reported as rejected RejectReported bool = true // AcceptReported represents that flow was reported as accepted AcceptReported bool = false )
MaximumUDPQueueLen is the maximum number of UDP packets buffered.
TCPConnectionExpirationNotifier handles processing the expiration of an element
type AuthInfo struct { LocalContext []byte RemoteContext []byte RemoteContextID string RemotePublicKey interface{} RemoteIP string RemotePort string LocalServiceContext []byte RemoteServiceContext []byte }
AuthInfo keeps authentication information about a connection
ProxyConnState identifies the constants of the state of a proxied connection
const ( // ClientTokenSend Init token send for client ClientTokenSend ProxyConnState = iota // ServerReceivePeerToken -- waiting to receive peer token ServerReceivePeerToken // ServerSendToken -- Send our own token and the client tokens ServerSendToken // ClientPeerTokenReceive -- Receive signed tokens from server ClientPeerTokenReceive // ClientSendSignedPair -- Sign the (token/nonce pair) and send ClientSendSignedPair // ServerAuthenticatePair -- Authenticate pair of tokens ServerAuthenticatePair )
type ProxyConnection struct { sync.Mutex Auth AuthInfo ReportFlowPolicy *policy.FlowPolicy PacketFlowPolicy *policy.FlowPolicy // contains filtered or unexported fields }
ProxyConnection is a record to keep state of proxy auth
func NewProxyConnection() *ProxyConnection
NewProxyConnection returns a new Proxy Connection
func (c *ProxyConnection) GetState() ProxyConnState
GetState returns the state of a proxy connection
func (c *ProxyConnection) SetReported(reported bool)
SetReported sets the flag to reported when the conn is reported
func (c *ProxyConnection) SetState(state ProxyConnState)
SetState is used to setup the state for the Proxy Connection
type TCPConnection struct { sync.RWMutex Auth AuthInfo // ServiceData allows services to associate state with a connection ServiceData interface{} // Context is the pucontext.PUContext that is associated with this connection // Minimizes the number of caches and lookups Context *pucontext.PUContext // TimeOut signals the timeout to be used by the state machines TimeOut time.Duration // ServiceConnection indicates that this connection is handled by a service ServiceConnection bool // ReportFlowPolicy holds the last matched observed policy ReportFlowPolicy *policy.FlowPolicy // PacketFlowPolicy holds the last matched actual policy PacketFlowPolicy *policy.FlowPolicy // contains filtered or unexported fields }
TCPConnection is information regarding TCP Connection
func NewTCPConnection(context *pucontext.PUContext) *TCPConnection
NewTCPConnection returns a TCPConnection information struct
func (c *TCPConnection) Cleanup(expiration bool)
Cleanup will provide information when a connection is removed by a timer.
func (c *TCPConnection) GetState() TCPFlowState
GetState is used to return the state
func (c *TCPConnection) SetReported(flowState bool)
SetReported is used to track if a flow is reported
func (c *TCPConnection) SetState(state TCPFlowState)
SetState is used to setup the state for the TCP connection
func (c *TCPConnection) String() string
String returns a printable version of connection
TCPFlowState identifies the constants of the state of a TCP connectioncon
const ( // TCPSynSend is the state where the Syn packets has been send, but no response has been received TCPSynSend TCPFlowState = iota // TCPSynReceived indicates that the syn packet has been received TCPSynReceived // TCPSynAckSend indicates that the SynAck packet has been send TCPSynAckSend // TCPSynAckReceived is the state where the SynAck has been received TCPSynAckReceived // TCPAckSend indicates that the ack packets has been sent TCPAckSend // TCPAckProcessed is the state that the negotiation has been completed TCPAckProcessed // TCPData indicates that the packets are now data packets TCPData // UnknownState indicates that this an existing connection in the uknown state. UnknownState )
type UDPConnection struct { sync.RWMutex Context *pucontext.PUContext Auth AuthInfo ReportFlowPolicy *policy.FlowPolicy PacketFlowPolicy *policy.FlowPolicy // ServiceData allows services to associate state with a connection ServiceData interface{} // PacketQueue indicates app UDP packets queued while authorization is in progress. PacketQueue chan *packet.Packet Writer afinetrawsocket.SocketWriter // ServiceConnection indicates that this connection is handled by a service ServiceConnection bool TestIgnore bool // contains filtered or unexported fields }
UDPConnection is information regarding UDP connection.
func NewUDPConnection(context *pucontext.PUContext, writer afinetrawsocket.SocketWriter) *UDPConnection
NewUDPConnection returns UDPConnection struct.
func (c *UDPConnection) AckChannel() chan bool
AckChannel returns the Ack stop channel.
func (c *UDPConnection) AckStop()
AckStop issues a stop in the Ack channel.
func (c *UDPConnection) DropPackets()
DropPackets drops packets on errors during Authorization.
func (c *UDPConnection) GetState() UDPFlowState
GetState is used to get state of UDP Connection.
func (c *UDPConnection) QueuePackets(udpPacket *packet.Packet) (err error)
QueuePackets queues UDP packets till the flow is authenticated.
func (c *UDPConnection) ReadPacket() *packet.Packet
ReadPacket reads a packet from the queue.
func (c *UDPConnection) SetReported(flowState bool)
SetReported is used to track if a flow is reported
func (c *UDPConnection) SetState(state UDPFlowState)
SetState is used to setup the state for the UDP Connection.
func (c *UDPConnection) SynAckChannel() chan bool
SynAckChannel returns the SynAck stop channel.
func (c *UDPConnection) SynAckStop()
SynAckStop issues a stop in the synAckStop channel.
func (c *UDPConnection) SynChannel() chan bool
SynChannel returns the SynStop channel.
func (c *UDPConnection) SynStop()
SynStop issues a stop on the synStop channel.
UDPFlowState identifies the constants of the state of a UDP connection.
const ( // UDPStart is the state where a syn will be sent. UDPStart UDPFlowState = iota // UDPClientSendSyn is the state where a syn has been sent. UDPClientSendSyn // UDPClientSendAck is the state where application side has send the ACK. UDPClientSendAck // UDPReceiverSendSynAck is the state where syn ack packet has been sent. UDPReceiverSendSynAck // UDPReceiverProcessedAck is the state that the negotiation has been completed. UDPReceiverProcessedAck // UDPData is the state where data is being transmitted. UDPData )
Package connection imports 10 packages (graph) and is imported by 7 packages. Updated 2018-11-17. Refresh now. Tools for package owners.
|
https://godoc.org/go.aporeto.io/trireme-lib/controller/pkg/connection
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
KSZ8873 Ethernet switch. More...
#include "core/net.h"
#include "drivers/switch/ksz8873_driver.h"
#include "debug.h"
Go to the source code of this file.
KSZ8873 Ethernet switch. ksz8873_driver.c.
Definition at line 30 of file ksz8873_driver.c.
Disable interrupts.
Definition at line 185 of file ksz8873_driver.c.
Dump PHY registers for debugging purpose.
Definition at line 278 of file ksz8873_driver.c.
Enable interrupts.
Definition at line 175 of file ksz8873_driver.c.
KSZ8873 event handler.
Definition at line 195 of file ksz8873_driver.c.
Get link state.
Definition at line 91 of file ksz8873_driver.c.
KSZ8873 Ethernet switch initialization.
Definition at line 58 of file ksz8873_driver.c.
Read PHY register.
Definition at line 264 of file ksz8873_driver.c.
KSZ8873 timer handler.
Definition at line 125 of file ksz8873_driver.c.
Write PHY register.
Definition at line 248 of file ksz8873_driver.c.
KSZ8873 Ethernet switch driver.
Definition at line 42 of file ksz8873_driver.c.
|
https://oryx-embedded.com/doc/ksz8873__driver_8c.html
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
#include <wx/textfile.h>
The wxTextFile is a simple class which allows to work with text files on line by line basis.
It also understands the differences in line termination characters under different platforms and will not do anything bad to files with "non native" line termination sequences - in fact, it can be also used to modify the text files and change the line termination characters from one type (say DOS) to another (say Unix).
One word of warning: the class is not at all optimized for big files and thus it will load the file entirely into memory when opened. Of course, you should not work in this way with large files (as an estimation, anything over 1 Megabyte is surely too big for this class). On the other hand, it is not a serious limitation for small files like configuration files or program sources which are well handled by wxTextFile.
The typical things you may do with wxTextFile in order are:.
Returns the current line: it has meaning only when you're using GetFirstLine()/GetNextLine() functions, it doesn't get updated when you're using "direct access" functions like GetLine().
GetFirstLine() and GetLastLine() also change the value of the current line, as well as GoToLine(). Mac to enumerate&) constructor and also loads file in memory on success.
It will fail if the file does not exist, Create() should be used in this case.
The conv argument is only meaningful in Unicode build of wxWidgets when it is used to convert the file to wide character representation.
Delete line number n from the file.
Change the file on disk.
The typeNew parameter allows you to change the file format (default argument means "don't change type") and may be used to convert, for example, DOS files to Unix.
The conv argument is only meaningful in Unicode build of wxWidgets when it is used to convert all lines to multibyte representation before writing them to physical file.
Default type for current platform determined at compile time.
|
https://docs.wxwidgets.org/3.0/classwx_text_file.html
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
Help using Qthread and signal/slot
Hello,
I'm a beginner and i try using qt with multi-thread and signal/slot.
This is my worker class worker.h:
#ifndef GSTIMPL_H #define GSTIMPL_H #include <QObject> #include <QThread> #include <QDebug> class Worker : public QObject { Q_OBJECT public: Worker(); ~Worker(); public slots: void Process(); void Stop(); signals: void finished(); private: bool m_play; }; #endif // GSTIMPL_H
the corresponding worker.cpp:
#include "Worker.h" Worker::Worker() { // Constructor qDebug() << "-------------- Worker Constructor --------------" << endl; m_play = true; } Worker::~Worker() { // Destructor qDebug() << "-------------- Worker Destructor --------------" << endl; } void Worker::Process() { // Process. Start processing data. qDebug() << "-------------- Worker Process --------------" << endl; while(m_play == true) { qDebug("Hello World!"); QThread::sleep(1); } emit finished(); } void Worker::Stop() { qDebug() << "-------------- Worker Stop --------------" << endl; m_play = false; }
My controller class:
#ifndef CONTROLLER_H #define CONTROLLER_H #include <QObject> #include <QThread> #include "Worker.h" class Controller : public QObject { Q_OBJECT QThread workerThread; public: Controller(); public slots: signals: void Play(); void Stop(); }; #endif // CONTROLLER_H
and the corresponding controller.cpp:
#include "controller.h" Controller::Controller() { qDebug() << "-------------- Controller Constructor --------------" << endl; Worker* worker = new Worker(); worker->moveToThread(&workerThread); connect(&workerThread, SIGNAL (started()), worker, SLOT (Process())); connect(worker, SIGNAL (finished()), &workerThread, SLOT (quit())); connect(worker, SIGNAL (finished()), worker, SLOT (deleteLater())); connect(&workerThread, SIGNAL (finished()), &workerThread, SLOT (deleteLater())); connect(this, SIGNAL (Stop()), worker, SLOT (Stop())); workerThread.start(); emit Stop(); }
And this is my main:
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; Controller c; return app.exec(); }
This is the output i get :
*Starting /opt/GstBind/bin/GstBind...
QML debugging is enabled. Only use this in a safe environment.
Using Wayland-EGL
-------------- Controller Constructor --------------
-------------- Worker Constructor --------------
-------------- Worker Process --------------
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
User requested stop. Shutting down...
Process killed by signal*
As you can see my problem is about signal/slot Stop(). It is never called whereas in my controller constructor it should be ! and so never printed too.
@fd101283 said in Help using Qthread and signal/slot:
QThread workerThread;
Hi! There's a double free in your code:
workerThreadis a member variable of
Controller(thus gets automatically destroyed by the C++ runtime when
Controllergets destroyed) and at the same time you connected
workerThread's
finishedsignal to its
deleteLaterslot.
@Wieland said in Help using Qthread and signal/slot:
Hi! There's a double free in your code: workerThread is a member variable of Controller (thus gets automatically destroyed by the C++ runtime when Controller gets destroyed) and at the same time you connected workerThread's finished signal to its deleteLater slot.
Hi,
In fact the code is extrated from here :
BUt even without the free, i can't see Stop signal working!
- jazzycamel
I think it may be because you are emitting the signal from within the constructor which means that the event loop isn't running yet. Try replacing:
emit Stop();
with
QTimer::singleShot(1000, [](){ emit Stop(); });
This will ensure that the loop is running before the signal is emitted.
|
https://forum.qt.io/topic/85455/help-using-qthread-and-signal-slot
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
This package lets you communicate between the server and client,
all you need to do is
SocketMessage.shrinkT(x,[y]) to turn x into json and make y it's type
and
SocketMessage.expandT(x) to turn the json string x into an object.
this package uses dson.
¯\_(ツ)_/¯
did stuff i guess
0.1.5:
Add this to your package's pubspec.yaml file:
dependencies: server_client_comm: ^0.1.7
You can install packages from the command line:
with pub:
$ pub get
Alternatively, your editor might support
pub get.
Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:server_client_comm/server_client_comm.dart';
We analyzed this package on Dec 5, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:
Detected platforms:
Low code quality prevents platform classification.
Fix
lib/src/sccomm.dart. (-90.04 points)
Analysis of
lib/src/sccomm.dart failed with 8 errors, 1 hint, including:
line 49 col 33: Undefined name 'JSON'.
line 53 col 19: Undefined name 'JSON'.
line 58 col 20: Undefined name 'JSON'.
line 61 col 45: The method tear-off 'expandT' has type '(String) → dynamic' that isn't of expected type '(dynamic) → dynamic'. This means its parameter or return type does not match what is expected.
line 64 col 44: The method tear-off 'expandT' has type '(String) → dynamic' that isn't of expected type '(dynamic) → dynamic'. This means its parameter or return type does not match what is expected.
Format
lib/server_client_comm.dart.
Run
dartfmt to format
lib/server_client_comm.dart.
Format
lib/src/typesOfSame.dart.
Run
dartfmt to format
lib/src/typesOfSame.dart.
Fix platform conflicts. (-20 points)
Low code quality prevents platform classification.
Use constrained dependencies. (-20 points)
The
pubspec.yaml contains 1 dependency without version constraints. Specify version ranges for the following dependencies:
dson.
Homepage is not helpful. (-10 points)
Update the
homepage property: create a website about the package or use the source repository URL.
Package is getting outdated. (-13.70 points)
The package was released 59 weeks ago.
Maintain an example. (-10 points)
Create a short demo in the
example/ directory to show how to use this package. Common file name patterns include:
main.dart,
example.dart or you could also use
server_client_comm.dart.
The description is too long. (-10 points)
Search engines will display only the first part of the description. Try to keep it under 180 characters.
|
https://pub.dartlang.org/packages/server_client_comm
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
Use)); }
string_scanner1.0.0.
path, since we don't actually import it.
SourceSpans for scalar values surrounded by whitespace.
Rewrite the parser for a 10x speed improvement.
Support anchors and aliases (
&foo and
*foo).
Support explicit tags (e.g.
!!str). Note that user-defined tags are still
not fully supported.
%YAML and
%TAG directives are now parsed, although again user-defined tags
are not fully supported.
YamlScalar,
YamlList, and
YamlMap now expose the styles in which they
were written (for example plain vs folded, block vs flow).
A
yamlWarningCallback field is exposed. This field can be used to customize
how YAML warnings are displayed.
Fix an import in a test.
Widen the version constraint on the
collection package.
Spanclass in documentation and tests.
Switch from
source_maps'
Span class to
source_span's
SourceSpan class.
For consistency with
source_span and
string_scanner, all
sourceName
parameters have been renamed to
sourceUrl. They now accept Urls as well as
Strings.
Fix broken type arguments that caused breakage on dart2js.
Fix an analyzer warning in
yaml_node_wrapper.dart.
Add new publicly-accessible constructors for
YamlNode subclasses. These
constructors make it possible to use the same API to access non-YAML data as
YAML data.
Make
YamlException inherit from source_map's [
SpanFormatException][]. This
improves the error formatting and allows callers access to source range
information.
Backwards incompatibility: The data structures returned by
loadYaml and
loadYamlStream are now immutable.
Backwards incompatibility: The interface of the
YamlMap class has
changed substantially in numerous ways. External users may no longer construct
their own instances.
Maps and lists returned by
loadYaml and
loadYamlStream now contain
information about their source locations.
A new
loadYamlNode function returns the source location of top-level scalars
as well.
YamlMapclass is deprecated. In a future version, maps returned by
loadYamland
loadYamlStreamwill be Dart
HashMaps with a custom equality operation.
Add this to your package's pubspec.yaml file:
dependencies: yaml: ^2.1.10
You can install packages from the command line:
with pub:
$ pub get
Alternatively, your editor might support
pub get.
Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:yaml/yaml.
|
https://pub.dartlang.org/packages/yaml/versions/2.1.10
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
FileTables (SQL Server)
.
The FileTable feature builds on top of SQL Server FILESTREAM technology. To learn more about FILESTREAM, see FILESTREAM (SQL Server).
Benefits of the FileTable Feature.
What Is a FileTable?:
A FileTable represents a hierarchy of directories and files. It stores data related to all the nodes in that hierarchy, for both directories and the files they contain. This hierarchy starts from a root directory that you specify when you create the FileTable.
Every row in a FileTable represents a file or a directory.
Every row contains the following items. For more information about the schema of a FileTable, see FileTable Schema.
A file_stream column for stream data and a stream_id (GUID) identifier. (The file_stream column is NULL for a directory.)
Both path_locator and parent_path_locator columns for representing and maintaining the current item (file or directory) and directory hierarchy.
10 file attributes such as created date and modified date that are useful with file I/O APIs.
A type column that supports full-text search and semantic search over files and documents.
A FileTable enforces certain system-defined constraints and triggers to maintain file namespace semantics.
When the database is configured for non-transactional access, the file and directory hierarchy represented in the FileTable is exposed under the FILESTREAM share configured for the SQL Server instance. This provides file system access for Windows applications.
Some additional characteristics of FileTables include the following:
The file and directory data stored in a FileTable is exposed through a Windows share for non-transactional file access for Windows API based applications. For a Windows application, this looks like a normal share with its files and directories. Applications can use a rich set of Windows APIs to manage the files and directories under this share.
The directory hierarchy surfaced through the share is a purely logical directory structure that is maintained within the FileTable.
Calls to create or change a file or directory through the Windows share are intercepted by a SQL Server component and reflected in the corresponding relational data in the FileTable.
Windows API operations are non-transactional in nature, and are not associated with user transactions. However, transactional access to FILESTREAM data stored in a FileTable is fully supported, as is the case for any FILESTREAM column in a regular table.
FileTables can also be queried and updated through normal Transact-SQL access. They are also integrated with SQL Server management tools, and features such as backup.
Additional Considerations for Using FileTables.
Related Tasks
Enable the Prerequisites for FileTable
Describes how to enable the prerequisites for creating and using FileTables.
Create, Alter, and Drop FileTables
Describes how to create a new FileTable, or alter or drop an existing FileTable.
Load Files into FileTables
Describes how to load or migrate files into FileTables.
Work with Directories and Paths in FileTables
Describes the directory structure in which the files are stored in FileTables.
Access FileTables with Transact-SQL
Describes how Transact-SQL data manipulation language (DML) commands work with FileTables.
Access FileTables with File Input-Output APIs
Describes how file system I/O works on a FileTable.
Manage FileTables
Describes common administrative tasks for managing FileTables.
Related Content
FileTable Schema
Describes the pre-defined and fixed schema of a FileTable.
FileTable Compatibility with Other SQL Server Features
Describes how FileTables work with other features of SQL Server.
FileTable DDL, Functions, Stored Procedures, and Views
Lists the Transact-SQL statements and the SQL Server database objects that have been added or changed to support the FileTable feature.
See Also
Filestream and FileTable Dynamic Management Views (Transact-SQL)
Filestream and FileTable Catalog Views (Transact-SQL)
Filestream and FileTable System Stored Procedures (Transact-SQL)
|
https://docs.microsoft.com/en-us/sql/relational-databases/blob/filetables-sql-server?view=sql-server-2017
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
Integrating with ASP.NET
You can integrate the Validation Application Block with ASP.NET applications. For example, you can use the application block to validate information a user enters into a Web form. ASP.NET is integrated with the Validation Application Block through the types defined in the Microsoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet assembly.
The PropertyProxyValidator class defined in this assembly provides the main integration point. Its purpose is to check an ASP.NET control's value using the validators that are included in a user-provided application class. The PropertyProxyValidator class acts as a wrapper that links a control to a validator in an application-level class.
The PropertyProxyValidator class provides an OnValueConvert property that allows you to specify a handler for converting values entered by the user to values required by the validators. If you do not specify a handler then a default conversion is performed by the ASP.NET TypeConverter services. For an example of how to use the PropertyProxyValidator class to validate user input in an ASP.NET application, see Validation QuickStart.
To use the PropertyProxyValidatorcontrol, you must manually add the code to an .aspx file, as shown in the following example.
The SourceTypeName XML attribute shown in the designer-generated XML code references the Customer application class. This is the class whose validators will be used.
When using ASP.NET with the Validation Application Block, you may need to convert data types such as dates before you can validate the data. The integration library provides a way for you to insert code that performs this conversion. To do this, you need to provide an event handler for the conversion and then reference this handler in the .aspx file.
The following code excerpt shows a handler that converts a date of birth string into a date.
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Validation; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators; protected void dateOfBirthValidator_ValueConvert(object sender, Microsoft.Practices.EnterpriseLibrary.Validation.Integration.AspNet.ValueConvertEventArgs e) { string value = e.ValueToConvert as string; try { e.ConvertedValue = DateTime.Parse(value, System.Globalization.CultureInfo.CurrentCulture); } catch { e.ConversionErrorMessage = "Date Of Birth is not in the correct format."; e.ConvertedValue = null; } }
The next code excerpt shows the dateOfBirthValidator and the dateOfBirthTextBox control together on an .aspx page. The OnValueConvert attribute of the PropertyProxyValidator specifies the name of the event handler to use (the code for which is located on the associated code-behind page).
...<tr> <td style="width: 100px"> Date Of Birth:</td> <td style="width: 508px"> <asp:TextBox</asp:TextBox><br /> AspNetQuickStart.Customer"> </cc1:PropertyProxyValidator></td> </tr> ...
The OnValueConvert property of the PropertyProxyValidator links the control to the conversion handler defined in the previous example.
|
https://msdn.microsoft.com/en-us/library/cc309331.aspx
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
Header definition of GoMacH. More...
Header definition of GoMacH.
Definition in file gnrc/gomach/hdr.h.
#include <stdint.h>
#include <stdbool.h>
#include "net/ieee802154.h"
Go to the source code of this file.
GoMacH announce frame type.
This frame type is specifically used to announce the chosen sub-channel sequence of the node to its one-hop neighbors.
Definition at line 75 of file gnrc/gomach/hdr.h.
|
http://riot-os.org/api/gnrc_2gomach_2hdr_8h.html
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
Ppt on credit policy Ppt on ip address classes and range Ppt on world environment day 2017 Uses of water for kids ppt on batteries Ppt on namespace in c++ Ppt on ideal gas law units Ppt online shopping cart system Ppt on share market basics Ppt on bluetooth hacking device Ppt on indian army weapons and equipment
|
http://slideplayer.com/slide/217886/
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
- .16 Introduction to Windows Application Programming
Today, users demand software with rich graphical user interfaces (GUIs) that allow them to click buttons, select items from menus and much more. In this chapter and the previous one, we have created console applications. However, the vast majority of Visual Basic programs used in industry are Windows applications with GUIs. For this reason, we have chosen to introduce Windows applications early in the book, although doing so exposes some concepts that cannot be explained fully until later chapters.
In Chapter 2, we introduced the concept of visual programming, which allows programmers to create GUIs without writing any program code. In this section, we combine visual programming with the conventional programming techniques introduced in this chapter and the previous chapter. Through this combination, we can enhance considerably the Windows application introduced in Chapter 2.
Before proceeding, load the project ASimpleProgram from Chapter 2 into the IDE, and change the (Name) properties of the form, label and picture box to FrmASim-pleProgram, lblWelcome and picBug, respectively. The modification of these names enables us easily to identify the form and its controls in the program code. [Note: In this section, we change the file name from Form1.vb to ASimpleProgram.vb, to enhance clarity.]
Good Programming Practice 3.2
The prefixes Frm, lbl and pic allow forms, labels and picture boxes; respectively, easily to be identified easily in program code.
With visual programming, the IDE generates the program code that creates the GUI. This code contains instructions for creating the form and every control on it. Unlike with a console application, a Windows application's program code is not displayed initially in the editor window. Once the program's project (e.g., ASimpleProgram) is opened in the IDE, the program code can be viewed by selecting View > Code. Figure 3.16 shows the code editor displaying the program code.
Fig. 3.16 DE showing code for the program inI Fig. 2.14.
Notice that no module is present. Instead, Windows applications use classes. We already have seen examples of classes, such as Console and MessageBox, which are defined within the .NET Framework Class Library (FCL). Like modules, classes are logical groupings of procedures and data that simplify program organization. Modules are discussed in detail in Chapter 4, Procedures. In-depth coverage of classes is provided in Chapter 5, Object-Based Programming.
Every Windows application consists of at least one class that Inherits from class Form (which represents a form) in the FCL's System.Windows.Forms namespace. The keyword Class begins a class definition and is followed immediately by the class name (FrmASimpleProgram). Recall that the form's name is set by means of the (Name) property. Keyword Inherits indicates that the class FrmASimplePro-gram inherits existing pieces from another class. The class from which FrmASimpleProgram inheritshere, System.Win-dows.Forms.Formappears to the right of the Inherits keyword. In this inheritance relationship, Form is called the superclass, or base class, and FrmASimpleProgram is called the subclass, or derived class. The use of inheritance results in a FrmASimpleProgram class definition that has the attributes (data) and behaviors (methods) of class Form. We discuss the significance of the keyword Public in Chapter 5.
A key benefit of inheriting from class Form is that someone else previously has defined "what it means to be a form." The Windows operating system expects every window (e.g., a form) to have certain capabilities (attributes and behaviors). However, because class Form already provides those capabilities, programmers do not need to "reinvent the wheel" by defining all those capabilities themselves. In fact, class Form has over 400 methods! In our programs up to this point, we have used only one method (i.e., Main), so you can imagine how much work went into creating class Form. The use of Inherits to extend from class Form enables programmers to create forms quickly and easily.
In the editor window (Fig. 3.16), notice the text WindowsFormDesignergen-eratedcode, which is colored gray and has a plus box next to it. The plus box indicates that this section of code is collapsed. Although collapsed code is not visible, it is still part of the program. Code collapsing allows programmers to hide code in the editor, so that they can focus on key code segments. Notice that the entire class definition also can be collapsed, by clicking the minus box to the left of Public. In Fig 3.16, the description to the right of the plus box indicates that the collapsed code was created by the Windows Form Designer (i.e., the part of the IDE that creates the code for the GUI). This collapsed code contains the code created by the IDE for the form and its controls, as well as code that enables the program to run. Click the plus box to view the code.
Upon initial inspection, the expanded code (Fig. 3.17) appears complex.This code is created by the IDE and normally is not edited by the programmer. However, we feel that it is important for readers to see the code that is generated by the IDE, even though much of the code is not explained until later in the book. This type of code is present in every Windows application. Allowing the IDE to create this code saves the programmer considerable development time. If the IDE did not provide the code, the programmer would have to write it, which would require a considerable amount of time. The vast majority of the code shown has not been introduced yet, so you are not expected to understand how it works. However, certain programming constructs, such as comments and control structures, should be familiar. Our explanation of this code will enable us to discuss visual programming in greater detail. As you continue to study Visual Basic, especially in Chapters 510, the purpose of this code will become clearer.
Fig. 3.17 Windows Form Designer-generated code when expanded.
When we created this application in Chapter 2, we used the Properties window to set properties for the form, label and picture box. Once a property was set, the form or control was updated immediately. Forms and controls contain a set of default properties, which are displayed initially in the Properties window when a form or control is created. These default properties provide the initial characteristics of a form or control when it is created. When a control, such as a label, is placed on the form, the IDE adds code to the class (e.g., FrmASimpleProgram) that creates the control and that sets some of the control's property values, such as the name of the control and its location on the form. Figure 3.18 shows a portion of the code generated by the IDE for setting the label's (i.e., lblWelcome's) properties, including the label's Font, Location, Name, Text and TextAlign properties. Recall from Chapter 2 that we explicitly set values for the label's Text and Tex-tAlign properties. Other properties, such as Location, are set only when the label is placed on the form.
Fig. 3.18 Code generated by the IDE for lblWelcome.
The values assigned to the properties are based on the values in the Properties window. We now demonstrate how the IDE updates the Windows Form Designergenerated code created when a property value in the Properties window changes. During this process, we must switch between code view and design view. To switch views, select the corresponding tabs: ASimpleProgram.vb for code view and ASimpleProgram.vb [Design] for design view. Alternatively, you can select View > Code or View > Designer. Perform the following steps:
Modify the file name. First, change the name of the file from Form1.vb to ASimpleProgram.vb by clicking the file name in the Solution Explorer and changing the File Nameproperty.
Modify the label control's Textproperty, using the Properties window. Recall that properties can be changed in design view by clicking a form or control to select it and modifying the appropriate property in the Properties window. Change the Text property of the label to "DeitelandAssociates" (Fig. 3.19).
Fig. 3.19 Properties window as used to set a property value.
Examine the changes in code view. Switch to code view, and examine the code. Notice that the label's Textproperty is now assigned the text that we entered in the Properties window (Fig. 3.20). When a property is changed in design mode, the Windows Form Designer updates the appropriate line of code in the class to reflect the new value.
Fig. 3.20 Windows Form Designer-generated code reflecting new property values.
Modify a property value in code view. In the code-view editor, locate the three lines of comments indicating the initialization for lblWelcome, and change the Stringassigned to Me.lblWelcome.Textfrom "Deitel andAssoci-ates" to "VisualBasic.NET" (Fig. 3.21).Then switch to design mode. The label now displays the updated text, and the Properties window for lblWel-comedisplays the new Textvalue (Fig. 3.22).
Note
Property values should not be set using the techniques presented in this step. Here, we modify the property value in the IDE-generated code only as a demonstration of the relationship between program code and the Windows Form Designer.
Fig. 3.21 Changing a property in the code-view editor.
Fig. 3.22 New Text property value as reflected in design mode.
Change the label's Textproperty at runtime. In the previous steps, we set properties at design time. Often, however, it is necessary to modify a property while a program is running. For example, to display the result of a calculation, a label's text can be assigned a Stringcontaining the result. In console applications, such code is located in Main. In Windows applications, we must create a method that executes when the form is loaded into memory during program execution. Like Main, this method is invoked when the program is run. Double-clicking the form in design view adds a method named FrmASimpleProgram_Load to the class (Fig. 3.23). Notice that FrmASimpleProgram_Loadis not part of the Windows Form Designer-generated code. Add the statement lblWelcome.Text="Vi-sualBasic"into the body of the method definition (Fig. 3.24). In Visual Basic, properties are accessed by placing the property name (i.e., Textin this case) after the class name (i.e., lblWelcomein this case), separated by the dot operator. This syntax is similar to that used when accessing class methods. Notice that the Intel-liSense feature displays the Textproperty in the member list after the class name and dot operator have been typed (Fig. 3.23). In Chapter 5, Object-Based Programming, we discuss how programmers can create their own properties.
Fig. 3.23 Adding program code to FrmASimpleProgram_Load.
Fig. 3.24 Method FrmASimpleProgram_Load containing program code.
Examine the results of the FrmASimpleProgram_Load method. Notice that the text in the label looks the same in Design mode as it did in Fig. 3.22. Note also that the Property window still displays the value "VisualBasic.NET" as the label's Textproperty. The IDE-generated code has not changed either. Select Build > Build Solution and Debug > Start to run the program. Once the form is displayed, the text in the label reflects the property assignment in FrmASimpleProgram_Load(Fig. 3.25).
Fig. 3.25 Changing a property value at runtime.
Terminate program execution. Click the close button to terminate program execution. Once again, notice that both the label and the label's Textproperty contain the text Visual Basic .NET. The IDE-generated code also contains the text VisualBasic.NET, which is assigned to the label's Textproperty.
This chapter discussed how to compose programs from control structures that contain actions and decisions. In Chapter 4, Procedures and Arrays, we introduce another program-structuring unit, called the procedure. We will discuss how to compose programs by combining procedures that are composed of control structures. We also discuss how procedures promote software reusability. In Chapter 5, Object-Based Programming, we discuss in more detail another Visual Basic program-structuring unit, called the class. We then create objects from classes and proceed with our treatment of object-oriented programminga key focus of this book.
|
http://www.informit.com/articles/article.aspx?p=31092&seqNum=16
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
Recently, and write than range-based for loops, because lambda expressions are pretty clumsy, algorithm naming is inconsistent, and algorithm interfaces are inconvenient. But, they are still better than handwritten for-loops.
Contents
- Using Range-Based For – Introduces the new C++11 range-based for-loop and compares it to index-based, iterator-based and foreach loops.
- Using STL Algorithms with Lambdas – Gives typical examples of how to rewrite handwritten for-loops with STL algorithms and range-based for. Discusses the pros and cons of the different implementations.
- Using the
any_ofAlgorithm – Shows that knowing Qt and STL algorithms can save us from reinventing the wheel and that the STL lacks some useful algorithms.
- Using the
find_ifAlgorithm – Provides evidence that range-based for will be one of the most important STL algorithms. Shows that returning an object by value instead of through a parameter of pointer type is simpler and more efficient.
- Using the
replace_ifAlgorithm – Demonstrates an algorithm that modifies the container elements in-place.
- Using the
accumulateAlgorithm – Argues that the
accumulatealgorithm can be less efficient than range-based for.
- Using the
copyAlgorithm on a C-Style Array – Shows one of the rare cases where indices are essential and range-based for cannot be used.
- Conclusion
Using Range-Based For
When I looked through the 900+ for-loops written in a medium-sized project, I spotted three main ways how to iterate over a container: index-based loops, iterator-based loops and loops using Qt’s
foreach macro. Index-based loops are often inefficient. Iterator-based loops are efficient but hard to read. Qt’s
foreach macro only works with Qt containers. We can get rid of all these problems by using C++11’s new range-based for. Let me illustrate this with an example.
The function
toggleTimers() below iterates over the list
m_timerColl by iterating over the admissible indices from 0 to
m_timerColl.size() - 1.
// Example 1a: Index-Based Loop (old C++) // thing.h class Thing { public: void toggleTimers(); private: QList<QTimer*> m_timerColl; }; // thing.cpp void Thing::toggleTimers() { for (int i = 0; i < m_timerColl.size(); ++i) { if (m_timerColl[i]->isActive()) m_timerColl[i]->stop(); else m_timerColl[i]->start(); } }
The implementation suffers from two inefficiencies. First, the body of the for-loop accesses the element at index
i three times to call some functions on the timers. Calling the index operator three times (
m_timerColl[i]) is not only code duplication, but also inefficient. The index operator uses some arithmetical operations to calculate the pointer to the location where the element with index
i resides in memory. Second, the expression
m_timerColl.size() is evaluated in every iteration of the loop. We can fix these two inefficiencies as follows.
// Example 1b: Improved Index-Based Loop (old C++) // thing.cpp void Thing::toggleTimers() { QTimer *timer = 0; const int timerCount = m_timerColl.size(); for (int i = 0; i < timerCount; ++i) { timer = m_timerColl[i]; if (timer->isActive()) timer->stop(); else timer->start(); } }
As Qt guarantees that the index operator works in constant time, index-based for-loops run in linear time. Note that index-based iteration over
std::list is not possible, because the standard C++ list container does not provide an index operator. As the C++ standard must not prescribe a special implementation of lists (as done by Qt), the best guarantee for the index operator would be linear time using
std::advance(). Hence, index-based loops would always have quadratic time complexity. This is why STL lists don’t have an index operator.
Let us admit it: Qt made us lazy! We were too lazy to write the for-loop with STL iterators.
// Example 1c: Iterator-Based Loop (old C++) // thing.cpp void Thing::toggleTimers() { QList
::iterator end = m_timerColl.end(); for (QList ::iterator timer = m_timerColl.begin(); timer != end; ++timer) { if ((*timer)->isActive()) (*timer)->stop(); else (*timer)->start(); } }
Not excactly a pretty sight, but at least more efficient than index-based loops. The iterator
timer is incremented in each step, which is more efficient than incrementing the index
i and performing some arithmetical operations for the index operator.
Qt has – of course – a solution for the problems with index-based and iterator-based for-loops: the
foreach macro.
// Example 1d: Foreach Macro (Qt/C++) // thing.cpp (Qt/C++) void Thing::toggleTimers() { foreach (QTimer *timer, m_timerColl) { if (timer->isActive()) timer->stop(); else timer->start(); } }
This version is as efficient as the iterator-based loop (see Example 2) and even simpler to read than the index-based loops (see Examples 1a and 1b). But it only works for Qt containers. It does not work for STL containers. Moreover, it’s a macro. If the type of the “iterator” variable contains a comma like
QPair, the
foreach gets confused. We would have to declare the “iterator” variable before the
foreach loop.
We can conclude that all of the above for-loops have problems: performance, simplicity and generality. The new range-based for statement of C++11 solves all of these problems.
// Example 1e: Range-Based For-Loop (C++11) // thing.cpp void Thing::toggleTimers() { for (auto timer : m_timerColl) { if (timer->isActive()) timer->stop(); else timer->start(); } }
If we looked at the implementation of range-based for, we would see that it is implemented very similar to the iterator-based version. The range-based for combined with auto is a nifty way to avoid clumsy STL iterators without sacrificing performance.
When we move to C++11 in our projects, we should consistently use range-based for instead of index-based loops, iterator-based loops or foreach macros. Based on my experience, we should be able to do this for 95% of the for-loops. For-loops that require indices are pretty rare. This is fully in line with Swift – the new iOS programming language – dropping the increment and decrement operators in version 2.2.
Using STL Algorithms with Lambdas
Rule #84 of [CodingRules] advises us to “prefer algorithm calls to handwritten loops”, because algorithm calls are “more expressive and maintainable, less error-prone, and as efficient”. So, let us roll up our sleeves, rewrite some typical hand-written loops with STL or Qt algorithms, and discuss how the results compare to the originals.
Using the
any_of Algorithm
Let us start with a simple example that was implemented in a pretty complicated way.
// Example 2a (old C++) // In thing.h QList<int> m_groups; // In thing.cpp bool Thing::containsGroup(int groupId) const { bool didFind = false; for (int i = 0; i < m_groups.count(); ++i) { if (m_groups[i] == groupId) { didFind = true; break; } } return didFind; }
When I looked at the code for the first time, I was puzzled for a couple of seconds and then started chuckling. In Qt, we could simply rewrite this function as follows.
// Example 2b (Qt) // In thing.h QList<int> m_groups; // In thing.cpp bool Thing::containsGroup(int groupId) const { return m_groups.contains(groupId); }
Now, it is more than obvious what this function does. It checks whether the
groupId is contained in the container
m_groups. The writer of the original code (Example 2a) wasted quite a few “brain cycles” to reinvent the wheel. The original solution is also inefficient, because it uses an index-based loop.
If we cannot use Qt containers, we can improve the original solution – even before the advent of C++11. We simply use the
find algorithm of the STL.
// Example 2c (old C++) // In thing.h std::list<int> m_groups; // In thing.cpp #include <algorithm> using namespace std; bool Thing::containsGroup(int groupId) const { return find(m_groups.begin(), m_groups.end(), groupId) != m_groups.end(); }
The function
find() returns an iterator to the element in
m_groups that is equal to
groupId. If this iterator is not equal to the end iterator,
m_groups contains an element with
groupId and the function returns true. Otherwise, it returns false.
C++11 comes with a new function
any_of, which returns true if the container
m_groups contains at least one occurrence of
groupId. This allows us to drop the comparison with the end iterator. C++11 also introduces constant versions of the begin and end iterator. As we do not modify the container, these constant versions are more appropriate than the non-constant ones. Using these two features, we can change the function
containsGroup() as follows.
// Example 2d (C++11) bool Thing::containsGroup(int groupId) const { return any_of(m_groups.cbegin(), m_groups.cend(), [groupId](int id) { return groupId == id; } ); }
The highlighted code is a lambda function, which returns true if the
id of the current element is equal to
groupId. The capture
[groupId] says that the lambda expression may only use the variable
groupId from the outside. The expression
(int id) is the parameter list of the lambda function. While iterating over the container,
any_of will pass each element of the container – with type
int – to the lambda function as the function’s argument.
Preferring algorithm calls to handwritten loops – as stated in rule #84 of [CodingRules] – is certainly good advice. All refactored versions (Examples 2b, 2c and 2d) are much easier to understand than the original version (Example 2a). We can look at them and know immediately what they do. They are certainly more efficient and less error-prone.
I think that the STL could do better than with the
any_of algorithm. The STL provides
any_of, which is equivalent to
std::find_if and which can be implemented using
find_if. However, the STL does not provide any equivalent to
find. Unfortunately, such an algorithm is neither part of C++14 nor C++17.
Fortunately, we can easily write such a function. We call the new function
contains, because overloading of
any_of does not work and because it is a more telling name than
any_of.
// Example 2e (C++) template<class InputIt, class T> bool contains(InputIt first, InputIt last, const T& value) { return std::find(first, last, value) != last; }
Then, we can use our brand new
contains algorithm to simplify our
containsGroup function.
// Example 2f (C++11) bool Thing::containsGroup(int groupId) const { return contains(m_groups.cbegin(), m_groups.cend(), groupId); }
I would prefer this version over the Qt version (Example 2b), because it is more general in supporting both Qt and STL containers, that is, it is more robust when things change. More developers should know this solution than the Qt solution. It may be a candidate for QtAlgorithms. By the way,
any_of, which actually behaves like
any_of_if, should be made available as
contains_if.
Using the
find_if Algorithm
What does the for-loop in the function
findConfigElementById() do?
// Example 3a (old C++) // thing.h struct ConfigElement { ConfigElement() : id(-1), value(0) {} ConfigElement(int cid, const QString &cname, int cvalue) : id(cid), name(cname), value(cvalue) {} int id; QString name; int value; }; QList<ConfigElement> m_configElements; // thing.cpp bool Thing::findConfigElementById(int id, ConfigElement *element) const { bool didFind = false; ConfigElement currentElement; int numberOfConfigElements = m_configElements.size(); for (int i = 0; i < numberOfConfigElements; ++i) { currentElement = m_configElements.at(i); if (currentElement.id == id) { didFind = true; *element = currentElement; break; } } return didFind; } // client.cpp ConfigElement element; if (aThing.findConfigElementById(5, &element)) // do something with element else // do something else with element
Well, I guess it took all of us some time to figure out that this function actually performs a
find_if. Then, let us simply write down the intent of the for-loop directly.
// Example 3b (C++11) // thing.cpp bool Thing::findConfigElementById(int id, ConfigElement *element) const { auto pos = find_if(m_configElements.cbegin(), m_configElements.cend(), [id](const ConfigElement &elem) { return elem.id == id; }); if (pos != m_configElements.cend()) { *element = *pos; return true; } return false; }
Using the algorithm
find_if states the intent of the function very clearly. The return values depend on whether an element was found in the container or not. Hence, the if-statement is absolutely normal. Calling
find_if and computing return values depending on the result of
find_if becomes second nature, once we start using STL algorithms regularly.
The new implementation is also more efficient. It got rid of the index-based loop with direct access to the container elements. It also replaces three temporary variables by one. Finally, the new implementation makes less assumptions about the container used. It can use any STL or Qt container. The container does not have to provide direct access to its element. We can easier switch to a different container. All in all, the advice of [CodingRules] to “prefer algorithm calls to handwritten loops” is good advice.
This time Qt cannot play the role of the white knight and save us with a super-simple solution. We can, however, come up with a pretty simple solution using a range-based for-loop.
// Example 3c (C++11) // thing.cpp bool Thing::findConfigElementById(int id, ConfigElement *element) const { for (const auto &elem : m_configElements) { if (elem.id == id) { *element = elem; return true; } } return false; }
It is important to write
const auto &elem instead of
auto elem in the for-loop. The latter form would copy the current element into the loop variable
elem in each iteration (see the implementation of the range-based for-loop for details). The former form with the constant reference avoids these copies – and is more efficient.
The solution shown in Example 3c is as efficient and as general as the solution with the
find_if algorithm (Example 3b). On top of that, it is simpler to read and write.
This result is typical for almost all of the 900+ for-loops: The range-based for yields simpler code than the STL algorithms. The reason is that STL algorithms with lambda expressions tend to be pretty lengthy and hence feel a bit clumsy. However, we don’t have to say good-bye to the advice of “preferring algorithm calls to handwritten loops”, as Jossutis points out in [StandardLibrary]:
Historically, one of the most important algorithms was for_each(). […] Note, however, that since C++11, the range-based for loop provides this behavior more conveniently and more naturally […]. Thus, for_each() might lose its importance over time.
This settles it: range-based for is an algorithm in disguise!
I have bad news. We are not yet done with improving our function. The function violates the most important principle of object-oriented design: the single-responsibility principle! Its first responsibility is to check whether there is an element matching a given criterion. Its second responsibility is to return the element itself through its second parameter
element.
We can fix this by making
findConfigElementById() return an object of type
ConfigElement. By checking the validity of the returned object, clients can figure out whether the container holds an element satisfying the given criterion. Let us put this in code.
// Example 3d (C++11) // thing.h struct ConfigElement { ... bool isValid() const { return id != -1; } }; // thing.cpp ConfigElement Thing::findConfigElementById(int id) const { for (const auto &elem : m_configElements) { if (elem.id == id) { return elem; } } return ConfigElement{}; } // client.cpp const auto element = aThing.findConfigElementById(5); if (element.isValid()) // do something with element else // do something else with element
Changing the interface of
findConfigElementById() improves the client code. We can define
element as constant, which isn’t possible in the original solution. We can express exactly whether we want to modify
element later on or not.
Changing the interface has another less visible advantage. It is slightly more efficient than the previous version (Example 3c). For the previous version, client code always creates a
ConfigElement object before it calls the function
findConfigElementById() – no matter whether the function finds a matching element or not. The latest version creates such a default object only if the function doesn’t find anything. Return-value optimisation makes sure that this object is constructed directly into the
element variable of the client code – without any copying taken place.
But that’s not all. When the function finds a value, the previous version copy assigns the found element to the return value (
*element = elem), whereas the latest version copy constructs its return value (
return elem). This is more efficient because the copy assignment must call the destructors on every member variable of the target of the assignment. Copy construction doesn’t incur this overhead.
So, following coding rules and principles pays off. We have turned the original implementation of
findConfigElementById() into a much simpler and slightly more efficient implementation. Good job!
Using the
replace_if Algorithm
We have looked at non-modifying for-loops so far. This is going to change now.
// Example 4a (old C++) // thing.h struct Parameter { int id; int value; }; QList<Parameter> m_group; // thing.cpp void ForLoopsTest::updateParameterInGroup(const Parameter ¶m) { Parameter current; for (int i = 0; i < m_group.size(); ++i) { current = m_group[i]; if (current.id == param.id) { m_group.replace(i, param); } } }
This function replaces every element
current in the list
m_group by the new element
param, if the IDs of
current and
param are equal. The function performs a
replace_if. We can easily rewrite this function with a range-based for.
// Example 4b (C++11) // thing.cpp void ForLoopsTest::updateParameterInGroup(const Parameter ¶m) { for (auto ¤t : m_group) { if (current.id == param.id) { current = param; } } }
Note that the loop variable
current is declared as a non-constant variable, because the assignment
current = param changes the object in the list
m_group referred to by
current.
The following solution using the
replace_if makes it slightly more obvious than the previous solution what’s going on. But, as usual, it’s a bit longer.
// Example 4c (C++11) // thing.cpp void ForLoopsTest::updateParameterInGroup(const Parameter ¶m) { replace_if(m_group.begin(), m_group.end(), [param](const Parameter ¤t) { return current.id == param.id; }, param); }
Note that we must use the non-constant begin and end iterator, because we change the underlying container by the replacements.
Using the
accumulate Algorithm
This is the first example, where the STL algorithm is less efficient than a range-based for-loop. The index-based for-loop runs through a list of string pairs, concatenates the string pairs in a certain format, and appends the concatenated string to the result.
// Example 5a (old C++) // thing.h QList< QPair<QString, QString> > m_versions; // thing.cpp QString Thing::getModuleVersions() const { QString result; int versionSize = m_versions.size(); for (int i = 0; i < versionSize; ++i) { result += QString("%1: %2\n").arg(m_versions[i].first).arg(m_versions[i].second); } return result; }
Rewriting this function with a range-based for-loop yields the following result.
// Example 5b (C++11) // thing.cpp QString Thing::getModuleVersions() const { QString result; for (const auto &version : m_versions) { result += QString("%1: %2\n").arg(version.first).arg(version.second); } return result; }
The for-loop accumulates the result line by line. Hence, the
accumulate algorithm from the
numeric header should be a good match.
// Example 5c (C++11) // thing.cpp #include <numeric> using namespace std; QString Thing::getModuleVersions() const { return accumulate(m_versions.begin(), m_versions.end(), QString{}, [](const QString &result, const QPair<QString, QString> &version) { return result + QString("%1: %2\n").arg(version.first).arg(version.second); }); }
The third argument
QString{} in the
accumulate call is the initial value of the accumulated result. In each iteration, the algorithm concatenates the
result accumulated so far with a new value and assigns this concatenated string to the accumulated result. The range-based for-loop does not need to compute this concatenated string but can simply append the new value to the accumulated result. Furthermore, if the accumulated type (here
QString) does not support move semantics or does not use implicit sharing like
QString or Qt’s container types, assigning the concatenation to the accumulated result performs a deep copy.
Hence, the range-based for solution is more efficient than the
accumulate algorithm and should be the preferred solution.
Using the
copy Algorithm on a C-Style Array
The following example copies data from one C-style array – starting at the third position – to another C-style array.
// Example 6a (old C++) // thing.h static const quint8 UDS_CAN_OFFSET = 2; static const quint8 SIZE_CAN_MESSAGE = 8; static const quint8 SIZE_UDS_MESSAGE = 200; quint8 m_udsMessage[SIZE_UDS_MESSAGE]; // thing.cpp void Thing::convertCanToUdsMessage(const quint8 *canMessage) { for (quint8 i = UDS_CAN_OFFSET; i < SIZE_CAN_MESSAGE; ++i) { m_udsMessage[i - UDS_CAN_OFFSET] = canMessage[i]; } }
Even before C++11, we were able to replace the handwritten loop by the
copy algorithm. The for-loop shrinks to a single line.
// Example 6b (old C++) // thing.cpp #include <algorithm> using namespace std; void Thing::convertCanToUdsMessage(const quint8 *canMessage) { copy(canMessage + UDS_CAN_OFFSET, canMessage + SIZE_CAN_MESSAGE, m_udsMessage); }
The
copy call copies the elements from index
2 to index
SIZE_CAN_MESSAGE - 1 in the array
canMessage to the array
m_udsMessage. The destination array
m_udsMessage must be big enough to store all the copied elements.
The big problem with the above implementations is that they use C-style arrays. CAN messages can be longer than 8 bytes. The above functions would simply ignore all additional bytes. UDS messages are typically much shorter than 200 bytes. So, the functions waste memory. It would be a good idea to replace the C-style array by
std::vector or
QVector, which is actually what rule #77 of [CodingRules] (“use vector instead of arrays”) suggests.
Before we switch from C-style arrays to
QVector, we should rewrite the above function such that it works both with C-style arrays and
QVector. We would need the iterator functions
begin() and
end(), which are provided by a class like
QVector but not by a built-in type like a C-style array. C++11 comes to our rescue with the global versions of
begin() and
end() taking a container as their argument.
There is one little problem left. We can apply the global
begin() and
end() functions only to C-style arrays whose size is known. By passing the
canMessage as
const quint8 *canMessage or
const quint8 canMessage[], we strip off the size information. We can fix this by passing a reference to the array
canMessage of fixed size
SIZE_CAN_MESSAGE. This is written in a slightly capricious way as
const quint8 (&canMessage)[SIZE_CAN_MESSAGE].
// Example 6c (C++11) // thing.cpp void Thing::convertCanToUdsMessage(const quint8 (&canMessage)[SIZE_CAN_MESSAGE]) { copy(begin(canMessage) + UDS_CAN_OFFSET, end(canMessage), begin(m_udsMessage)); }
Now, we can simply change the type of the parameter
canMessage to
const QVector<quint8> & – without changing the implementation of our function.
// Example 6d (C++11) // thing.h static const quint8 SIZE_UDS_MESSAGE = 200; quint8 m_udsMessage[SIZE_UDS_MESSAGE]; // thing.cpp void Thing::convertCanToUdsMessage(const QVector<quint8> &canMessage) { copy(begin(canMessage) + UDS_CAN_OFFSET, end(canMessage), begin(m_udsMessage)); }
If we change the type of
m_udsMessage to
QVector<quint8> as well, we must make sure that
QVector reserves enough space to store all the elements from
canMessage. Otherwise, the
copy algorithm will crash, because it accesses non-existing indices of the target vector
m_udsMessage.
Reserving enough space for the vector
m_udsMessage undoes the advantage of using a vector over a C-style array. The remedy is to use
back_inserter(m_udsMessage) instead of
begin(m_udsMessage). The
back_inserter() makes sure that the vector is big enough, before it copies an element to a non-existing position in
m_udsMessage.
// Example 6e (C++11) // thing.h QVector<quint8> m_udsMessage; // thing.cpp void Thing::convertCanToUdsMessage(const QVector<quint8> &canMessage) { copy(begin(canMessage) + UDS_CAN_OFFSET, end(canMessage), back_inserter(m_udsMessage)); }
The downside is that this version does not work with C-style arrays any more. It crashes for C-style arrays. Well, we cannot have everything.
This last version (Example 6e) would typically be the final step in a big refactoring, where we replaced C-style arrays by vectors. It is good proof of rule #77 from [CodingRules] that we should use vectors instead of C-style arrays. We eliminated quite a few opportunities to shoot ourselves in the foot.
Note that this example is one of the rare cases, where we cannot replace an index-based for-loop by a range-based for-loop. However, we can get rid of the indices by using the
copy algorithm.
Conclusion
C++11’s new range-based for turns out to be a pretty powerful feature. When we rewrite handwritten for-loops with the new range-based for, the result is almost always simpler and often more efficient. Range-based for-loops are always simpler than iterator-based for-loops. Well, that was the main reason why range-based for was introduced in C++11, wasn’t it?
With the introduction of lambda expressions in C++11, we can consider using STL algorithms seriously for the first time – instead of handwritten for-loops. Lambda expressions are more flexible, more powerful and simpler to write and read than the function objects from the pre-C++11 era. As the examples above show, STL algorithms with lambda expressions tend to be lengthier than range-based for-loops. However, STL algorithms always state explicitly what they do. STL algorithms and range-based for have very similar performance most of the times.
The advice of rule #84 from [CodingRules] to “prefer algorithm calls to handwritten loops” is very good advice. And don’t forget that the range-based for is a powerful, yet simple replacement of the
for_each algorithm. The rule should be updated to: “prefer algorithm calls (including range-based for) to handwritten loops”. Range-based for will often be your first choice, before you fall back to STL algorithms with lambdas.
References
- [EffectiveCpp11] Scott Meyers. Effective Modern C++: 42 Specific Ways to Improve your Use of C++11 and C++14. O’Reilly, 2015
- [CodingRules] Herb Sutter, Andrei Alexandrescu. C++ Coding Standards: 101 Rules, Guidelines, and Best Practices. Pearson Education, 2005
- [StandardLibrary] Nicolai M. Jossutis. The C++ Standard Library, 2nd edition. Pearson Education, 2012
|
http://www.embeddeduse.com/2016/05/13/simplifying-loops-with-cpp11/
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
Opened 12 years ago
Closed 12 years ago
Last modified 11 years ago
#1777 closed defect (fixed)
sqlite backend has small bug in date conversion
Description
Here's a diff for the sqlite backend I was just experiencing. Part of the problem was that the tables were created with a different ORM (sqlobject) that uses a different name for the time stamp. It also need another flag to read it.
Index: django/db/backends/sqlite3/base.py
===================================================================
--- django/db/backends/sqlite3/base.py (revision 2832)
+++ django/db/backends/sqlite3/base.py (working copy)
@@ -11,6 +11,8 @@
Database.register_converter("time", util.typecast_time)
Database.register_converter("date", util.typecast_date)
Database.register_converter("datetime", util.typecast_timestamp)
+Database.register_converter("timestamp", util.typecast_timestamp)
+Database.register_converter("TIMESTAMP", util.typecast_timestamp)
def utf8rowFactory(cursor, row):
def utf8(s):
@@ -35,7 +37,9 @@
def cursor(self):
from django.conf import settings
if self.connection is None:
- self.connection = Database.connect(settings.DATABASE_NAME, detect_types=Database.PARSE_DECLTYPES)
+ self.connection = Database.connect(settings.DATABASE_NAME,
+ detect_types=Database.PARSE_DECLTYPES|Database.PARSE_COLNAMES)
+
# register extract and date_trun functions
self.connection.create_function("django_extract", 2, _sqlite_extract)
self.connection.create_function("django_date_trunc", 2, _sqlite_date_trunc)
diff from svn
|
https://code.djangoproject.com/ticket/1777
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
Uncommon classes need explicit imports
Widely used classes, such as those in java.io and java.util, are well known to the typical Java programmer. When importing such classes, it's reasonable to use an abbreviated style:
import java.io.*;
import java.util.*;
When importing classes that are not among the most widely used, one should probably use another style, in which each class has an explicit import statement. If a class is unfamiliar to a reader, an explicit import makes it easier to find related documentation.
Example
For example, if a class imports items from the Apache Commons FileUpload tool, then instead of :
import org.apache.commons.fileupload.*;one should likely use the more explicit style :
import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.FileItem; ...etc...
See Also :
Would you use this technique?
|
http://javapractices.com/topic/TopicAction.do;jsessionid=BEB3F81764028EA8F5354F661C2330C5?Id=30
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
I have a word list and a file containing a number of anagrams. These anagrams are words found in the word list. I need to develop an algorithm to find the matching words and produce them in an output file. The code I have developed so far has only worked for the first two words. In addition, I can't get the code to play nice with strings containing numbers anywhere in it. Please tell me how I can fix the code.
EDIT: Oops, I left the x and y uninitialized, causing the code to crashEDIT: Oops, I left the x and y uninitialized, causing the code to crashCode:#include <iostream> #include <fstream> #include <string> using namespace std; int main (void) { int x = 0, y = 0; int a = 0, b = 0; int emptyx, emptyy; int match = 0; ifstream f1, f2; ofstream f3; string line, line1[1500], line2[50]; size_t found; f1.open ("wordlist.txt", ios::in); f2.open ("file.txt", ios::in); f3.open ("output.txt", ios::out); //stores content into string arrays if (f1.is_open() && f2.is_open()) { while (f1.eof() == 0) { getline (f1, line); line1[x] = line; x++; } while (f2.eof() == 0) { getline (f2, line); line2[y] = line; y++; } //finds position of last elements emptyx = x-1; emptyy = y-1; //matching algorithm for (y = 0; y <= emptyy; y++) { for (x = 0; x <= emptyx; x++) { if (line2[y].length() == line1[x].length()) { for (a = 0; a < line1[x].length(); a++) { found = line2[y].find(line1[x][a]); if (found != string::npos) { match++; line2[y].replace(found, 1, 1, '.'); if (match == line1[x].length()) { f3 << line1[x] << ", "; match = 0; } } } } } } f1.close(); f2.close(); f3.close(); } //file access error else cout << "Input error."; return 0; }
|
https://cboard.cprogramming.com/cplusplus-programming/139010-finding-anagrams-word-list.html
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
.NET Technology
By
Aruna Paramasivam, Associate
Jeff Gellman, Technology Manager
ViewPoints
LiquidHub, Inc.
l
500 East Swedesford Road
l
Suite 300
l
Wayne, PA 19087
l
484.654.1400
l
ViewPoints
2
Topics covered in this paper include:
¾
The .Net Framework
¾
.Net Architectural Overview
¾
.Net: A Platform for Enterprise Web Services
¾
Deployment Considerations
Overview
This LiquidHub white paper is intended to provide a high-level overview, in non-technical terms, of
how .NET technology works, and how it can be employed toward business goals. The vision of .NET is
explained, and a summary of the components of the unique .NET framework follows. The value that .NET
applications can bring to an organization is detailed, as are a few of the existing short comings in .NET
technology. The ultimate goal of this white paper is to provide business decision-makers with a high-
level outline of .NET and its capabilities, and to assist readers in determining whether to invest in further
examining this burgeoning technology.
What is Microsoft .NET?
Microsoft .NET, or simply .NET, is a term that has stealthily but rapidly moved into software development
nomenclature in the last few years. .NET is considered by many to be the next step in the Internet
revolution. The .NET concept dates back to 1999 when it was a part of a discussion of Next Generation
Windows Services. Before the derivation of .NET, the acronym of choice by Microsoft was DNA – Distributed
internet Architecture. While .NET is immersed in this notion, it has by far surpassed its initial conception.
To fully exploit the potential of the Internet and the web-based applications it enables, a robust and easily
integrated architecture is required. Microsoft has filled this void with the .NET vision. With successful
promotion by Microsoft and widespread acceptance by companies, .NET has the potential to become the
standard foundation for building powerful yet flexible Internet-centric applications.
The .NET initiative is based on an entirely new architecture in comparison to previous versions of Microsoft
tools. It is intended to elevate the development environment to a new level of sophistication, capability
and ease of use. .NET provides Internet users with a way of “programming the Web,” giving us a platform
for the development of interoperable Web applications. In broad terms, then, .NET can be thought of as
software that connects information, people, systems and devices.
Definition
According to Microsoft, .NET is a “revolutionary new platform, built on open Internet protocols and
standards, with tools and services that meld computing and communications in new ways.” .NET is billed
as a means for “connecting a world of information, people, systems and devices together to radically
improve communication and business performance” regardless of the platform used. A more practical
way of explaining the concepts behind .NET would be:
¾
It is a new environment for developing and running software applications
¾
It provides the framework for an Internet-centric industry standard that makes it possible to tie
together applications, information and data sources using Web Services
¾
It enables software to become platform and device-independent.
ViewPoints
3
¾
It employs many standard run-time services available to components written in a variety of
programming languages
¾
It has inter-language and inter-machine operability
Distributed Computing
Microsoft .NET uses distributed computing, as opposed to the typical two-node client/server systems
that are predominant today. Distributed computing is a programming model where processing can
occur in numerous points throughout a network. Developers can thus determine the most logical node
for processing to take place, whether at a server level, personal computer, handheld device or other
smart device. This makes the concept of .NET particularly efficient and creates a true open-architecture
environment. Systems that use such distributed computing are known as distributed applications. .NET
provides a robust and secure environment for the development and execution of distributed applications.
Web Services
The coordination and execution of processing that occurs in distributed applications is enabled by Web
Services. Web Services are units of code that allow programs written in different programming languages
and on different platforms to communicate and share data through standard Internet protocols. Such
protocols include Extensible Markup Language (XML), Simple Object Access Protocol (SOAP), Web
Services Description Language (WSDL), and Universal Description, Discovery, and Integration (UDDI).
In a typical .NET application, SOAP lies above the XML layer. SOAP is an emerging standard for transmitting
messages across the Internet. SOAP facilitates application-to-application interoperation between multiple
processing points and geographic sites by exploiting the Internet. WSDL provides a means to describe
the basic format of these requests, whether the underlying protocol is SOAP, XML or other encoding.
WDSL is a key component of what is known as the UDDI initiative to provide directories and descriptions
of online services for E-commerce purposes.
Figure 1: .NET Web Services
ViewPoints
4
Web Services comprise a platform-independent method that enables applications to communicate and
share data over the Internet, as defined by public organizations such as W3C.
Languages Supported
Out of the box, Microsoft currently provides support for the following languages:
¾
Microsoft Visual Basic .NET
¾
Microsoft Visual C#
¾
Microsoft Visual J#
¾
Microsoft Visual C++ .NET
¾
Microsoft Jscript
Additionally, third parties provide support for languages such as Cobol, Fortran, Perl, Eiffel, SmallTalk and
Python.
For a language to compile and execute within the .NET framework, it must conform to what is known as
the Common Language Specification (CLS). Unparalleled language interoperability is available within the
.NET framework because these languages adhere to the Common Type System (CTS). These languages all
have the ability to support a rich set of data types that are encompassed by CTS.
Platforms Supported
The .NET Runtime is compatible with Windows XP, Windows 2000, NT4 SP6a and Windows ME/98.
Windows 95 is not supported. It is important to note that some parts of the framework do not operate
on all platforms. For instance, ASP.NET is only supported on Windows XP and Windows 2000. In addition,
Windows ME/98 cannot be used for development purposes. Furthermore, Internet Information Services
(IIS) is not supported on Windows XP Home Edition, and therefore cannot be used to host ASP.NET.
However, the ASP.NET Web Matrix server does indeed run on the Windows XP Home edition. This opens
up the environment to ASP.NET users. (See for more information on this subject)
.NET Tools
The following tools can be used to develop .NET applications:
.NET Framework SDK
This SDK is free and can be downloaded from the Microsoft site. It contains compilers for C#, C++, VB .NET
and several other utilities that are useful for development.
ASP .NET Web Matrix
This is a free ASP .NET development environment provided by Microsoft. This can be particularly
advantageous for users of XP Home Edition, since it opens up the ASP .NET environment to those machines,
which as mentioned above, cannot run IIS. The ASP .NET Web Matrix is available on the Microsoft site. The
download includes a GUI as well as a simple web server that can be used instead of IIS to host ASP .NET
applications.
ViewPoints
5
Microsoft Visual Studio .NET
Microsoft Visual Studio .NET includes support for all the Microsoft languages such as C#, C++, and VB
.NET, with extensive wizard support. MS Visual Studio .NET constitutes the core of .NET development.
It provides a complete development platform to design, develop, debug and deploy .NET applications
and Web Services. It comprises tools for building Web and Windows applications as well as Web Services
and also has a full set of data access tools. There are also complete error -handling features available for
local debugging, remote debugging and tracing. Visual Studio .NET is available in Standard, Professional,
Enterprise Developer and Enterprise Architect versions.
In general, Microsoft Visual Studio .NET should be the default means for developing and executing .NET
applications. It greatly simplifies the process of creating Web Service client- or server-applications and
provides built-in support for the entire .NET development process.
Figure 2: .NET Framework and Visual Studio .NET
The .NET Framework
The .NET framework provides the foundation for developing, deploying and running Web Services and
.NET-based applications. It is a standards-based, multi-language application execution environment that
provides the necessary compile-time and run-time basis for building and running these Web Services
and .NET-based applications. The following paragraphs describe the major components of the .NET
Framework.
Common Language Runtime (CLR)
The CLR executes programs compiled from any Microsoft .NET compiled language. It is a controlled
ViewPoints
6
execution environment that not only compiles and runs code, but also displays bugs and handles runtime
services such as language integration, security and memory management.
Figure 3: Common Language Runtime
In addition, the CLR also provides the mechanism for sharing code between systems. This minimizes
conflicts between applications by enabling incompatible software components to coexist. Multiple
versions of program libraries can co-exist on one machine as a result, thereby preventing what is
commonly known as “DLL hell.” .NET applications are compiled and built on one platform. The bulk of the
functions performed by the CLR are done transparently, thereby simplifying the work of IT administrators.
The CLR is sometimes referred to as a managed environment. The code executed and managed by the
CLR is called managed code. Managed code supplies the information necessary for the CLR to provide
services such as memory management, cross-language integration, code access security, and automatic
lifetime control of objects. This managed code allows different programming languages to integrate fully
with each other. Such integration is available as all managed code in the CLR is compiled down to an
object-oriented intermediate assembly language called Microsoft Intermediate Language (MSIL).
As a modern, object-oriented assembly language, MSIL has instructions to define new classes, create
objects, call methods and access properties. Therefore, when individual languages provide syntax to
perform any of these tasks, the source code is compiled down into MSIL containing special assembly
instructions. These commands, in turn, are compiled by the Just-In-Time (JIT) compilers into calls
to specific CLR services. These calls are what handle all common class and object creation, method
invocation and garbage collection services among other functions. The end result of this process is that
all .NET languages’ classes and objects are ultimately represented in memory in a common manner. This
commonality opens the door to allowing a class in one .NET language to inherit a class developed in
another .NET language. Inheritance across languages allows for true software reuse. Hence, the hundreds
of built-in and fully documented classes within the CLR are immediately reusable and extendable from
any .NET-compiled language.
ViewPoints
7
Figure 4: .NET Framework Class Library
The CLR, however, does not interpret this MSIL directly. Instead, the CLR loads this code on demand and
natively compiles it into machine code in just-in-time fashion before it is run. This approach, combined
with other techniques such as caching of compiled code, is what enables .NET to execute at native speeds
at all times. The interoperability fostered by the environment-independent model also aids in enabling
the feature of distributed computing, generating the open architecture of the .NET environment.
Class Libraries
The .NET Framework Class Libraries provide reusable code for common tasks such as data access and web
service development, as well as Web and Windows forms. The Libraries supply the resources needed to
build applications with data access, as well as web server and networking features. Framework classes
can be used as a model to illustrate how classes in the class libraries are reusable and extensible. All .NET
programming languages use the same framework classes. For example, multiple programs can use the
same Console class to display information on the screen. The console class is just one of many classes
within the System namespace. The System namespace contains many low level classes for mathematical
manipulation, garbage collection and other such functions. There are also a number of sub-namespaces
within “System” that are name-spaces in their own right. Here are a few examples:
¾
System.Collections: includes basic container classes such as ArrayList, SortedList, Stack and Queue
¾
System.Diagnostics: includes classes for tracing and debugging
¾
System.IO: holds classes for file IO such as Stream, MemoryStream, FileStream, Path and Directory
¾
System.NET: includes classes for network programming such as Socket, DNS, IPAddress, Connection
and HttpWebRequest
¾
System.Security: includes classes dealing with permissions and cryptography
¾
System.Threading: holds classes like Thread, ThreadPool, Mutex and Timeout
ViewPoints
8
¾
System.Web: includes classes that facilitate Web development
¾
System.Windows.Forms: holds classes needed for Win32 development such as Menu, Tooltip, Control,
¾
Button, Data-Grid and ScrollBar
¾
System.XML: provides classes for interacting with XML data
Security of the .NET Framework
The .NET Framework facilitates a wide range of flexible security options that can be implemented by
developers, administrators and users. he following is a high-level overview the security features provided
by the .NET framework.
Role-Based Security
Role based security grants access and privileges based on the user’s assigned roles and functions within an
application. Within the .NET environment, this is done via authentication and authorization. Credentials
such as user name and password are examined and when the user is authorized, authentication is
accomplished. After this is performed, application code then determines the role of the user and level of
access and permission is allocated to the user.
The .NET framework supports the following authentication protocols:
¾
Basic
¾
Digest
¾
NTLM
¾
Kerberos
¾
SSL/TLS client certificates
Authorization can be done in several ways in the .NET environment. For instance, XML can be used to
designate which users can access certain URLs. Custom authorization checks can also be created. Or,
to simplify further, developers can simply tap into existing Windows authorization mechanisms. These
authentication and authorization methods can be combined in numerous ways to build powerful yet
flexible security within the distributed computing model of .NET.
Evidence-Based and Code Access Security
Evidence-based and code access security are exemplified by:
¾
Code residing in a particular code directory
¾
Code coming from the Internet or Intranet
¾
Code bearing a certain hash value
¾
Code signed with a certain key
The type of code access security denotes what resources users within specific domains can access. This
layer of security provides administrators with additional granular control over the machines within their
domain. This additional security overlay ensures further protection from potentially dangerous code.
ViewPoints
9
Cryptography
Within the .NET framework, functions for encryption, digital signatures, hashing, and random number
generation encompass cryptography. The following algorithms are supported by the .NET framework:
¾
Symmetric encryption such as DES, TripleDES, or RC2
¾
Asymmetric encryption such as RSA or DSA
¾
XML digital signature specification and hashes such as MD5 or SHA1
These core security components, when combined and layered, provide a great degree of flexibility in the
various levels of security available to meet the different and varied needs of each .NET application.
Value of .NET Technology
After examining the .NET Framework, it becomes clear that there are numerous potential technical
advantages to adopting .NET technology.
Increased Application Reliability
The .NET framework provides improved reliability for development and execution of code thanks to
automatic version control of components and also the ability to isolate applications from one another. As
a result, there are no conflicts between applications and associated components. Web services and web
applications built on the .NET framework are capable of automatically detecting and recovering from
errors such as deadlocks and memory leaks to further ensure application availability to all users.
Better Performance
The .NET environment is able to provide better performance due to the advanced compilation and caching
techniques supported by the CLR. According to Microsoft, organizations that have moved from ASP to
ASP .NET have seen significant increases in speed. In some cases, this has even been in the range of 300-
500% increase, which is obviously quite substantial, especially where quick data access and information
transfer are key—as they almost always are.
Higher Level of Flexible Security
.NET provides a variety of security options for application directories, local environment variables,
databases, network servers, and printers. Evidence about origin and authorship of code and components
can be collected via the .NET framework. The runtime environment can then combine that evidence with
administrator-set or default security policies to make fine-grained decisions about whether to run that
application or enable it to access a particular resource. Using a combination of authentication, evidence-
based security and cryptography, policies can mandate that only applications originating from a particular
location or bearing a particular digital signature or Authenticode publisher signature can access certain
resources and perform certain operations.
Integration and Interoperability
The .NET framework fully supports existing Internet technologies, thereby allowing for complete
interoperability between HTML, HTTP, XML, SOAP, XSL, Xpath and other web standards. .NET applications
can thus integrate seamlessly with one another. With the use of open standard Web Services, data can
ViewPoints
10
be transferred between a wide variety of client devices, such as various computer operating systems,
cellular telephones, personal digital assistants (PDAs) and even game consoles. This level of integration
is potentially advantageous from both an internal and external perspective. Internally, applications
with external sources of data and information can still be integrated within networks by means of the
.NET framework. Externally, .NET technology can be used to integrate the products and services of an
enterprise into the business of its key clients or favored suppliers and vendors because of its platform
independence and ease of integration.
Decreased Programming Effort
Programming is generally easier within .NET, primarily because of the self-describing property of the CLR.
All code written for the .NET environment is delivered in packages. These packages are called assemblies–
one or more .EXEs and/or DLLs that represent a logical set of functionality. These files also include all
the metadata information to completely describe their contents. The CLR itself, as well as development
tools, can read this information for all sorts of purposes, from determining file dependencies, to verifying
versions, to automating the generation of client code to access the internal objects. CLR system classes can
enable developers to interrogate assemblies at runtime and query the component’s capabilities. Objects
can also be called dynamically from the scripting environment if needed. Furthermore, the metadata
system is extensible, allowing developers to add their own custom information to assemblies through
user-defined attributes. The metadata system also allows developers to write tools to later extract that
information for their own purposes. All these features significantly decrease the programming effort
involved in the .NET environment, providing increased productivity and allowing for simpler, quicker
application development.
Increased Developer Productivity
The .NET framework supports the integration of over twenty languages. Thanks to the multi-language
support of .NET, experienced developers do not have as steep a learning curve as may be presented
by another new technology. Components supported by .NET, even when written in different languages,
can continue to integrate with one another easily. This allows developers to choose the language with
which they’re most comfortable, thereby increasing individual developer productivity and allowing the
creation of development teams with varied experience and programming language capabilities. The
programming model within .NET is fairly intuitive. There is a large amount of code available in the class
libraries for reuse. The .NET framework transparently handles features such as memory management
without additional effort required by the developer.
Easier Deployment
To install and deploy a Windows-based application, there are typically several registry settings, files and
shortcuts that must be created. However, these steps are completely eliminated in the .NET environment.
.NET components are not referenced in the registry. Applications can be deployed to a client or server by
simply copying the application directory to the target machine with no registration necessary. To uninstall
a .NET application, only the application’s directory tree needs to be deleted. In addition, Windows-based
smart client applications can now be deployed to and up-dated on specific personal computers by
copying the necessary components to a Web server that can be accessed by the target end users.
Easier Administration
.NET applications are highly manageable. Application configurations are contained in XML files, which
ViewPoints
11
can be edited and updated using any text editor. Scriptable command-line tools and snap-ins are also
available, and they’re very easy to use and execute.
Business Advantages
To step back to the broader perspective of business goals, there are a number of economic and strategic
advantages driving the adoption of .NET technology and standardized Web Services. Several of the
technical benefits described above, such as higher level of security and increased reliability, also present
clear business advantages.
Accelerated Life Cycle Development
Applications can be developed quickly with .NET. Developers can focus on the needs of the applications
and eliminate mundane tasks such as memory allocation since this is automatically taken care of by the
.NET framework. Code can also be reused easily from the class libraries saving much development time.
Furthermore, beyond the advantages of object-oriented design, developers and business also benefit by
spending less time debugging when involved with a .NET application. The CLR within the .NET framework
supports a consistent exception-based error handling system. All errors in .NET code are handled the
same way. This allows for code in one language to throw an exception and have the exception caught in
another language.
In a .NET environment, business changes can be implemented more quickly within applications and with
much less programming effort and dependencies tracking. An example of how businesses can benefit
from .NET development and integration is Newport News Shipbuilding, which used .NET-connected
software to build an application to connect with partners. The company reported that it improved its time
to market by 19 percent by building and launching its new application with .NET technology.
Lowered IT Cost
Due to accelerated lifecycle development, and developers being able to use their existing skill sets for
programming in the .NET environment, grand-scale corporate IT costs can be reduced on many fronts.
With .NET speeding up implementation of applications, there is a measurable drop in development costs
by day. The ability to use existing Web Services also presents substantial savings, as will the opportunity
to use present development efforts for future business-driven changes. There is generally no significant
cost in retraining or hiring new developers when a .NET project is undertaken. Programmers can rely on
much of their existing skill-sets since .NET supports multiple programming languages.
Integration for Better Service and Lower Operating Costs
.NET technology makes integration between applications, the Internet and sources of data easier because
it is platform and device-independent. Using a standard framework reduces the cost, time and expertise
required to tie together separate applications. The .NET framework facilitates a Web Services environment,
which presents a standard framework within which applications can share data. Consequently, information
can be made available to any application or device type. Application-to-application transactions can use
an Internet-based communication link, which provides organizations with greater flexibility to conduct
their businesses. The ability to connect systems can have a significant impact on a company’s ability to
execute its core competencies, whether the need exists to connect a handful of internal applications or
to integrate with an extensive outside supply chain. For example, with .NET services, a company’s order
management system might now directly interface with a web-based credit verification system. Thorough
ViewPoints
12
integration between these two systems provides customers with quicker and more reliable transactions
resulting in better overall service and customer satisfaction.
In other cases, many smaller suppliers have never taken to Electronic Data Exchange (EDI) methods. Many
companies continue to use isolated computer systems and still rely on phone, fax and email methods.
However, with .NET connected software, their communication gaps can be bridged easily to lower overall
operating costs. Business and supply chain transactions can often be conducted so much more efficiently
with .NET integration that the ROI on development is nearly immediate.
Increased Mobility Support
With the .NET standard, data can be easily transferred to field workers via mobile devices using a variety
of communication methods. Such devices integrate directly with applications and data, reducing the
amount of time and effort required to obtain and transfer information. Increased mobility support can
present significant value depending on the type of business operations being supported. For example,
sales staff can now have easy access to data that may have been contained previously in isolated back-
end systems. With the use of familiar operating systems such as Windows XP, which has .NET capabilities,
information can be easily transferred to a wide range of smart devices. This allows field personnel to
analyze data they may require while still in the field, allowing employees to focus on their primary roles
rather than travel and administrative tasks.
Easier Web Development
Using ASP .NET, an application can be transformed into a Web service with just one simple line of code.
This is made possible because ASP scripts are morphed into ASPX files and IIS acquires a new ISAPI DLL
to run these files. This in turn allows both ASP and ASPX files to be handled on the same site. With Web
Forms, the foundation of ASP .NET, the HTTP code that displays the page and application code can be
physically separated. This makes for much simpler maintenance and easier code reuse. .NET thus allows
for quick development as well as easier maintenance of web-based applications.
Quick Value Obtained via Out-Of-The-Box .Net Compatible Solutions
Microsoft is providing several .NET connected applications that serve to provide out-of-the–box business
functionality. Without requiring that businesses develop systems from scratch, these applications
can be integrated into extant systems to provide .NET connectivity. For example, Microsoft Office XP,
Microsoft’s Office suite of desktop applications, is now .NET compatible. Office XP applications can now
be integrated quickly and easily into other .NET-connected applications and services. Microsoft Great
Plains Business Solutions, which is a common business management and accounting package, is also
now .NET compatible. The benefits provided by .NET can quickly be gained through the use of these of
out-of-the-box packages-for quick implementation and seamless integration.
Microsoft MapPoint .NET is another example of a fully .NET connected application. An XML Web service
provides the functionality for the .NET connection application to integrate dynamic mapping and
location services. One way to integrate this application effectively would be to use it within a sales force
automation (SFA) package that requires access to location and mapping information. This would enable
sales representatives who may be making in-person calls in various territories to be connected to the
information they need for travel and communication using a wide variety of devices.
ViewPoints
13
Another useful .NET connected application is Microsoft .NET Passport2, which is currently available at
no cost. .NET Passport is a web-based service that provides authentication and verification service to
consumers. A user may register with Passport and provide information such as name, address, email
and other data that they would normally submit during any web-based transaction. This user can then
automatically share this information with any other .NET passport connected site without having to re-
type and re-share this information. Microsoft .NET passport has a strong security policy and enables users
to maintain a personal profile online safely. Thanks to the provision of such basic software functions in
readily available forms, quick value can be obtained by using Microsoft .NET solutions.
Current Issues With .NET
As with any new technology, (having just been released in 2001) .NET is still evolving. There are still a
couple of areas where .NET falls short. It should be noted that Microsoft has shown a strong commitment
to improving and providing enhancements to existing .NET technology in many ways thus far. They have
released compilers for a range of languages and have submitted the CLR specification to open body
standards to broaden the horizons of languages that are compatible with the .NET framework. .NET
supports the use of other non-Microsoft databases such as Oracle and DB2. ADO .NET can be used to link
a database of choice with .NET applications; drivers are provided out of the box for Oracle and IBM DB2.
.NET has also garnered a substantial level of industry dedication. Independent technology developers
and value-added resellers all have vested interests in establishing a Web Services standard. It appears to
be well understood in the industry that if the .NET standard emerges and is successful, then enterprises
all stand to gain from an ever increasing span of capabilities, services, functionalities and features to add
value to their businesses. For the organizations with limited financial resources and technical expertise,
the option remains where they may gradually adopt .NET functionality as feasible, while leaving other
applications operational as they are.
Lack of Linux/Unix Direct Interoperability
There is no direct interoperability with .NET and Linux or Unix. However, this constraint may soon change
since Microsoft has submitted the CLR specification to open standards bodies. Presently, interoperability
between .NET programs and Linux/Unix based applications is still possible using Web Services as a link.
Migration of Existing Applications
Within Microsoft languages, there are many discrepancies between past versions and what .NET uses.
In the past, Visual Basic has been a popular choice of programming language for business applications.
Many systems have also been written in Visual C++. However, for the .NET environment, new versions of
both these languages have been created such that these older versions cannot run without changes. For
example, the memory protection that is incorporated in the CLR makes it difficult for C++ applications to
be moved into .NET without significant changes. As for VB .NET, there are numerous changes in syntax,
which need to be made. VB developers also need to adapt to static classes that are not instantiated as
opposed to the ordinary classes they are accustomed to.
Gartner Group analyst Michael Ricciuiti stated on CNET News.com (Oct 2002) that “a surprisingly large
amount of change” is usually required to move existing applications into the .NET framework. The Gartner
Group has concluded that only 40% of existing code written using Visual Basic 6 can be migrated to Visual
Basic .NET without “substantial redesign and coding.” In some cases, it can be very difficult to use .NET
technology within existing systems and where application migration is required. Significant development
ViewPoints
14
efforts, which consequently result in high costs, can be required. In such cases, developers will need to re-
write code completely, although no features will be gained. In addition, these programs have to be tested
thoroughly again for due diligence before implementation, resulting in significant quality assurance
efforts before complete deployment. The return for this cost, time and effort equates to a more efficient,
effective, secure and reliable application that takes advantage of the numerous benefits of the unique
.NET framework.
Conclusion
.NET has been designed as a technology architecture and development initiative, but it can also be
considered a business strategy. Companies providing .NET connected applications have the technical
and functional incentive to open up their applications and permit transfer of data via Web Services across
the Internet. .NET allows business leaders to focus on solving problems and creating opportunities rather
than on managing software programming efforts. The .NET framework takes away much of the “plumbing
and maintenance” generally associated with software development and condenses the work of actual
programming.
.NET applications simplify the task of developing and integrating complex application environments.
Using the concept of distributed computing, .NET ushers in a new open architecture model, with the
Internet as its core. With the elimination of platform and device dependence, .NET brings about seamless
integration and direct connectivity to computer, applications and handheld devices. Thus, data can easily
be accessed, transmitted and acquired as needed throughout enterprises. .NET allows businesses to use
the Internet as a means of worldwide communication by presenting a robust and stable open architecture
for the development of web applications. It provides a new level of reliability and security that was
previously unavailable in Internet-reliant applications. It should also be noted that .NET is still a fairly new
technology which was only announced in 2001 by Microsoft as a vision. Hence, not all associated problems
and issues that may be associated with it may have been located. Microsoft has made a commitment to
.NET and is dedicated in its promotion of this technology. Other partners and resellers in the industry are
also eager for the establishment of a standard framework for applications to share data since it is clear
there are numerous business advantages associated in adapting .NET applications. .NET provides another
avenue for the innovative enterprises, looking to focus their expertise on meeting the new accelerating
demands of business, with the financial resources and technical expertise to undertake a new venture.
References:
Notes
1 – See for additional information
2 – See for additional information
ViewPoints
15
About the Strategic Technology & Advancement Research (STAR) Team
The Strategic Technology & Advancement Research Team serves as the proving ground for our ideas.
STAR brings together the best and brightest of LiquidHub to encourage new thinking and develop
through leadership around technology. Breakthrough ideas emerge and are exercised by the Team, to
strengthen client engagements and educate industry leaders.
Log in to post a comment
|
https://www.techylib.com/en/view/scatteredneedless/.net_technology_liquidhub
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
Results 1 to 1 of 1
Thread: slmodem with kernel 2.6.19
- Join Date
- Dec 2006
- 3
slmodem with kernel 2.6.19
one was a .patch file that i personally could not get to work
After stairing at the patch file and the other things i ran accross on the net i came up with a fix
this was done with slmodem-2.9.11-20061021
after unpacking cd into slmodem-2.9.11-20061021/drivers
edit amrmo_init.c
remove this line:
#include <linux/config.h>
save and exit
cd .. back to slmodem-2.9.11-20061021
make like normal
this fixes the errors that look like this
/path/to/slmodem-2.9.11-20061021/drivers/amrmo_init.c:589: warning: passing arg 2 of `request_irq' from incompatible pointer type
make[4]: *** [/path/to/slmodem-2.9.11-20061021/drivers/amrmo_init.o] Error 1
hope this saves someone else a headache after upgrading to the new kernel.
|
http://www.linuxforums.org/forum/hardware-peripherals/80058-slmodem-kernel-2-6-19-a.html
|
CC-MAIN-2017-51
|
en
|
refinedweb
|
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
(API 8.0) How to know the trigger field of method @api.depends('field_1', 'field_2', ..., 'field_n') ?
Hello community friends.
I am working with the new api 8.0 of odoo
And Please I need you help...
I have two fields: field_1 and field_2:
field_1 = fields.Many2one(........, compute='_filling_method')
field_2 = fields.Many2one(........, compute='_filling_method')
... and the _filling_method:
@api.depends('field_1', 'field_2')
def _filling_method(self):
.......
How I can know what is the trigger field in the method? field_1 or field_2?
@api.depends('field_1', 'field_2')
def _filling_method(self):
if trigger == 'field_1':
......
if trigger == 'field_2':
.....
Is there any way?
Thanks a lot.!
Why do not you use:
@api.depends('field_1')
def _filling_method_AAA(self):
...
@api.depends('field_2')
def _filling_method_BBB(self):
...
And what if you have just one only field_1 (with its one compute method) that depends on field_2 and field_3, and you need to know which one triggers the method in order to give a value to field_1?
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
|
https://www.odoo.com/forum/help-1/question/api-8-0-how-to-know-the-trigger-field-of-method-api-depends-field-1-field-2-field-n-84654
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
Anonymous classes and methods in C#, Anonymous, as the name suggests is undesignated or unspecified. It is an interim data type whose properties can only be read but not manipulated.
The scope of the anonymous type is mainly local to the method where it is declared. Points to be noted in the case of anonymous types:
- Defined using the keyword new.
- They are the only reference type.
- The implicitly typed variable var is used to hold an anonymous type.
If two or more anonymous object initializers in an assembly specify a sequence of properties that are in the same order and that have the same names and types, then it will be treated as an instance of the same type by the C# compiler.
Let us take an example:
public class Student { public int StudentRoll { get; set; } public string StudentName { get; set; } public int age { get; set; } } class Program { static void Main(string[] args) { lList<Student> studentList = new List<Student>() { new Student(){ StudentRoll = 1, StudentName = "Jai", age = 19}, new Student(){ StudentRoll = 2, StudentName = "Jojo", age = 21}, new Student(){ StudentRoll = 3, StudentName = "Abhil",age = 22}, new Student(){ StudentRoll = 4, StudentName = "Adi",age = 20}, new Student(){ StudentRoll = 5,StudentName = "Shubham",age = 21}}; var studentNames = from s in studentList select new { StudentRoll = s.StudentRoll, StudentName = s.StudentName }; } }
In the above example, Student class is including various properties. In the Main() method of the above program, Linq select clause is creating an anonymous type that will include only StudentId and StudentName.
Restrictions of Anonymous Classes:
1.Anonymous classes can contain only public fields.
2.Anonymous class’s fields must all be initialized.
3.Anonymous class members are never static.
4.Anonymous class cannot specify any methods.
5.Anonymous cannot implement the interface.
Anonymous methods is an undesignated method which uses the delegate keyword followed by the name of the required method and its body. They can be easily used to assign handlers to events. We can declare the methods without parameters or use parameters to declare them. Let us take an example:
namespace AnonymousMethods { Public class MyClass { public delegate void MyDelegate(string message); public event MyDelegate MyEvent; public void RaiseMyEvent(string msg) { if (MyEvent != null) MyEvent(msg); } } class Call { Static void Main(striing[] args) { MyClass myClass1 = new MyClass(); myClass1.MyEvent +=delegate { myClass1.MyEvent += delegate(string message) { console.WriteLine(“your message is: {0}”, message); }; Console.WriteLine(“Enter your message”); string msg = Console.ReadLine(); myClass1.RaiseMyEvent(msg); Console.ReadLine(); } } }
The above example handles events with the help of anonymous methods.
Useful resource:
Can you tell how to do a anonamus calls nd messages? How to Track ip address.? How to steal messages.?(without victims phone). How to hack cctvs.? How Pishing Hacking works?. What is panic attack. Hacking.? What is sql injection how it works.
Reply me at @shoutout_india_0fficial
#Anonamus
|
http://knowledgetpoint.com/csharp/anonymous-classes-methods/
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
Ads
Hi,
here is my code:
package project1; public class dddddddddd { public static void main(String[] args) { System.out.println("dddddddddddddddd"); }
}
but output is as follows: run: java.lang.NoSuchMethodError: main Exception in thread "main" Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds)
please help me on this..
Thanks in Advance.
I checked your code on eclipse ide..there will be no problem in executing this code.
But if you are executing it using command prompt(CMD), you need to first compile it inside project1 folder as :
...\project1>javac dddddddddd.java
then you need to run it as :
java project1.dddddddddd
Hope this will solve your problem.
ya.. thanks a lot.... great absevation..
|
http://www.roseindia.net/answers/viewqa/Java-Beginners/17806-JAVA.html
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
Now that we built a skeleton framework to test using the Stripe REST API, storing and retrieving the API Key, we can perform actions. We are going to:
- Create a method called getListOfCharges in our StripeUtils class, where we can pass in how many charges we wish to retrieve.
- Create a data object to hold all the information we retrieve.
- Add functionality that turns the JSON object we get back, and add all information into the data object we created, using Google's GSON library.
What Our Framework Will Look LikeBy the end of this blog post, our automation framework will look like:
src/test/java
- data
- LoadProperties.java
- libraries
- StripeUtils.java
- maps
- CollectionOfCharges.java
- properties
- qa-properties.properties
- testcases
- Stripe.java
Design a Simple Data Object
Let's say we want to get the last Charge object using HTTPS, we would enter using the public Stripe API Key into our browser:
... Remembering, of course, that entering a non-public secret API key into a URL is a completely lousy idea! We will be remedying this later.
If you take a look at the JSON file returned it looks like:
{ "object": "list", "data": [ *** LOTS OF CHARGE DATA *** ], "has_more": true, "url": "/v1/charges" }
This means we need to create a Data Object to store information, we only have to worry about four parameters:
- A string named "object"
- Object array named "data"
- A boolean named "has_more"
- A string named "url"
Our Data Object will look like...
stripe.maps.CollectionOfCharges.java
public class CollectionOfCharges { String object; Object[] data; boolean has_more; String url; public String getObject() { return object; } public void setObject(String object) { this.object = object; } public Object[] getData() { return data; } public void setData(Object[] data) { this.data = data; } public boolean isHas_more() { return has_more; } public void setHas_more(boolean has_more) { this.has_more = has_more; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
Next, we need to get the data. We will be doing this with Apache Http Components.
Why Use Apache HttpComponents?From the Apache HttpClient Tutorial:
".
What Does Http Client Do?
"The".
Parts of a URI
A web address or URL -- Universal Resource Locator -- is a type of Uniform Resource Identifier, one that points to a physical location such as a server. A URI, though, is more abstract.
There are many parts to a URI as shown below:
scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
- Scheme: Can be web based (http or https), Transporting a file (ftp), or even an email (mailto). The Internet Assigned Numbers Authority keeps track of all schemes. ( LINK ).
- Authority:
- Optional username, or the username & password.
- Host, such as the domain name, registered name or hostname
- Optional port name such as :8088.
- Path: The subdirectory, such as /v1/charges.
- Query: Everything starting with the ? symbol in the URI is a query.
- URIBuilder then allows you to add names and values to Parameters, such as key and sk_test or limit and 3.
Get the Last Three Charges
Let's say you want to retrieve a list of charges from the API is passing into the getListOfCharges how many charge orders to get. What is the limit? One? Two? Five? Eight?
If we were manually testing if the API can retrieve the last three charges, we would enter the following code into our web browser to form the HTTP GET statement...
... And place the JSON parameters into something such as an Excel spreadsheet.
Instead we are going to use Apache Http Components to do the work for us. We are going to:
- Break the URI into different pieces and validate them with URIBuilder.
- Add the URI into a HttpGet class.
- Instantiate a new BasicCredentialsProvider class, and set credentials with the Stripe API key.
- Create using HttpBuilder an HTTP call holding the credentials.
- Store the call in a CloseableHttpClient.
- Execute the HttpGet statement, storing the results in a HttpResponse class.
- Examine the response's status line and status code to see if it the status was OK, with a value of "200". If not, we are going to throw an error.
Got that? ... No? Okay, we are going to walk through this again... We went through so many steps, I even lost myself!
URIBuilder
We are going to use URI Builder to construct the URI we will be using to connect to the API:
- Set the scheme to be https.
- Set the host to be api.stripe.com.
- Set the path to be /v1/charges.
- Set the parameter "limit" to be whatever limit has been passed.
URIBuilder uriBuilder = new URIBuilder(); uriBuilder.setScheme("https") .setHost("api.stripe.com") .setPath("/v1/charges") .setParameter("limit", limit.toString();
...Why use URI Builder instead of feeding the straight URL into the API? Validation:
- If you accidentally have a blank space in the URL, it will tell you exactly where there is an Illegal Character.
HttpGetWe are going to try the following:
- Build the URI according to the parameters we set up.
- Compose an HTTP GET Method based on the URI.
- Set up using BasicCrendentialsProvider the UsernamePasswordCredentials. We will add the Stripe API Key here.
- We then build with HttpClientBuilder and instantiate with CloseableHttpClient the credentials.
- Finally, we execute the Http Client using the HttpGet statement we set up.);
Check Status CodeAre there problems? Is the response anything but 200-OK? We are going to throw an error.
if (statusCode != 200) { String errorMessage = "ERROR: Attempting to Capture Charge: " + statusCode + "\n" + "Reason: " + response.getStatusLine().getReasonPhrase(); throw new TestException (errorMessage);
Convert Results into StringIf everything is successful, we are going to
- Take that response and get the entity.
- Convert the entity into a String format, using EntityUtils.toString.
String json = EntityUtils.toString(response.getEntity());
Use GSON
Once we have the JSON Feed as a String, we are going to use Google's GSON library to take the String and place it in the CollectionOfCharges class we just created.
chargesRetrieved = gson.fromJson(json, CollectionOfCharges.class);
... we will go over GSON a few blog posts from now.
Check for Errors
If there is anything wrong with:
- URI Synatax ... a URI Syntax Exception is thrown.
- If input or output cannot be read, an IOException is thrown.
... We are going to print a stack trace so we can figure out what went wrong.
catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace();
Putting it all together, our code looks like:
Adding getListOfCharges to StripeUtils.java.
public CollectionOfCharges getListOfCharges(Integer limit){ CollectionOfCharges chargesRetrieved = new CollectionOfCharges(); Gson gson = new Gson(); URIBuilder uriBuilder = new URIBuilder(); uriBuilder.setScheme("https") .setHost("api.stripe.com") .setPath("/v1/charges") .setParameter("limit", limit.toString()); try {); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { String errorMessage = "ERROR: Attempting to Capture Charge: " + statusCode + "\n" + "Reason: " + response.getStatusLine().getReasonPhrase(); throw new TestException (errorMessage); } String json = EntityUtils.toString(response.getEntity()); chargesRetrieved = gson.fromJson(json, CollectionOfCharges.class); client.close(); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return chargesRetrieved; }
Writing an API Test
If you go back to Stripe API Documentation, where it says List Charges, you will see the following:
{ "object": "list", "url": "/v1/charges",
... The name "object" should return the value "list". The name "url" should return "/v1/charges".
Let's make that the test!
First let's see if that is what is returned, with a quick little test we can put in the Stripe.java test class we created in the testcases folder during our last blog.
@Test public void test_printCollectionOfChargesParameters(){ Integer numberOfChargesReturned = 2; StripeUtils stripe = new StripeUtils(Locale.US); CollectionOfCharges charges = stripe.getListOfCharges(numberOfChargesReturned); System.out.println("Object: " + charges.getObject()); System.out.println("URL: " + charges.getUrl()); }
Running this test we get:
[TestNG] Running: C:\Users\tmaher\.IdeaIC15\system\temp-testng-customsuite.xml Object: list URL: /v1/charges =============================================== Default Suite Total tests run: 1, Failures: 0, Skips: 0 ===============================================
... We now can absolutely confirm the output matches the documentation -- Always a good thing!
Let's changes the print statements to assert statements...
... And also refactor the getObject to getObjectType. The charge objects are stored in "data". It seems to be more of an object type that an actual object, so let's name it as such. With IntelliJ, I can Refactor -> Rename, and the name of the method gets changed everywhere in our automated test.
); assertEquals(charges.getObjectType(), expectedObjectType); assertEquals(charges.getUrl(), expectedUrl); }
Hrm. I still am not happy with it. This test? It'll run, and it will pass or fail depending on if the expected parameters matches what is actually captured, but I prefer some type of logging explicitly spelling out exactly:
- What is the test is supposed to do?
- What is the expected output?
- What is the actual mark?
- In plain English, does it (PASS) or does it (FAIL)?
The assert statement isn't enough for me. Let's borrow some code I whipped up in my last project to handle reporting, and place it in the test class.
checkMatchingValues:
private boolean checkMatchingValues(String testHeading, Object actualValue, Object expectedValue) { String successMessage = "\t* The Expected and Actual Values match. (PASS)\n"; String failureMessage = "\t* The Expected and Actual Values do not match! (FAIL)\n"; boolean doValuesMatch = false; System.out.println(testHeading); System.out.println("\t* Expected Value: " + expectedValue); System.out.println("\t* Actual Value: " + actualValue); if (actualValue.equals(expectedValue)) { System.out.println(successMessage); doValuesMatch = true; } else { System.out.println(failureMessage); doValuesMatch = false; } return doValuesMatch; }
... Now, I might be able to get the output I like to see.
The new test looks like:
); String actualObjectType = charges.getObjectType(); checkMatchingValues("Verify that the Returned Collection Object types match", actualObjectType, expectedObjectType); assertEquals(actualObjectType, expectedObjectType, "ERROR: The Object types do not match!"); String actualUrl = charges.getUrl(); checkMatchingValues("Verify that the Returned Collection URLs match", actualUrl, expectedUrl); assertEquals(actualUrl, expectedUrl, "ERROR: The urls do not match!"); }
... And the output of the test looks like ...
[TestNG] Running: C:\Users\tmaher\.IdeaIC15\system\temp-testng-customsuite.xml Verify that the Returned Collection Object types match * Expected Value: list * Actual Value: list * The Expected and Actual Values match. (PASS) Verify that the Returned Collection URLs match * Expected Value: /v1/charges * Actual Value: /v1/charges * The Expected and Actual Values match. (PASS) =============================================== Default Suite Total tests run: 1, Failures: 0, Skips: 0 ===============================================
Nice output. It's clear cut. You know exactly what is being tested. Call it the manual tester in me, but I get suspicious of positive results as much as negative results. If everything is spelled out, it is easier to spot an error.
If you want to examine the code, it can be viewed on GitHub at.
Next week, we will examine Google GSON more closely, and write a few more Stripe tests on capturing charges.
Until then, happy testing!
NEXT: From JSON to Object: HttpEntity and GSON.
|
http://www.tjmaher.com/2016/02/restful-testing-with-stripe-using.html
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
[This article was contributed by the AppFabric team.]
In the Windows Azure AppFabric May 2011 CTP, we released enhancements to Service Bus including the new message-oriented middleware features around Queues and Topics. More details regarding these features can be found here: Introducing the Windows Azure AppFabric Service Bus May 2011 CTP. These enhancements will go live with an update to the commercially available service in a few months.
Currently we have two versions of the Access Control service in our production environment: the January 2010 version and the April 2011 version. More details regarding this can be found here: Windows Azure AppFabric April release now available featuring a new version of the Access Control service!.
Until the production Service Bus is updated it continues to use the January 2010 version of the Access Control service. But once Service Bus is updated it will also be able to use the new April 2011 version of the Access Control service. Once the Service Bus update goes live we strongly recommend to customers to update their Service Bus solutions to use the new version of the Access Control service for two reasons:
-.
Following are explanations on the current state, what will change once Service Bus gets updated, and how you can prepare.
Current state in the production environment
In the Windows Azure AppFabric Management Portal, the two versions of Access Control are labeled ACSV1 for the January 2010 release and ACSV2 for the April 2011 release.
Today when you create a new Service Bus namespace, a matching ACSV1 namespace is automatically created with the namespace suffix “–sb”. This ACSV1 namespace is used by Service Bus.
The two versions of the Access Control service support the same protocol and authorization token format that is expected by Service Bus today (OAuth WRAP SWT), and are fully compatible for all runtime operations. However, ACSV2 supports a new, richer management service protocol based on OData. While the two services are runtime-compatible, they are not compatible for code performing automated setup of access control rules and service identities via the management service.
Following the Service Bus update
For backwards-compatibility with existing applications, Service Bus namespaces that exist in the production environment at the time of the update will not be automatically switched over to ACSV2, and will continue to use ACSV1. You will need to migrate these namespaces from ACSV1 to ACSV2 on your own, coordinated with updates to your code that calls the management service.
As we update the service in a few months, we will provide tooling and step-by-step guidance for how to perform the migration from ACSV1 to ACSV2.
While we will provide detailed guidance as we release the update, the migration process will generally involve the following test-then-migrate sequence of steps:
-.
Running applications should not experience any service disruption resulting from this switch.
The version differences and migration will mostly affect applications that automatically provision rules in ACSV1 using the management service. Since the management service differs between ACSV1 and ACSV2, the guidance will suggest a process that can be outlined as follows:
-.
How to prepare
Our LABS environment at already includes the enhancements to Service Bus, as well as the new version of Access Control. Hence, you can use this environment, free of charge, to start planning your migration and test it.
In the LABS environment already today, when customers create new Service Bus namespaces the system will generate a new Access Control namespace with the “-sb” suffix, but that namespace is created in ACSV2. This will be the production experience when we release the update to Service Bus in a few months.
You can immediately start developing this new management code path creating rules against ACSV2 against the versions of Service Bus and Access Control that are available in the May 2011 CTP environment at.
As always, if you have any questions or feedback feel free to visit the Connectivity for the Windows Azure Platform forum.
The AppFabric Team.
|
https://azure.microsoft.com/ru-ru/blog/windows-azure-appfabric-service-bus-access-control-federation-and-rule-migration/
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
Handling ajax request in WebForms
Elegant way to do AJAX in WebForms
In case you want to add JQuery Ajax calls to your page, you would basically need to add one more page which will be invoked with Ajax call.
In order to reduce number of physical pages you can reuse the same page, but make it act differently for normal GET/POST HTTP request and totally different for Ajax GET/POST HTTP request.
To determine whether request is AJAX or not you can use extension method described in this article.
The main idea is to render one content for normal and one for AJAX request. For this purpose we use placeholder for rendering AJAX content.
Handling of request should be done on Page_Init handle.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Asp.Net; using System.IO; public partial class _Default : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { if (Request.IsAjaxRequest()) { Response.Clear(); StringWriter sw = new StringWriter(); this.phAjaxContent.Visible = true; this.phAjaxContent.RenderControl(new HtmlTextWriter(sw)); Response.Write(sw.ToString()); Response.End(); } } }
Extension method IsAjaxRequest is coming from custom library Asp.Net which I build and which is contained in attachment for this article. This extension method is described in this article. You can add it it to you own dll, compile it and use the same way it is used here.
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
|
http://dejanstojanovic.net/aspnet/2014/march/handling-ajax-request-in-webforms/
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
action
set name indexer? modifier-expression? to value set string-sink-function-call to value
In the first form,
set assigns a value to a shelf item; the shelf item's previous value is replaced
with the new value.
import "ombcd.xmd" unprefixed process local integer i local string s local switch w local bcd x set i to 78 set s to "Hello, World!%n" set w to true set x to 10.56
The value appearing on the right-hand side of a
set must have the correct type for the shelf
item appearing on the left-hand side of the
set, or a conversion function must
exist that can convert an instance of right-hand side's type to an instance of the left-hand side's type:
define string conversion-function value switch w as return w -> "TRUE" | "FALSE" process local string s local switch w initial { true } set s to w
In the second form,
set invokes the given
string sink function; within the function
invocation,
#current-input is initially set to value.
define string sink function hexify (value string sink s) as using output as s repeat scan #current-input match any => t output "16r2fzd" % binary t again process set hexify (#main-output) to "Hello, World!%n"
When the type of the shelf item on the left-hand side is
stream,
set is equivalent to an
open of the
stream, writing to the
stream, then a
close. For this reason, any
modifiers that can be used with
open can also be used with
set:
process local stream s size 2 set s[1] with referents-allowed defaulting { "" } to "Hello, World!%n" set s[2] with referents-displayed to s
|
http://developers.omnimark.com/docs/html/keyword/296.htm
|
CC-MAIN-2017-34
|
en
|
refinedweb
|
- Post-processing (pre-delivery) plugins, which allow you to add processing logic after publication contents have been personalized.
- Distribution complete (post-delivery) plugins, which allow you to add processing logic after publication contents have been delivered.
Building and deploying custom post-processing (pre-delivery) publication extensions
The com.businessobjects.publisher.postprocessing.PostProcessingPluginHelper provides several static methods that can be used in post-processing plugins. For example, to add new artifacts, use createInfoObject method. The following code creates a text file info object.
ITxt textInfoObject = (ITxt) PostProcessingPluginHelper.createInfoObject(context, ITxt.PROGID, “text/plain”, null, null);
For detailed information on IPublicationPostProcessingPlugin, IPublicationPostProcessingContext, PluginTargetDestination, and PostProcessingPluginHelper, see the SAP BusinessObjects Business Intelligence Platform Java API Reference .
An example publication extension is posted at this blog post: Sample Publication Extension: Deliver shortcut to a BI platform folder based on personalization . This post processing publication extension creates a shortcut of the publication artifact in a folder based on the personalization. For example if you personalize on Country and have a folder for USA and Canada, then a shortcut for the publication artifact filtered to USA will be created in a USA folder, and a shortcut for the Canada document will be created in a Canada folder.
After the publication extension is built into a jar file, it needs to be deployed in the publication extensions directory. The default location of this directory is <Enterprise Dir>\java\lib\publishingPlugins. Once the extension was added, you have to restart the Adaptive Processing Server.
Adding a publication extensions to a publication
A publication extension can be added to a publication either programmatically or from the Central Management Console (CMC). The BI launch pad application does not allow you to specify publication extensions for a publication through the UI.
At this point it is assumed that you have already deployed the publication extension as described above on all computers that run the Adaptive Processing Server.
Below are the steps to add a publication extension via the CMC:
- Double-click a publication to open it. The “Properties” dialog box appears.
- Expand Additional Options, and click Publication Extension.
- In the Publication Extension Name box, type a name for the extension.
- In the Class Name box, type the fully qualified class name for the extension.
- (Optional) In the Parameter box, type a serialized string that your extension requires. What the parameter is would depend on how the extension was designed.
- To use the extension after processing but before delivery, above the Before Publication Delivery list, click the Add button. The extension is added to the Before Publication Delivery list.
- To use the extension after delivery, above the After Publication Delivery list, click the Add button. The extension is added to the After Publication Delivery list.
- Click Save.
- Repeat steps 2 to 8 for each extension you want to add.
To define the order in which to execute publication extensions, click Move Up or Move Down under the Before Publication Delivery list or the After Publication Delivery list.
As always great blog Christina, very useful and informative. Thanks a lot for sharing.
Regards,
Sohel
Thanks Sohel! this particular one was long over due 🙂
The fruit of patience is sweet 🙂
Excellent!!!
Thanks
Great and helpful article. I’ve created a basic publication extension that works. However, when I added additional functionality to it that requires external .JARs from a third-party, I can’t seem to get things to work. The publication log shows that it’s not able to find the necessary class. Short of putting the additional .JARs directly in to the <drive>\Program Files\Business Objects\common\4.0\java\lib\publishingPlugins directory I can’t seem to get it to work.
When I package my the third-party jars in my publishing plugin jar, it appears to ignore the class path and jars there. Is there any way to set the classpath for BO or have it find those jars without dumping them in the publishingPlugins directory?
It’s recommended to put all the custom jars (and dependencies) in <drive>\Program Files\Business Objects\common\4.0\java\lib\publishingPlugins because BOE will load all jars in that folder. This is how we avoid having to change the classpath.
Thanks,
Derrick
Also for the question on “When I package my the third-party jars in my publishing plugin jar, it appears to ignore the class path and jars there”, we only load classes inside jars inside the publishingPlugins folder. If you package 3rd party jars inside the publishing jars, it won’t be loaded. You can just put multiple jars (including the 3rd party ones) inside the publishingPlugins folder and it should work 🙂 .
Cheers,
Derrick
Got a chance to check this only now. Amazing Christina.
In my publication I define output file name as %SI_NAME%_%SI_OWNER%.%EXT% . Please how do I capture SI_NAME, SI_OWNER (from profile) and EXT in publication extension? I already have a functional publication extension using online examples but these examples captures artifact titles internal to cms. I am interestes in the physical file names of the publications. Thanks.
Hi Christina,
We are in the process of updating our CE Enterprise ver 10 Server to BOBJ 4.1 SP2 (using BOE Xi 3.1 as the intermediate as one cannot migrate directly) and encountered a puzzling issue in the test environment when using BOBJ 4.1 SP2.
I am new to Crystal as a whole relatively speaking (~ 1 year) and so am finding this daunting, especially when I’m not familiar with java.
Here’s our issue:
A former staff many moons ago must have set up a custom SDK coding for the Crystal Enterprise ver 10 where there is a “hidden” parameter that would automatically pass the value of the User security groups (ie. If you belong to Security Group A), then “A” will pass to the “vUsername” parameter automatically when an individual runs a Crystal Report. The report would, based on this, only show Group A’s data. User belonging to Group B would then only see Group B’s data, etc. This is working fine in Crystal Enterprise ver 10, but on the newly set up BOBJ 4.1 SP2 CMS server, we could not get the value to pass automatically.
I’m assuming we need to add this with a publication extension somehow. Would you be able to assist or direct me on how to get this set up as we’ve been puzzling over this for awhile now and we need to get this resolved asap.
thx!
Hi Jeff,
I no longer work on this area. I suggest to contact support about this or post it as a discussion for others to see, not as a comment on a blog.
Thanks,
Christina
Am getting an error such as cannot instantiate the class. Class not found.
Any suggstions would be much appreciated.
Java Code:
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.businessobjects.publisher.postprocessing.IPublicationPostProcessingContext;
import com.businessobjects.publisher.postprocessing.IPublicationPostProcessingPlugin;
import com.businessobjects.publisher.postprocessing.PluginTargetDestination;
import com.crystaldecisions.sdk.occa.infostore.IDestinationPluginArtifactFormat;
import com.crystaldecisions.sdk.occa.infostore.IInfoObject;
import com.crystaldecisions.sdk.occa.infostore.IInfoObjects;
import com.crystaldecisions.sdk.plugin.CeProgID;
public class TestPublishingPostProcessingPlugin implements
IPublicationPostProcessingPlugin
{
public Collection getTargetDestinations() throws Exception
{
Collection pluginTargetDestinations = new ArrayList();
pluginTargetDestinations.add(new PluginTargetDestination(CeProgID.DISKUNMANAGED,
IDestinationPluginArtifactFormat.CeDistributionMode.FILTER_NONE));
pluginTargetDestinations.add(new PluginTargetDestination(null,
IDestinationPluginArtifactFormat.CeDistributionMode.FILTER_NONE));
return pluginTargetDestinations;
}
public IInfoObjects handle(IPublicationPostProcessingContext context) throws
Exception
{
FileWriter outFile = new FileWriter(“C:\\test\\PPLog” +
System.currentTimeMillis()+”.log”);
outFile.write(“hello!\n”);
ArrayList docs = context.getDocuments();
Iterator docIt = docs.iterator();
IInfoObjects objs = context.getInfoStore().newInfoObjectCollection();
while (docIt.hasNext())
{
IInfoObject obj = (IInfoObject)docIt.next();
outFile.write(obj.getTitle() + “\n”);
String newName = “Artifact – ” + System.currentTimeMillis();
outFile.write(“Renaming ‘” + obj.getTitle() + “‘ to ” + newName);
obj.setTitle(newName);
objs.add(obj);
}
outFile.close();
return objs;
}
}
|
https://blogs.sap.com/2013/06/24/need-additional-functionality-for-publications-write-your-own-custom-publication-extension/
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
org.netbeans.modules.bpel.debugger.ui.source.SeveralSourceFilesWarning
core-main #15dfacd63b8a
Integrated into 'main-golden', will be available in build *200902131548* on (upload may still be in progress)
Changeset:
User: Marek Slama <mslama@netbeans.org>
Log: #158504: Remove override of java.awt.Component.isValid().
release65-fixes #c45b6e24873e
Verified in GF ESBv2.1 build:20090501-1001
Created two BPEL processes with identical names and namespaces (e.g. two "Process"
projects in different directories with "test.bpel" files in them). Then attached BPEL
debugger to the runtime. Since there is ambiguity which process should debugged in case events
for this name/namespace arrived.It shows the attached dialog window.
Created attachment 81722 [details]
Warning window screenshot
|
https://netbeans.org/bugzilla/show_bug.cgi?id=158504
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
Get/set format flags.
The first syntax returns the current set of format flags for the stream.
The second syntax sets fmtfl as the format flags for the stream.
The stored format flags affects the way data is interpreted in certain input functions
and how it is written by certain output functions.
The values of the different format flags are explained in the fmtflags type reference.
The second syntax of this function sets the value for all the format flags of the stream. If you want to modify a single flag refer to setf and unsetf.
Parameters.
Return Value.
The format flags of the stream before the call.
Example.
// modify flags
#include <iostream>
using namespace std;
int main () {
cout.flags ( ios_base::right | ios_base::hex | ios_base::showbase );
cout.width (10);
cout << 100;
return 0;
}
This simple example sets some format flags for cout affecting the
later insertion operation by printing the value in hexadecimal base format padded right
as in a field ten spaces long.
See also.
setf, unsetf
fmtflags type, ios_base class
|
http://www.kev.pulo.com.au/pp/RESOURCES/cplusplus/ref/iostream/ios_base/flags.html
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
xsh - XML Editing Shell
xsh [options] script_or_command xsh [options] -al script [arguments ...] xsh [options] -aC command [arguments ...] xsh [options] -p commands < input.xml > output.xml xsh [options] -I input.xml -O output.xml commands xsh [options] -P file.xml commands xsh [options] -cD compiled_script.pl ....
See XSH2 manual page or
@ARGV (in
XML::XSH2::Map namespace). If used with
--commands or without
--load, the first argument should contain XSH commands and the rest are the passed to via
@ARGV.
Indicate, that the command-line arguments should be treated as input filenames. If used with
--commands or without
--load, the first argument should contain XSH commands. A XSH script specified with
--load or XSH commands specified with
--commands (or both in this order) are evaluated repeatedly on each input file. For example, running
$ xsh -l script.xsh -FC command file1.xml file2.xml ...
is equivalent to
$ xsh --stdin -aC command file1.xml file2.xml ... for $INPUT_FILENAME in { @ARGV } { $INPUT := open $INPUT_FILENAME; . "script.xsh"; command } ^D, XML::XSH2, XML::XSH2::Compile, XML::LibXML, XML::XUpdate,
|
http://search.cpan.org/~pajas/XML-XSH2-2.1.6/xsh
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
NAME
import - saves any visible window on an X server and outputs it as an image file. You can capture a single window, the entire screen, or any rectangular portion of the screen.
SYNOPSIS -channel type apply option to select image channels -colorspace type alternate image colorspace -comment string annotate image with comment
Copyright (C) 1999-2009 ImageMagick Studio LLC. Additional copyrights and licenses apply to this software, see or
|
http://linux.fm4dd.com/en/man1/import.htm
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
save_joystick_data man page
save_joystick_data — Saves joystick calibration data. Allegro game programming library.
Synopsis
#include <allegro.h>
int save_joystick_data(const char *filename);
Description
After all the headache of calibrating the joystick, you may not want to make your poor users repeat the process every time they run your program. Call this function to save the joystick calibration data into the specified configuration file, from which it can later be read by load_joystick_data(). Pass a NULL filename to write the data to the currently selected configuration file.
Return Value
Returns zero on success, non-zero if the data could not be saved.
See Also
load_joystick_data(3), set_config_file(3)
Referenced By
load_joystick_data(3), push_config_state(3).
version 4.4.2 Allegro manual
|
https://www.mankier.com/3/save_joystick_data
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
To shorten qualified references
- Choose
ReSharper | Options | Code Editing | C# | Namespace Imports(for C# settings) or ReSharper | Options | Code Editing | Visual Basic .NET | Namespace Imports(for VB.NET settings).
- You can choose to use fully qualified names always or to use short names with namespace imports. In the
Reference Qualificationsection click Insert using directives when necessaryor Use fully qualified names. Moreover you can tune replacing, select or clear check boxes.
- Choose
Code Editing | Code Cleanupin ReSharper Optionsdialog box.
- Create a new profile as described in Creating Custom Profiles. In the
Selected profile settingssection for the new profile select Shorten qualified referencescheck box.
- Click
OKto save the new profile and shorten qualified references.
|
https://www.jetbrains.com/help/resharper/6.0/Code_Cleanup__Usage_Scenarios__Shortening_Qualified_References.proc
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
import "go/build"
Package,.
var ToolDir = filepath.Join(runtime.GOROOT(), "pkg/tool/"+runtime.GOOS+"_"+runtime.GOARCH)
ToolDir is the directory containing build tools.
func ArchChar(goarch string) (string, error)) ([]os.FileInfo, error) // OpenFile opens a file (not a directory) for reading. // If OpenFile is nil, Import uses os.Open. OpenFile func(path string) (io.ReadCloser,. AllowBinary // If ImportComment is set, parse import comments on package statements. // Import returns an error if it finds a comment it cannot understand // or finds conflicting comments in multiple source files. // See golang.org/s/go14customimport for more information. ImportComment //..
|
https://static-hotlinks.digitalstatic.net/go/build/
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
OpenCV is an open-source cross-platform computer vision library released under BSD open source license.
It provides C ++, C, Python, Java and other language call interface, you can run on Windows, Linux, Mac OS, iOS, Android and other operating systems.
Because you need to call an OpenCV image recognition algorithm, the way to sort out the OpenCV 2.4 Mac and CentOS under the installation and configuration.
Install OpenCV on Mac
The project development environment is on Mac. You can use Homebrew to install OpenCV on Mac. To install OpenCV on Mac you need to make sure the xCode have installed.
Homebrew installation is as follows
Before you do this, make sure you have Homebrew installed.
First, find the installation package:
$ brew search opencv opencv opencv@2
To install version 2.x of OpenCV, use the following command:
$ brew install opencv@2
The following is the process of compiling and installing OpenCV
1. Install
cmake
Source installation, you need to use cmake to build the project. First, need to install
cmake:
$ sudo brew install cmake
2. Download OpenCV
Download OpenCV and switch to the specified branch:
$ git clone $ cd opencv $ git checkout 2.4
Currently, OpenCV main branch version 3.3+, because we want to use the 2.4 version, so after downloading you need to switch to the 2.4 branch.
3. Compile and install OpenCV
$ mkdir build $ cd build $ cmake .. $ make $ sudo make install
4. Verify installation
OpenCV source samples directory, OpenCV contains a number of sample programs, we can use these examples to verify the OpenCV installation is successful.
First, compile these examples:
$ cd ../samples $ mkdir build $ cd build $ cmake .. $ make
After compiling, you can run any one of the examples to verify, such as:
$ ./cpp/cpp-example-em
Using OpenCV in Xcode
1. Create a project
Open xCode and create a macOS-Command Line Tool project with C ++ project language selection:
2. Configure the path
Select the target of the project, and configure its Header Search Path and Library Search Path to find the path, where:
Header Search Path is configured as: /usr/local/include
Library Search Path is configured as: /usr/local/lib
3. Add a library reference to the project
Create a new project called libs group (New Group), and then press shift + command + g in the pop-up window, type /usr/local/lib. After entering the specified directory, the files are sorted by type, and file references such as libopecv _ *. Dylib are added to the libs group.
4. Write the project code
Write the following code in main.cpp:
// // main.cpp // OpencvTest # include <iostream> # include <opencv2/core/core.hpp> # include <opencv2/highgui/highgui.hpp> # include <opencv2/opencv.hpp> using namespace std; using namespace cv; IplImage* doCanny(IplImage* image_input, double lowThresh, double highThresh, double aperture) { if(image_input->nChannels != 1) return (0); IplImage* image_output = cvCreateImage(cvGetSize(image_input), image_input->depth, image_input->nChannels); cvCanny(image_input,image_output,lowThresh,highThresh,aperture); return(image_output); } int main(int argc, char* argv[]) { cvNamedWindow("Camera" , CV_WINDOW_AUTOSIZE ); CvCapture* capture = cvCreateCameraCapture(CV_CAP_ANY); assert(capture != NULL); IplImage *frame = 0; frame = cvQueryFrame(capture); IplImage *frame_edge = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 1); while(1) { frame = cvQueryFrame(capture); if(!frame) break; cvConvertImage(frame,frame_edge,0); frame = cvCloneImage(frame_edge); frame_edge = doCanny(frame_edge,70,90,3); cvShowImage("Camera",frame_edge); char c = cvWaitKey(15); if(c == 27) break; } cvReleaseCapture(&capture); cvReleaseImage( &frame_edge ); cvReleaseImage( &frame); return (int)0; }
5. Run the project
After compiling the code compiled and run.
Install OpenCV on Linux (CentOS 7)
The project’s final operating environment is Linux with the CentOS release installed, and the OpenCV installation in CentOS 7 is as follows.
2.1 install dependent libraries
sudo yum install autoconf automake cmake freetype-devel gcc gcc-c++ git libtool make mercurial nasm pkgconfig zlib-devel
2.2 install FFmpeg
FFmpeg is used to decode the H264 encoded video data stream and convert it to the OpenCV processable Mat format before further processing by OpenCV. If you have the relevant needs of the project, you need to install FFmpeg.
Compile and install FFmpeg as follows:
$ git clone git://source.ffmpeg.org/ffmpeg $ cd ffmpeg $ ./configure --enable-shared $ make $ sudo make install
After installation, you can check whether the installation was successful by the ffmpeg -version command:
$ ffmpeg -version ffmpeg version 2.8.13 Copyright (c) 2000-2017 the FFmpeg developers built with gcc 4.8.5 (GCC) 20150623 (Red Hat 4.8.5-11) ...
2.3 Install OpenCV
We can download the source code from the GitHub official OpenCV repository, and then compile and install.
The steps are as follows:
$ git clone $ cd opencv $ git checkout 2.4 $ mkdir build $ cd build $ cmake .. $ make $ sudo make install
After the installation is complete, the same sample can be compiled samples directory to verify the installation was successful.
|
http://w3cgeek.com/install-opencv-on-mac-centos.html
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
This is a more specific (and perhaps more useful) case built from my base article on communicating with an iFrame. (That article has some base content, but it's not required to understand this article.)
To quickly recap, as long as you have access to the source of the iframe (the code and domain on which the iframe is hosted), then you can communicate with it and, therefore, adjust its content (i.e. manipulate its DOM).
Demo
The case we're going to create is that we need to adjust the theme of what is inside the iframe by clicking a button outside the frame.
We'll have two buttons, one to activate the light (default) theme and the other to activate the dark theme.
Your Site's Code
First, let's start with the code on your site. Your site will hold the buttons and the iframe that we want to manipulate.
The markup may look something like this:
<button data-Light Theme</button> <button data-Dark Theme</button> <iframe src="/location/of/iframe" frameborder="0" id="my-iframe"></iframe>
Our main focus in the script will be to toggle the theme within the iframe. To do this, we're taking advantage of the
postMessage method on the
window object.
// Send message to the iFrame with the theme we want to activate. function activateTheme(theme) { var iframe = document.getElementById('my-iframe'); if (iframe && iframe.contentWindow) { iframe.contentWindow.postMessage(theme, '*'); } }
Note: If you're using this exact approach, you may want to add some sort of active toggle to the buttons to show which theme is currently active.
You'll want an event listener to the button clicks and also activate the default theme once the iframe is ready. That looks like this:
// Load the light them when the iFrame is ready. $('#my-iframe').on('load', function() { activateTheme('light'); }); // Listen for clicks on buttons with a "data-theme" attribute, and activate that // theme on click. $('button[data-theme]').on('click', function(event) { activateTheme($(this).data('theme')); });
Altogether, we have:
(function() { $('#my-iframe').on('load', function() { activateTheme('light'); }); $('button[data-theme]').on('click', function(event) { activateTheme($(this).data('theme')); }); function activateTheme(theme) { var iframe = document.getElementById('my-iframe'); if (iframe && iframe.contentWindow) { iframe.contentWindow.postMessage(theme, '*'); } } })();
Note: Using the anonymous function approach (
(function() {})()) avoids placing
activateTheme into the global namespace, which we do not want.
iFrame Site's Code
The site with the iFrame will be receiving your posted message.
For toggling the theme, we may choose to place a class on the body and adjust the theme that way. A very basic example may have CSS that looks like this:
body, body.theme-light { background-color: #ededed; padding: 1rem; } body.theme-dark { background-color: #444; color: #fff; }
And then the JavaScript would listen for a message to be posted and set the appropriate class:
window.addEventListener('message', function(event) { if (event.origin === window.location.origin) { $('body').attr('class', 'theme-' + event.data); } }, false);
Note: We checking that the origin of the message is on the same domain as this iframe so we don't accept messages from other domains.
That's it.
The basics of it are pretty simple. Although the problem you're solving may be more involved, I hope this base can help get you started.
References
|
https://cobwwweb.com/change-css-iframe
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
HyperlinkHyperlink
Cool URLs that don't change.
Hyperlink provides a pure-Python implementation of immutable URLs. Based on RFC 3986 and 3987, the Hyperlink URL makes working with both URIs and IRIs easy.
Hyperlink is tested against Python 2.7, 3.4, 3.5, 3.6, and PyPy.
Full documentation is available on Read the Docs.
InstallationInstallation
Hyperlink is a pure-Python package and requires nothing but Python. The easiest way to install is with pip:
pip install hyperlink
Then, hyperlink away!
from hyperlink import URL url = URL.from_text(u'') utm_source = url.get(u'utm_source') better_url = url.replace(scheme=u'https') user_url = better_url.click(u'..')
See the full API docs on Read the Docs.
More informationMore information
Hyperlink would not have been possible without the help of Glyph Lefkowitz and many other community members, especially considering that it started as an extract from the Twisted networking library. Thanks to them, Hyperlink's URL has been production-grade for well over a decade.
Still, should you encounter any issues, do file an issue, or submit a pull request.
|
https://libraries.io/pypi/hyperlink
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
Edge Browser xsl transform default output to html
Confirmed Issue #8401292 • Assigned to Travis L.
Steps to reproduce
xsltProcessor set xsl:output method default to html.
That is not right, see.
For testing load test-xsl.html in Edge.
In Firefox or Chrome it works correct.
Microsoft Edge Team
Changed Assigned To to “Brad E.”
I’ve looked over the repro sample you provided to us and as far as I can tell Chrome and Edge seem to report the exact same data, unless I am overlooking something.
Which of the three sections are you showing a discrepancy with between Chrome and Edge?
Thanks for the feedback.
Look at the first section “without xsl output” and you can see, that edge transform the “image” node to “img” with namespace xhtml.
See my picture chrome-edge.png.
Regards Jan
Microsoft Edge Team
Changed Assigned To to “Christian F.”
Changed Assigned To to “Rico M.”
Changed Assigned To to “Travis Title from “Edge Browser xsl transform default output to html” to “Edge Browser xsl transform default output to html”
You need to sign in to your Microsoft account to add a comment.
|
https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8401292/
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
import "crypto/dsa"
Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.
The DSA operations in this package are not implemented using constant-time algorithms.
var ErrInvalidPublicKey = errors.New("crypto/dsa: invalid public key").
func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error).
func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool.
type ParameterSizes int )
type Parameters struct { P, Q, G *big.Int }
Parameters represents the domain parameters for a key. These parameters can be shared across many keys. The bit length of Q must be a multiple of 8.
type PrivateKey struct { PublicKey X *big.Int }
PrivateKey represents a DSA private key.
type PublicKey struct { Parameters Y *big.Int }
PublicKey represents a DSA public key.
|
https://static-hotlinks.digitalstatic.net/crypto/dsa/
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
Hello, guys!
I've written a GUI for a program. It's written like shit, the goal was to get it done fast. Well it didn't exactly work out, so when I refresh the data, every label disappears. Here is the code:
class GUI: def __init__(self, master): self.master = master self.label = Label(master, width=50, height=15) self.label.pack() self.makeMenus() self.showStats()
Then, loads of labels, some with textvariables like this:
def showStats(self): stats = loadStats() # buys Label( self.label, text='Buys', font=BOLDFONT ).place(x=40, y=10, anchor=NW) Label(self.label, text='Times:').place(x=10, y=50, anchor=NW) self.buyTimes = StringVar(self.label) Label( self.label, textvariable=self.buyTimes ).place(x=60, y=50, anchor=NW) ...
... and here is the code for the refresh method:
def refreshStats(self): stats = loadStats() self.buyTimes.set(stats['buys']) ...
So the problem is, that after refreshing, every label disappears for a second, but when I move the cursor over the ones with textvariables, they reapper, but the others don't.
What should I do?
|
https://www.daniweb.com/programming/software-development/threads/292070/tkinter-label-refresh-problem
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
File Input and Output
A file is aggregated data stored to disk, and it becomes either an input (read) or output(write) stream when opened for processing.
File input and output uses the namespace System.IO, which contains a number of important classes in file operations. Review a selection of classes below:
THE STREAM CLASS
The Stream class manages read and write manipulation. The StreamReader and StreamWriter classes specifically manage these areas. StreamReader inherits from TextReader, and represents a reader tool for reading a set of characters. Its methods follow: Close, closes the object and releases associated resources; Peek, returns the next character without consuming; Read, reads the next character; ReadLine, reads a line and returns a string; and Seek, moves the read/write position.
FILEMODE ENUMERATION
FileMode parameters specified in file operation constructors specify how a file will be opened. The parameters determine the action on the file: overwrite, creation, open, or a combination. Review its syntax below:
public enum FileMode
Its members include Append, Create, CreateNew, Open, OpenOrCreate, and Truncate.
MAKE A FILE
Produce a text file using any number of applications, or employ addListItem:
private void addListItem(string value) { this.listBoxOne.Items.Add(value); }
You can also use this statement:
this.listBoxOne.Items.Add(value);
ACCESSING A FILE
Use the StreamReader class to read a file. The contents of the file are then added to a ListBox control. Many ways exist for checking if the end of the file has been reached. One approach uses the Peek method. Review an example of reading from a file below (this code uses the winDir variable):
StreamReader reader=new StreamReader(winDir + "\\stuff.ini"); try { do { addListItem(reader.ReadLine()); } while(reader.Peek() != -1); } catch { addListItem("File has no content");} finally { reader.Close(); }
MODIFYING A FILE
The StreamWriter class can be used to create and write to a file. It also provides a way to open an existing file using the same approach. Review an example of its use below:
StreamWriter writer = new StreamWriter("c:\\testfile.txt"); writer.WriteLine("File spawned with the StreamWriter class."); writer.Close(); this.listboxOne.Items.Clear(); addListItem("Written to C:\\testfile.txt");
VIEW FILE DATA
The FileInfo object can be used to access file properties. In the example below, Notepad.exe is used to gather information, but virtually any editor can be used (this code uses the winDir variable).
FileInfo FileProps =new FileInfo(winDir + "\\notepad.exe"); addListItem("Name of file = " + FileProps.FullName); addListItem("Time of creation = " + FileProps.CreationTime); addListItem("Time of last access = " + FileProps.LastAccessTime); addListItem("Time of last write = " + FileProps.LastWriteTime); addListItem("File size = " + FileProps.Length); FileProps = null;
ACCESS DISK DRIVES
The Directory and Drive classes can be used to list logical drives. In the example below, the ListBox control is used for results:
string[] drives = Directory.GetLogicalDrives(); foreach(string drive in drives) { addListItem(drive); }
The GetDirectories method and GetFiles method of the Directory class can be utilized to list folders and files.
|
https://freeasphosting.net/csharp-tutorial-file-input-and-output.html
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
C sharp Interview Questions And Answers
Table of contents
- Introduction
- Background
- C# Interview Questions
- What are Abstract Classes?
- What are Abstract methods?Give an example?
- What is Interface? Explain with an example?
- Explain The Difference Between Abstract Class and Interface ?
- Explain Generic Collections & Array Lists ?
- What are Finalize and Dispose? Can you list down the differences between them?
- What is Dependency Injection?How can we implement it?
- What is Data Encapsulation and explain its Implementation?
- Conclusion
- Your turn. What do you think?
Introduction
In this article, we will discuss the most asked C# interview questions and answers. If you need to know other interview questions and answers, I strongly recommend to follow this link: Interview Questions. Now in this post, we are going to share the interview questions for C# or a Dot Net developer. No matter you are experienced or fresher, it is important that you must aware of these. So please read it carefully. I hope you will like this article.
Background
C# is one of my favorite programming languages. So I am really happy to share you some interview questions related to C#. You can always read my other interview questions here in the below links.
So shall we now discuss C# interview questions?
C# Interview Questions
What are Abstract Classes?
The purpose of an abstract class is to define some common behavior that can be inherited by multiple subclasses, without implementing the entire class. In C#, the abstract keyword designates both an abstract class and a pure virtual method..
Properties
Syntax
public abstract class A { public abstract void DoWork(int i); }
What are Abstract methods?Give an example?
Abstract Methods
Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. (See above example for syntax)
Derived classes of the abstract class must implement all abstract methods.
When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method.
Example
// compile with: /target:library public class D { public virtual void DoWork(int i) { // Original implementation. } }
public abstract class E : D { public abstract override void DoWork(int i); } public class F : E { public override void DoWork(int i) { // New implementation. } }
What is Interface? Explain with an example?
An interface is useful when you want to be able to use some common functionality of otherwise unrelated classes- they share no implementation details, only the function signatures. In C#, function declarations within an interface are implicitly pure virtual.
An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.
Properties
An interface can be a member of a namespace or a class and can contain signatures of methods, properties, events, indexers.
An interface can inherit from one or more base interfaces. A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.
Example
interface IControl { void Paint(); }
interface ISurface { void Paint(); }
public class SampleClass : IControl, ISurface { void IControl.Paint() { System.Console.WriteLine("IControl.Paint"); } void ISurface.Paint() { System.Console.WriteLine("ISurface.Paint"); } }
Calling the methods
// Call the Paint methods from Main. SampleClass obj = new SampleClass(); //obj.Paint(); // Compiler error.
IControl c = (IControl)obj; c.Paint(); // Calls IControl.Paint on SampleClass.
ISurface s = (ISurface)obj; s.Paint(); // Calls ISurface.Paint on SampleClass.
Explain The Difference Between Abstract Class and Interface ?
An Abstract class doesn’t provide full abstraction but an interface does provide full abstraction; i.e. both a declaration and a definition is given in an abstract class but not so in an interface. Using Abstract we cannot achieve multiple inheritances but be using an Interface we can achieve multiple inheritances. We cannot declare a member field in an Interface. We cannot use any access modifier i.e. public, private, protected, internal etc. because within an interface by default everything is public. An Interface member cannot be defined using the keyword static, virtual, abstract or sealed.
Explain Generic Collections & Array Lists ?
Generics allow you to delay the specification of the data type of programming elements in a class or a method until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
Generic Collections helps us to create flexible type-safe, strong type collections at compile time.
Syntax
List<int> myInts = new List<int>();
Namespace
System.Collections.Generic
ArrayList
They are ordered a collection of objects, that can be resized automatically, that has dynamic memory allocation and which can contain different types of data.
Arraylist stores its members as objects, so in order to retrieve it, we must type cast it.
Syntax and Example
ArrayList intlist = new ArrayList(); intlist.Add(34); intlist.Add("sasi");
Namespace
System.Collections;
What are Finalize and Dispose? Can you list down the differences between them?
Finalizers are run by the Garbage Collection before an object that is eligible for collection is reclaimed. Dispose() is meant for cleaning up unmanaged resources, like network connections, files, handles to OS stuff, &c. It works best in conjunction with the using block where the compiler makes sure that Dispose() will be called immediately once you are done with an object – and also ensures that you cannot work with the object anymore once it’s disposed of.
Dispose() Method
– This dispose method will be used to free unmanaged resources like files, database connection etc.
– To clear unmanaged resources, we need to write code manually to raise dispose() method.
– This Dispose() method belongs to the IDisposable interface.
– If we need to implement this method for any custom classes we need to inherit the class from IDisposable interface.
– It will not show any effect on the performance of the website and we can use this method whenever we want to free objects immediately.
Finalize() Method
– This method also free unmanaged resources like database connections, files etc…
– It is automatically raised by garbage collection mechanism whenever the object goes out of scope.
– This method belongs to object class.
– We need to implement this method whenever we have unmanaged resources in our code and make sure these resources will be freed when
garbage collection process was done.
– It will show the effect on the performance of the website and it will not suitable to free objects immediately.
What is Dependency Injection?How can we implement it?
Simply put Dependency injection is for decoupling two components. It can be explained by a simple example.
public class ErrorLogger { public void WriteIntoDataBase(string message) { // Creates DataBase Entry. } }
public class ApplicationWatcher { ErrorLogger logger = new ErrorLogger(); public void Notify() { logger.WriteIntoDataBase("This is the message that I want to write.") } }
Have a look at the code above.
I have an ErrorLogger class that writes an error into database. The method is actually called from another class ApplicationWatcher.
In a later stage, if I want to send an email instead of writing into the database, this design will not suffice. I will have created another class that has a method that sends an email and creates its instance in the application watches.
What is Data Encapsulation and explain its Implementation?
To know about the Data encapsulation in C#, I recommend you to read here:
Data Encapsulation and Its Implementation
That’s all. Have a great day.
|
https://sibeeshpassion.com/c-sharp-interview-questions-and-answers/
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
i
Preface
This M.Sc. Thesis presents the results of my final master project entitled Secure Routing in Mobile Ad Hoc Networks. The master project was carried out in the period 1st of July to 31st of December 2003 and corresponds to 30 ETCS points. It has been the final part of my studies for the Master of Science degree (In Danish Civilingeniøruddannelsen) at the Department of Informatics and Mathematics Modelling, IMM, Technical University of Denmark, DTU. Associate Professor Christian Damsgaard Jensen, IMM, was supervisor of my M.Sc. Thesis project. I would like to take this opportunity to thank Christian Damsgaard Jensen for his counseling, support and not least his interest in my M.Sc. Thesis project. Furthermore, I would like to thank the following persons: Casper Borly, Finn Conrad, Simon Haldrup and Tom Skovgaard for comments and discussions during my thesis work. Last but not least, I would like to thank my girlfriend Lene Skovgaard for her patience and understanding. Lyngby, DTU, 30th December 2003
Lennart Conrad
ii
M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
iii
A system that stores and updates trust values for nodes encountered in mobile ad hoc networks is designed and implemented. To evaluate the performance impacts of applying trust based route selection to the DSR protocol several different simulations have been performed on the Ns-2 network simulator. A protocol. The implemented system has been integrated with an existing implementation of the Dynamic Source Routing protocol. iv M. The results from these simulations have been analyzed and presented. Thesis has focused on the design and implementation of trust based route selection in mobile wireless ad hoc networks.Sc. The trust values are used to base routing decisions on. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .Sc.Abstract This M. used for communication in mobile wireless ad hoc networks. different strategies for evaluation of routes based of the nodes trust values have been designed and implemented. To identify how and where to incorporate the trust in the DSR protocol an analysis of possible malicious attacks against the protocol have been conducted and presented. Since a route consists of many nodes that are grouped.
Sc.M. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 v .
Sc. blevet designet og implementeret.Sc Thesis har fokuseret på design og implementering af tillids baserede rute valg i mobile trådløse ad hoc netværk. på baggrund af nodernes tillids værdier. For at evaluere effekten af at benytte tillids baserede rute valg i DSR er der blevet foretaget flere forskellige simuleringer på Ns-2 netværks simulatoren. For at indentificere hvor og hvordan tillid har kunnet indbygges i DSR protokollen. Et system som gemmer og opdaterer tillids værdier for kendte noder i ad hoc netværk er blevet designet og implementeret. er blevet analyserede og presenterede. De opnåede resultater her af. Det implementerede system er blevet integreret med en eksisterende implementering af ”Dynamic Source Routing” protokollen. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . vi M. Tillids værdierne benyttes til at basere rute valg på. Eftersom en rute består af mange noder som er grupperede.Abstract in Danish Denne M. en protokol som benyttes til kommunikation i trådløse ad hoc netærk. er der foretaget og præsenteret en analyse af mulige angreb på protokollen. er forskellige strategier til at evaluere ruter.
Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 vii .Sc.M.
.......................1 Definitions of trust..........30 3 Analysis ......3 Forwarding of packets .....................................................................25 2......................................................................................................................23 2.....24 2................6 Comparison of Ad Hoc Routing Protocols..............14 2.4 The Dynamic Source Route (DSR) Protocol ............3 Frameworks for Working with Trust........................7 Summary ...........6 Summary ..........................................................3 1............................3...........................................................21 2.............................................3.........20 2....2...............5 2....2 The Security Aware Ad-Hoc Routing Protocol (SAR)....3 Security In Ad-Hoc Networks..........39 4 Design ...........16 2.....6 Nuglets .......................14 2................24 2.............................................................................................. 41 4................................1 Identification of components..............33 3............................................................................7 Trust based routing ...4 Attacks that are not covered by the analysis ..........22 2.............................................2 Main objectives..1 Introduction to Ad Hoc Networks and Routing..3 Assumptions made about malicious nodes ........3 1....1........................................................2 Receiving packets ...........................................1....1....3..................1....................33 3...4 Trust ...............18 2...............................................................................................41 4.........2....................................2...............................3..........................................................1........1 Analysis of DSR ................42 viii M.............................................................................................................................................................................13 2................................................34 3.............................2 1............................................6 2..........................................................1...........................2 The Destination-Sequenced Distance Vector (DSDV) Protocol...................................8 Summary ...........................4 Summary ............4 2 State of the art.....1 Preliminary objectives ............3 REFEREE ...............................................................23 2.......18 2..................................................................1 Routing protocols ......................................................................2 Extensions to DSR ..................................................................................................1...................................................... 33 3.................................1.......5 Prioritization and general assumptions................................................................3 Entity Recognition ...............5 The CONFIDANT protocol .............................................................................. 5 2...............................37 3.......38 3.............4.................................2 Different categories of trust ....................3...4 The Watchdog – Pathrater approach .. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 ....35 3..........................................................................4 Summary ................15 2......................................3 Post objective .....1 Motivation .2 1..............................................2...8 2..............7 2.....................16 2....................................17 2...........1 Introduction..............................19 2..............38 3.....................................................................2 KeyNote...3..........4...........................Sc........1.................4.........................................................................1 Sending of packets.....................................................................2............4 1....4................1....................3 Report Roadmap ............................................................................1 Trust Formation ..........................................................................................2....13 2.16 2....29 2.....................................................3 The Temporally-Ordered Routing Algorithm (TORA) ................5 Subjective evaluation of methods and techniques.................................3............5 The Ad-Hoc On Demand Distance Vector (AODV) Protocol........9 2..................................1 PolicyMaker..............................................................37 3........................2 Trust Management Systems.1 Zhou et al Key Management Service ....................................................................... 1 1.............2 Aim and Objectives ...2..............................................27 2....3.....................1.....
.....................................................6 Comparison of Route selection strategies ....................................................................................................................7 Existing DSR Implementation in NS-2.4...................2 Estimation of acknowledgement time out...7 Evolution of trust values ..........................5.............................83 8 A B Conclusion.66 6........................ 61 6.................................................................................................. 93 C Nomenclature ..................74 6..........................8 Malicious packet drops ............................................................................................3 Tests ............................................................. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 ix .....................4.......................47 4............1...............................................1 The randomness of simulations....................................................................8 Merging the trust modules with the existing DSR code............77 6..58 5......1 Table of standard DSR parameters...................................................7 Summary ........4........................................ 81 7.................49 4........82 7.............1....................................................4 Malicious nodes......................5 Acknowledgement monitoring .......... 57 5.......................................................................................................Sc............81 7.....................................................................58 5........................................................................................................6 Combining the trust modules....................................................4...............................................................................3 Route selection.........................66 6.........................2 Using a sliding window mechanism for acknowledgements .............. Improvements and Perspective ..............................3 Processing the output...................78 7 Future Work.....................67 6............59 6 Simulations and Results.................49 4................................................ 89 List of used terms and definitions...........................11 Summary ................................................4 Summary ............................5...........1.....................................................................................................3 Other parameters ...81 7............9 Examining the Route Cache.56 5 Implementation and tests ..............................................................................4 Trust management .................42 4...2 Trust related parameters ...................................................................................64 6..........................................................................57 5.........64 6..............................................................4 Examining cause and location of packet drops .....73 6..................82 7........6 Perspective..1 Introduction of grudging behavior ..............70 6................................................3 Derivation of knowledge by examining received packets ................ 94 D List of used acronyms .........................................63 6.........2 Metrics..1.5.............................. 95 M...............................2 Summary .4 Parameters.....................64 6.................65 6..................65 6......................5 Decrease trust over time .....62 6.............................................51 4................. 85 Bibliography...5 Preliminary simulations...............................................................................................................4....3 Impact of using different scenarios.................................................................1 Estimation of initial trust ..57 5..81 7.....................61 6.........................47 4.................................................1...................2 Implementation details ..............................................................................1.................75 6.......10 Uncertainties ...............66 6.....................1 Overview of Ns-2..............1 Introduction to the Ns-2 simulator..........................1..........................................................44 4...........................................................82 7..........1................................................2 Trust updating ...............................
.......................................... 100 I J K L Content of the CD..............................108 File format....................123 TrustUpdater (...........h and .....................................................java.................................................. 107 O Implementation details ......................cc)............... Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 ..........h and .....2 P............................1 O...3 P...........130 TrustConstants.......... 104 Simulation platform.................................................138 P Source code .... 106 N Output from simulations .................java...............................................cc) ...............114 TrustManager (......................................................................h and ......128 RouteSelector (................................E F Appendices (F – P)........................................108 Malicious behavior ...........................................................................1 P............9 x M. 108 O.........................h and .......................cc) .........................111 Otcl script............................ 109 P............................................................................... 97 G List of tables .....Sc........................... 102 Result from simulating DSR with different scenarios...........................................109 RouteParser.................................................... 99 H List of equations .... 97 List of figures ...........................5 P.............h and .......................................4 P............................................7 P.........................................3 Scanning for timed out acknowledgements ......................................................................6 P.................2 O.....................................................................................cc) ......................................................117 TrustFormater (.. 105 M Sendbuffer drops during simulation with RS1 ..................126 ACKMonitor (........8 P...................................cc) ...................108 DSRParser................................h .... 101 Structure of mobile node in Ns-2...................
M. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 xi .Sc.
However several factors such as.Introduction 1 Introduction The need of access to wireless communication is increasing rapidly as the desire of mobile connectivity with devices such as cell phones. 1 M. Figure 1-1: Mobile wireless ad hoc network Ad hoc networks are often proposed for search and rescue mission and military operations where existing infrastructure have been damaged and is inoperative. As illustrated all nodes are not in direct connection with each other but can use other nodes as relays in order to transmit to a destination.Sc. often referred to. An ad hoc network is illustrated in Figure 1-1. Another type of ad hoc networks. as collaborative networks are networks where agents with no common relations join together to achieve their own personal goal of sending packets to a destination. the inaccessibility to servers or centralized administration. ad hoc routing protocols that can be used in mobile wireless networks have been developed. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . PDA’s and laptops to data networks is becoming more and more prevalent The growing demand for mobile access is reflected by the current increase in the establishment of local wireless networks and the construction of new pylons for tele communication.1 . nodes in the network collaborate to route data to destinations that might be out of the senders transmission range. To manage situations where access points are out of transmission range. In such situations the nodes are related by outside factors such as organizational hierarchies. Due to the relatively short transmission range of wireless devices. An ad hoc network is a collection of wireless mobile nodes that dynamically functions as a network without the use of any existing infrastructure and centralized administration. The figure also illustrates another important property of the shown ad hoc network. Nodes move around which can cause links to be broken and established. geographic conditions. and spontaneous occurring needs can make the establishment or existence of access points impossible. economics.
The design and implementation of the solution is presented and results from simulations with the implemented system is analyzed and discussed.1 Motivation Most common protocols for mobile wireless networks build on the assumptions that nodes in the network are willing to participate to the networks existence by forwarding packets for other nodes. lack of existing infrastructure and un-accessibility to trusted servers make traditional security methods and system insufficient for application in mobile wireless ad hoc networks.Sc.1 . This results in a conflict. By allowing an unknown node to forward data. it is expected that the establishment and evolution of trust can be used to detect nodes that betrays the trust placed in them. This M. nodes perform a trust-based decision. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 2 . The solution addresses the problem that occurs when malicious nodes starts to drop packets they were supposed to forward. 1. The open structure. Achieving different levels of security therefore represents a major issue for the distribution and use of ad hoc networks. The structure of the ad hoc network gives rise to security issues of different severity.2 Aim and Objectives This section states the aim and objectives that have been stated for the Master project.Introduction The structure of collaborative ad hoc networks is untraditional. which means that each transmission has a cost in terms of power consumption. since nobody can claim ownership and control of the network and thereby attend to administration of the network and require payment for its use. thesis. it is expected that readers of this have a general technical insight and knowledge of software development methods. There is little reason to assume that some nodes will not try to achieve the benefits of participating in the network and avoid the disadvantages it involves. from which they achieve no benefits and as a result consume their own battery power. since malicious nodes can seek to exploit the openness of the network. Because of the exploratory nature of the project the list of objectives has evolved in M. because the node originating the transmission might be out of range to detect the malicious act. since nodes have to perform the task of forwarding data. In general most mobile devices operate on battery power. Trust is a well-known sociological concept that humans on a daily basis base decision on. By incorporating trust in ad hoc routing protocols and thereby mimicking human behavior. Due to the technical nature of this M. This could mean that some nodes refuse to forward packets as supposed and thereby decrease the efficiency of the network. 1.Sc. Because of the nature of the ad hoc network it is difficult to identify nodes that express such malicious behavior.Sc thesis investigates several existing security solutions for ad hoc networks and proposes a trust based route selection solution. The detection of untrustworthy nodes can be used to apply trust based route selection strategies to ad hoc routing protocols and thereby increase the effectiveness of the network.
The aim of the assignment has been to design and implement a system that can be used for trust based routing. situations where trust can be incorporated must be identified. 3 M. In order to achieve the primary objective several intermediate objectives are defined. main and post objectives 1. PRE-O 2. Investigate security solutions applied to ad hoc networks and ad hoc routing protocols.1 . Research the area of trust.Sc.2 Main objectives The fulfillment of the main objectives leads to the fulfillment of the primary objective. PRE-O 3. These objectives are divided into three categories: preliminary. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . which is stated in Figure 1-2 has been clear from the start. To attain knowledge and insight in the area of ad hoc routing existing protocols must be examined. These values should be adjusted based on the experiences the nodes have. To detect weaknesses and possible pitfalls the DSR protocol [Johnson1] must be analyzed. in order to fortify the protocol and improve route selection.Introduction order to reflect the increasing knowledge and insight in the areas of ad hoc routing and trust. PRE-O 1. Analyze the DSR protocol. to identify useful methods and approaches.1 Preliminary objectives The preliminary objectives are objectives that need to be fulfilled in order to gain the sufficient knowledge to fulfill the main objectives. Research the area of trust management and trust in general to gain deeper knowledge of trust as a concept and to find formal methods for expressing trust. 1. Figure 1-2: Primary objective. Existing security solutions that have been applied to ad hoc networks and routing protocols must be investigated. The system must make it possible for nodes to store and updates crisp values that represent their trust in other nodes. It is the aim that such a system can be applied to the DSR protocol to achieve route selection strategies that can avoid nodes with low values. Furthermore.2. M-O 1. Examine existing ad hoc routing protocols. Primary objective: To apply trust based route selection to the Dynamic Source Routing (DSR) protocol.2. The primary objective. which can increase throughput in situations where malicious nodes are present in the network. When a route is selected is must be selected by an evolution of the nodes on the routes values.
Furthermore the integration with the existing DSR classes is covered. 1.Introduction M-O 2.1 . Furthermore. Chapter 6 Simulations and Results: In this chapter the performed simulations are described and the achieved results are discussed and analyzed. Design and implement components to incorporate trust based route selection to the existing DSR protocol. Particular emphasis must be put on the design of different routing strategies. P-O 1. The results must be analyzed to determine the impact of applying the trust based routing strategies and to detect possible areas of improvements. Based on the analysis modules that incorporate trust must be designed. Chapter 7 Future Work.2. Chapter 5 Implementation and tests: This chapter covers the implementation of the designed system and discusses the tests that have been performed. Chapter 8 Conclusion: The final chapter presents the conclusion and contribution of the project and summarizes the achieved results.3 Post objective This objective needs to be fulfilled to determine to what extend the primary objective has been fulfilled and to identify possible areas of improvement. it gives a small introduction to the Ns-2 network simulator. M. Improvements: Some of the future area of work and possible areas of improvements are discussed in this chapter.3 Report Roadmap This section gives a brief presentation of each chapter in the thesis. Simulate behavior of the implemented trust based routing and analyze results. 1. Chapter 1 Introduction: In this chapter an introduction to the investigated area ad hoc networks is presented. Simulations with the implemented extension have to be carried out. Chapter 4 Design: The design of the component that is used to incorporate trust based route selection in DSR is described. Furthermore. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 4 . the motivation and the objectives are presented. The analysis focuses on how to apply trust to the protocol and how malicious nodes can misuse the protocol.Sc. Chapter 2 State of the art: This chapter concerns examined areas such as: • • • • Ad hoc routing protocols Trust management systems Security in Ad hoc networks Trust Chapter 3 Analysis: In this chapter an analysis of the DSR protocol is presented. implemented and integrated with the existing implementation of the DSR protocol.
it is not sure that node C can use the same route back to A.1 Introduction to Ad Hoc Networks and Routing An ad hoc network consists of mobile wireless nodes. Since the nodes are mobile they operate on battery power. This chapter investigates these areas. it can require a lot of communication for a node to keep a static picture of the topology. Figure 2-1 below illustrates how node A uses a route through node B to get data to node C. PRE-O 1 and PRE-O 3. because C is out of A’s transmission range. Since nodes can move around. 5 M. the possible bandwidth for mobile devices today is not as high as for stationary networks. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . Several issues such that low battery power or different hardware types can cause unidirectional links. this means that even though node A can transmit to node C through node B.Sc. As illustrated in Figure 2-2 below. Furthermore. Routing protocols for ad hoc networks need to account for several aspects. trust and security in ad hoc networks has been researched.2 .State of the art 2 State of the art To achieve the preliminary objectives. which limits the amount of data they can transmit. and enter and leave the network. several areas such as ad hoc networks. before recharging is necessary. 2. Due to the possible rapid changes in topology. routing protocols. A B C : Transmission radius Figure 2-1: Node A transmits a package to node C by routing it through node B. Nodes participating in the network manage routing without the use of any existing infrastructure. Another issue in ad hoc networks is that links between nodes are not always bidirectional but can be unidirectional. Further more no centralized access point exists in the network. Mobile wireless nodes will typically have limited transmission range. the network topology can change rapidly. Due to these circumstances ad hoc routing protocols must minimize the number of packets used for maintaining the routes and must be able to adapt to changes in the topology. Most mobile devices today have less processing power and memory than standard PC’s. which means that packets might have to be forwarded by several nodes in order to get from one node in the network to another.
Sc. This section introduces some of these principles.State of the art A B C D Figure 2-2: Unidirectional links. Hop-by-hop routing protocols. but node C cannot transmit to node B and must use a different route to A. 2. M. This type of routing is referred to as source routing. The major advantage of on demand routing is that it saves bandwidth because it limits the routing overhead. The routes are stored and maintained in routing tables. Source routing vs. Bi-directional links can be established by lowering the distance between nodes. Hop-by-hop routing Some routing protocols include the entire route in the packet header. but has the disadvantage that it requires nodes to maintain and exchange routing information. node A can transmit to node B and B to C. In a highly dynamic network this increases routing related traffic. The disadvantage is the latency at the beginning of transmission to nodes when no route. but the disadvantage that they require nodes to periodically update routing tables. especially in large networks. It has the advantage that intermediate nodes are not required to maintain up-to-date routing information to forward the packet. the distance between the two nodes should be decreased. This has the advantage that it limits the packet size. Reactive Protocols can be proactive (also called table driven) which means that nodes periodically registers changes in the topology and updates routing information.1 Routing protocols There are several different principles that can be applied when constructing routing protocols for ad hoc networks. such as vector protocols. when data needs to be transmitted to a node where no route has yet been discovered. The opposite approach is the reactive (also called on-demand) protocols. only include information about the destination in the header and use local tables to determine the next hop on the route. The remainder of this chapter includes a general introduction to ad hoc routing protocols and an introduction to four well-known ad hoc routing protocols. The disadvantage of source routing is that the packet size can grow. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 6 . have yet been discovered [Zou].1. Proactive vs. Some comparisons of the performance of these protocols have been conducted and described in the literature and some of the results from these comparisons are summarized.2 . Routes are first discovered on demand. If node C should be able to transmit through the node B. The mode of operation for each protocol is explained. Proactive protocols have the advantage that there is little latency since routes are already available [Zou].
The protocol is of the hop-by-hop type. [Guoyou1]. 7 M. DSDV assumes that all links in the network are bi-directional. Assumptions A1. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . such as the one illustrated in Figure 2-3.2 The Destination-Sequenced Distance Vector (DSDV) Protocol The Destination-Sequenced Distance Vector protocol (DSDV) was introduced by Charlie E. Perkins and Elizabeth Royer in 1994 [Perkins1]. which requires that each router inform its neighbours of its routing table. No S406_H1 S128_H2 S444_H3 S123_H4 S489_H5 Install T001_H5 T001_H5 T001_H5 T001_H5 T001_H5 Table 2-1: Routing table for H4 node in the DSDV protocol.State of the art In the following sections some routing protocols that build on the described principles are investigated. 2. Mode of operation DSDV operates by having each node maintain a table with information about distances and information about the next node on a route. H3 H2 H4 H1 Figure 2-3: A simple topology H5 Table 2-1 illustrates the route information that the node H4 would store.2 . These modifications make the protocol more suitable for routing in ad hoc networks. This is a decentralized routing algorithm.1.Sc. The protocol is a modification of the Bellman-Ford routing algorithm [Siek1]. The protocol can be explained by looking at a small topology. Dest H1 H2 H3 H4 H5 Next Hop H2 H2 H2 H4 H5 Metric 2 1 2 1 1 Seq. Particular emphasis will be put on the description of the DSR protocol since this is the foundation for the subsequent design and implementation.
Assumptions A1. The next node on the route from H4 to H3 is H2. Undirected 2. A4. were links (edges) between nodes can be in one of the following three states: 1. Information concerning the next hop is stored in the Next Hop column.1. It is assumed that a link-level protocol. A2. Missing transmissions can be used by neighbour nodes to detect changes (broken links) in the topology. In this case node i is said to be downstream of node j. The value in the Install column is used to help determine when stale routes should be deleted. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 8 . Bi-directional communication between nodes is assumed possible. M. 3. Directed from node i to node j.State of the art Table 2-1 illustrates the nodes only stores information about destination and next hop. to inform others that the link is broken. which ensures that nodes always know their neighbours. Broken links may also be detected by communication hardware [Guoyou1]. The protocol is designed to minimize the reaction to topological changes and to discover multiple routes to a destination. 2. and the water in the tubes the packets flowing towards its destination” [Broch1]. which means that the metric is 2 (hops). The protocol uses a metric of height of nodes to direct the network. In this case node i is said to be upstream from node j. The tubes represent links between nodes. The sequence numbers in the Seq. and not about the entire route. When a node transmits a packet it is broadcasted to all of its neighbours. Routes with higher sequence numbers are considered more favorable. Each node in the network must periodically transmit its entire routing table to its neighbours. When a broken link is detected it is assigned a metric value of infinity and the node that detected the broken link broadcasts an update packet. No column is used to compare routes. Scott Corson [Corson1] in 1997. Directed from node j to node i.3 The Temporally-Ordered Routing Algorithm (TORA) The Temporally-Ordered Routing Algorithm (TORA) protocol was developed by Vincent D.2 . As seen. If the sequence number is the same the route with the lowest metric is preferred. A3. Park and M. The method of operation is described as “water flowing downhill towards a destination through a network of tubes that model the routing state of the real network. Mode of operation TORA organizes the topology as a graph. The protocol is an ondemand protocol that works by using a link-reversal algorithm such as the GafniBertsekas (GB) algorithms [Perkins2].Sc. is present. It is assumed that all transmitted packets are received correctly and in order of transmission. and H4 will therefore forward packets for H3 to H2. Finding the shortest path is considered to be of less importance in this context. the route from H4 to H3 goes through H2.
The protocol does not require any existing network infrastructure or administration and is completely self-organizing and selfconfiguring. When a node discovers that a route is no longer usable it will increase its height to a local maximum with respect to its neighbours and transmit an UPDATE packet.4 The Dynamic Source Route (DSR) Protocol DSR was first introduced and described by David B. The result of this process is a directed acyclic graph (DAG) [Corson1]. This strategy minimizes the number of nodes that needs to be informed of the changes in the topology. David A. e. since it correspond to a situation were water will flow back out of the node to the nodes that have been sending packets to it. The protocol basically consists of the two mechanisms: Route Discovery and Route Maintenance. The speed at which nodes move is moderate with respect to packet transmission latency. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . Assumptions Some assumptions concerning the behavior of the nodes that participate in the ad hoc network are made.2 . The protocol is specifically designed for use in multihop wireless ad hoc networks. A5. where the Route Discovery mechanism handles establishment of routes and the Route Maintenance mechanism keeps route information updated. The most important assumptions are the following: A1. The recipient broadcasts an UPDATE packet containing a value of the height that is a value that is assigned to the node. The establishment of routes essentially corresponds to assigning directions to links in an undirected network. When a node needs to establish a route to a destination D. This results in a set of directed links going from the sender of the QUERY.g. Nodes can detect and discard corrupted packages. it broadcasts a QUERY packet with the destination. The packet propagates through the network until the destination or a node with a route to the destination is reached. 9 M. Every time a node receives the UPDATE packet it sets its height to one greater than its neighbours. A3. 2.State of the art The protocol has three basic functions: • • • Establishing routes Maintaining routes Deleting routes. Maltz and Josh Broch in 1994 [Johnson1]. Each node can be identified by a unique id by which it is recognized in the network. Johnson.1. A4. To accomplish this task a query/reply process is used.Sc. who has the highest height value. in the interval of [5:10] nodes. The diameter of the network are often small. A2. All nodes that participate in the network are willing to participate fully in the protocols of the network. to the destination that has the lowest height value.
The two mechanisms: Route Discovery and Route Maintenance are described below. It timestamps the message so it can be examined later to determine if it should be send again. A unique ID that can identify the message. The hop limit can be used to limit the number of nodes that the message is allowed to pass. The address of the target.State of the art Especially A1 is interesting since it builds on the trust and good will of other nodes in the network.2 . If nodes have several network interfaces this information can be stored in this list. The sending node is referred to as the initiator and the destination node as the target. is send periodically and therefore routing traffic caused by DSR can scale down and overhead packages can be avoided. The fact that Johnson et al emphasizes this as an assumption [Johnson1]. such as route advertisement messages. If no route is discovered within a specified time frame. DSR stores discovered routes in a Route Cache. the packet is dropped M. referred to as the send buffer. The initiator initialize the Address List to an empty list and set the Initiator ID. This causes the packet to be received by nodes within the wireless transmission range.Sc. A list of all addresses of intermediate nodes that the message passes before its destination. There is an option of setting a bit so that the receiver returns an acknowledgement when a packet is received. which means that no data. DSR is a source routing protocol. which means the entire route is known before a packet transmission is begun. S initiates Route Discovery and sends out a ROUTE REQUEST message to find a route. Hop Limit Network Interface List Acknowledgment bit Table 2-2: Fields of the ROUTE REQUEST message. Route Discovery When a node S sends a packet to the destination D. If no route from S to D exists in S’s route cache. Mode of operation DSR operate on demand. The fields of the ROUTE REQUEST message are explained in Table 2-2. indicates that they notice that the goodwill of other nodes might not always exist in practice. the Target Id and the Unique Request Id in the ROUTE REQUEST message and then broadcasts the message. The Italic font are used to indicate fields used for the more advanced features of DSR. This is empty when the message is first send. Fields Initiator ID Target ID Unique Request ID Address List Explanation The address of the initiator. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 10 . The initiator keeps a copy of the packet in a buffer. it first searches its Route Cache for a suitable route to D.
Acknowledgment can be performed either by using mechanisms in the underlying protocol such as link-level acknowledgment or passive acknowledgment. Packets are also dropped from the send buffer if the buffer overruns. In this message the link that was broken is included. When a node receives a packet it is responsible for confirming that the packet reaches the next node on the route. Route Maintenance Since nodes move in and out of transmission range of other nodes and thereby creates and breaks routes. The figure also illustrates that node C might use another route to communicate to node A. The target searches its own Route Cache for a route to the initiator. The reason that the target node doesn’t just reverse the found route and use it is that that would require bi-directional links. Figure 2-4 that the mechanism works like a chain where each link has to make sure that the link in front of it is not broken. When a node receives a ROUTE REQUEST message it examine the Target ID to determine if it is the target of the message. This ROUTE REPLY message includes the accumulated route from the ROUTE REQUEST message. it performs a route discovery of its own and sends out a ROUTE REQUEST where it piggybacks the ROUTE REPLY for the initiator. If a node transmits a packet and does not receive an acknowledgment it tries to retransmit a fixed number of times. The initiator removes the route from its Route Cache and tries to transmit using another route from its Route Cache. If the node is the target it returns a ROUTE REPLY message to the initiator. ROUTE ERROR ROUTE ERROR ROUTE ERROR A Message B Message C Message D E ACK ACK Figure 2-4: The acknowledgement mechanism works like a chain. it is necessary to maintain the routes that are stored in the Route Cache. If a route is not found in the targets Route Cache. it is possible to specify that only the first should be handled and the subsequent discarded [Johnson2]. the transmitting node can set a bit in the packets header to request a specific DSR acknowledgment. If a route is found it is returned.State of the art from the send buffer.2 . Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . If no acknowledgement is received after the retransmissions. If the node is not the target it searches its own route cache for a route to the target.Sc. If not. it returns a ROUTE ERROR message to the initiator of the packet. If no route is available in the Route Cache a ROUTE REQUEST is transmitted in order to establish a new route. 11 M. the nodes own id is appended to the Address List and the ROUTE REQUEST is broadcasted. If a node subsequently receives two ROUTE REQUESTs with the same Request id. If none of these mechanisms are available.
Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 12 . but are not covered here. “Storms” can occur when a node broadcast a ROUTE REQUEST and its neighbour nodes all has routes for the target in their cache. This section gives an overview of these additional features. Replying to Route Request Using Cached Routes When a node receives a ROUTE REQUEST message for which it was not the destination it can attempt to find a route from its Route Cache instead of broadcasting the ROUTE REQUEST.2 . Avoiding Storms of Route Reply When nodes are allowed to reply to ROUTE REQUEST messages with routes from their Route Cache the risk of ROUTE REPLY “storms” is present.State of the art Additional features in DSR As explained in the above sections DSR has a quite simple mode of operation. Hop Limits on ROUTE REQUEST Messages Table 2-2 shows the ROUTE REQUEST has a field that can be used to limit the number of hops that the packet may pass. This delay effectively randomizes the time at which a node returns a ROUTE REPLY message. This mechanism is called snooping and is mostly used for snooping of routes.Sc. This can be avoided by letting the nodes delay ROUTE REPLYs for a random period. since nodes can discover new routes this way. If a route is found it is returned to the initiator. This will result in simultaneous ROUTE REPLYs from all neighbours that can cause congestion or packet collision. However several additional features exist. If the node has another route to the destination it can use it and thereby salvage the packet. It is possible to use the hop limit to implement an expanding ring search. Caching of Overheard Route Information Nodes can cache information about routes from packets that they overhear or forward. as a result of a ROUTE REQUEST. The node must however verify that the route that is being returned does not contain any duplicating nodes since this can lead to loops. If the hop limit is increased by 1 every time a ROUTE REPLY is not received. M. If the packet is salvaged a ROUTE ERROR should be send to the original sender to report the link on the route that was broken. the search for a suitable route will spread like a ring in the water. through the use of Route Maintenance. it might successively discover. This can be used to send non-propagating ROUTE REQUESTs and thereby query neighbour nodes to examine if one has a suitable route to the destination route in their Route Cache. that the route for the packet is broken. Some features such as prevention of increased spreading of ROUTE ERRORs and storing of compromising information exist. For example a node can cache the route that is returned in a ROUTE REPLY message when it forwards it. The use of route snooping can limit the amount of ROUTE REQUEST that are sends. Johnson points out the risk that this expanding ring search could have the affect of increasing the average latency of Route Discovery [Johnson1]. Salvaging Packets When a node forwards a packet.
but none of these seems to have resulted in a unanimous recommendation of one protocol over the others and no standard has yet been adopted. The purpose of the section is to give the reader an idea of different protocols performance. It is a requirement that the broadcast medium provides the means so nodes can detect neighbour nodes broadcast messages.2 . The overall goal of the comparison was to measure the protocols ability to adapt to changes in the topology and still deliver packets. in 1998 [Broch1]. The path maintenance mechanism used by AODV is quite similar to the one used by DSDV and therefore AODV will not be described further. the total number of packets send during the simulation. The protocol is a hybrid of the DSR protocol and the DSDV protocol.5 The Ad-Hoc On Demand Distance Vector (AODV) Protocol The AODV protocol was presented in 1997 and is designed by Charlie E. 2. Assumptions A1. DSDV. The primary objectives for the AODV algorithm are: • • • To broadcast discovery packets only when necessary.Sc. It uses a route discovery process much similar to the one used by DSR and makes use of hop-by-hop routing like DSDV.State of the art Automatic Route Shortening If a node overhears a packet that it eventually would receive it can return a “gratuitous” route reply to the original sender to inform the sender that a shorter route exists. 13 M. TORA and AODV are all compared using the same simulation environment (Ns-2) under similar conditions.6 Comparison of Ad Hoc Routing Protocols This section gives an introduction to some of the results of performance comparisons of ad hoc protocols that have been presented in literature [Broch1] [Johnson1]. who also designed the DSDV protocol [Perkins1]. Mode of operation As mentioned the route discovery process is much similar to the one used by the DSR protocol. the ratio between the number of packets that the application layer sends to the protocol and the number of packets received at the destination. To distinguish local connectivity management (neighbour nodes) from changes in the entire topology. The protocols were evaluated using three metrics: • • Packet delivery ratio. AODV differs from DSR in the way that nodes do not store the entire route to a destination. Perkins and Elizabeth Royer. One of the most comprehensive comparisons seems to be the one conducted by Josh Broch et al. DSR. To try to forward information concerning changes in local connectivity to neighbour nodes who are likely to need it. Routing overhead.1. Summarizing all results and conditions is not in the scope of this thesis.1. 2. Several performance comparisons of the protocols described in this chapter have been conducted over time. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .
This prevents that each application has to implement its own authentication mechanism. The four ad hoc routing protocols listed below have been described. 2. The Dynamic Source Routing protocol AODV. 4 or more hops than the optimal route were measured for some packets. such as proactive. Based on the results from the performance analysis and the fact that DSR is based on source routing. is not given much significance. For DSR these results correspond well to other results presented in literature [Johnson1]. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 14 .Sc. source route based and hop-by-hop based have been discussed. The research and investigations described in this section has lead to the fulfillment of the preliminary objective PRE-O 1. The abilities of TORA and DSDV to deliver packets depend on the movement patterns of nodes in the network. Destination-Sequenced Distance Vector protocol TORA.7 Summary In this section ad hoc networks have been introduced and different types of routing protocols for ad hoc networks. Trust management systems M.2 . This gives a unified mechanism so policies and credentials can be exchanged between different systems. the difference between the number of hops a packet took and the length of the shortest path. The trust management system supplies languages to represent policies and credentials. Ad-hoc On-demand Distance Vector The mode of operation and different assumptions for the protocols were covered. 2. the trust management system. It is concluded by several sources that DSR has the lowest routing overhead [Johnson1].1. supports the decision to apply trust based routing to DSR. [Broch1]. Finally some results from performance comparison of the four protocols have been pointed out.State of the art • Path optimality. AODV and TORA have significantly worse results. which means that the whole route is known at the time of transmission. reactive. The presented results show that DSDV and DSR seem to route very close to the optimal routes. since the cost of transmitting a packet is much greater than the cost of adding some extra bytes [Broch1].2 Trust Management Systems This section introduces trust management system in order to fulfill part of the preliminary objective PRE-O 3. The results show that DSR and AODV deliver over 95% of the packet regardless of the mobility rate of nodes used for the simulations. The basic idea of the trust management systems is that applications delegate authorization issues to a standard component. Temporally-Ordered Routing Algorithm DSR. Trust management systems are used to handle authorization issues in distributed systems. The fact that DSR packets contains a high number of bytes since the entire route is contained in the packet. • • • • DSDV. the more rapidly the nodes move the more packets be dropped.
2. Matt Blaze.keyn REQUEST ActionString ActionString is an application specific message that corresponds to some kind of trusted action requested by one or more public keys. so it is required that applications that use trust management systems handle the appropriate integrity checks and signature validations. Flexibility: The system must be expressively rich enough to support complex trust relationships and at the same time it must be possible to express simple and standard policies succinctly and comprehensibly.State of the art only handles authorization issues. alternatively on which third party it should rely for an appropriate “certificate”. key2.…. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . defines the following principles for trust management [Blaze1]: • • • • Unified mechanism: Policies. The system was the first tool that embodied the four trust management principles described above. PolicyMaker does not deal with the identity of the user of the key. in 1995 [Blaze1]. These predicates are used to describe actions that the keys are trusted to sign for.2 . PolicyMaker binds public keys to predicates.1 PolicyMaker PolicyMaker was developed by Matt Blaze et al. PolicyMaker processes the queries based on trust information contained in assertions. authentication and enabling of functionality. Assertions are of the form: Source ASSERTS AuthorityStruct WHERE filter 15 M. PolicyMaker takes as input a query of the form: key1.2. which makes the system ideal when anonymity is a requirement. credentials and trust relationships are expressed as programs and existing programs are forced to treat these concepts separately. who is one of the pioneers in the area of trust management. It is possible to add filters to the query so it only returns the ActionString if the filter predicate holds. Separation of mechanism from policy: The method for validating credentials does not depend on the credentials themselves or the application that uses them. The PolicyMaker system can be thought of as a form of database that the application queries for answers of the questions of the type: “May the key K perform action A according to the local policy LP ”. Locality of control: Each node in a network can decide whether it will accept credentials presented by a second party or.Sc. Unlike other systems. These systems have been selected because they are the most referenced in literature and because they are well documented. PolicyMaker is suitable for use together with services whose main goals are privacy. The following sections will introduce three of the most prominent trust management systems.
State of the art Source indicates the source of the assertion.Sc. AuthorityStruct specifies the public key(s) to which the assertion applies. In such a case the calling application needs to determine which action should be taken. Trust management systems seek to answer the questions: M.2 . This means that the system can be used to write policies about policies.4 Summary This section has introduced the basic principles of trust management systems and has covered three of the most known trust management systems: PolicyMaker. Like other trust management systems KeyNote does note enforce the policies upon the system. The answer to a query can be true. policies about cryptographic keys. As a result of passing this Action Environment. 2. KeyNote returns an application specific string.2. it only provides advice to applications that call it. One of the main differences between PolicyMaker and Keynote is that KeyNote has a simpler syntax and semantics aimed specifically to build public-key infrastructure applications were PolicyMaker aimed to provide a framework for a wider range of applications [Blaze3]. The system differs from PolicyMaker and KeyNote in the way that it is designed to help making access decisions concerning web sites. either a local policy (policy assertion) or a public key of a trusted third party (signed assertions). All trust decisions are based on policy control. KeyNote instead uses an Action Environment.2. 2. which in the simplest case could be “Action authorized”.3 REFEREE The REFEREE (Rule-Controlled Environment For Evaluation of Rules and Everything Else) system is from 1997 [Yang].2 KeyNote The KeyNote trust management system is a direct successor of the PolicyMaker system. This Action Environment is passed from the application to the KeyNote system. Like PolicyMaker and KeyNote it functions as an engine that can be queried for recommendations. The Action Environment is a triplet that consists of: • • • The security policy A list of credentials The request. Unknown means that the system was not able to make a decision about whether the requested action could be recommended using the policy that was in force. KeyNote and REFEREE. 2.2. It is also developed by Matt Blaze and builds on the same ideas as PolicyMaker. certificates or anything else. Where the PolicyMaker uses queries. The introduction has lead to fulfillment of part of the preliminary objective PRE-O 3. false or unknown. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 16 .
The devices (Laptops. Zhou et al identifies the following properties that need to be covered in order to obtain a secure ad hoc network [Zhou]: Confidentiality: Ensures that certain information is protected from unauthorized disclosure. 17 M. One of the major security obstacles is the absence of a fixed infrastructure. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . and presents some of the proposed solutions to such issues. which makes it impossible to use existing trusted servers in the used security mechanisms.State of the art Is the request R signed by the key(s) K allowed under the policy P? The idea behind trust management systems is to separate the development of the authorization mechanism from the development of the application. etc) are moved around which makes it hard to secure them physically. Since the mechanism for verifying credentials does not depend on the format of the credentials themselves. As mentioned earlier in section 2. Furthermore. recorded for replaying or altered.2 . mobile phones. DSR and AODV. It is difficult to protect physical connections.3 Security In Ad-Hoc Networks This section discusses some of the security issues that are related to wireless Ad-Hoc networks. different applications with different policies can share a single verification infrastructure. On a virtual level many different kinds of attacks can be made on the routing protocols. 2. Since security is such a complex field it is often divided into sub parts. DSDV. Ad hoc networks are vulnerable to security attacks on both physical and virtual levels. 1.1. none of the protocols. The two problems identified by Sharp actually cover several sub areas of security. Sharp recognizes the following two main problems for obtaining security in a distributed system in general [Sharp]. This is done by providing languages and API’s that can be used to specify policies and credentials and a mechanism to evaluate requests based on the specified credentials and policies. The nature of wireless Ad-Hoc networks makes their security characteristics different from other kinds of networks. the use of wireless links makes the network vulnerable to link level attacks [Zhou]. 2. Integrity: Guaranties that a message is never corrupted or modified. PDA’s. Availability: Ensures that the network is functional despite of denial of service attacks and available when expected. which means that one should assume that communication can be overheard. accommodates mechanisms to deal with any type of attacks or malicious behavior. It is hard to determine whether or not the party you are communicating with really is who you think he is. TORA.Sc.
it its doubtful whether the proposed solution can be applied to a collaborative network. Organizational M. 2.State of the art Authentication: Offers facilities for confirming that the node that one is communicating with is actually the party that one believes it to be. confidentiality and availability [Zhou].Sc. The service has one public/private keypair k that is divided among the trusted servers. 2. Each of these servers has a public/private key pair and stores all public keys of nodes in the network. the used examples and some of the areas that the paper cover indicates that the area of application assumes that a single authority is present in the network. It is assumed that n trusted servers are present in the network. To incorporate trust levels in the ad hoc network Yi et al.1 Zhou et al Key Management Service Zhou et al proposes a key management solution. If nodes receive a packet with a security metric or trust level that they cannot provide the packet is dropped and nodes that cannot provide the level of security will not be a part of the route. Non-repudiation with proof of origin is used when the sender cannot deny that he was the sender of the data and Non-repudiation with proof of delivery prevents the receiver from denying that data was received. Figure 2-5 illustrates the procedure S1 Server 1 PS(m. The protocol embeds the metrics for the security level that an application wants to use into Route Request packets. proposes that existing organizational hierarchies is mirrored in the ad hoc network.3.2 The Security Aware Ad-Hoc Routing Protocol (SAR) Yi et al proposes the SAR protocol to improve security in ad hoc networks [Yi]. A message is given a digital signature in order to obtain integrity.s3) Figure 2-5: Threshold signature. The following sections introduce different approaches to obtain one or more of the security properties mentioned above. which aims to ensure integrity. Even though it is not stated directly in Yi’s paper.3. The use of threshold signatures makes it possible to sign a message even though some servers in the network are compromised.2 . Since the trusted servers do not gain any benefits. Non-repudiation: Ensures that data has been sent or received by a particular party. even though server 2 is compromised it is still possible generate a signature. and impossible for a compromised server to sign the message. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 18 . The service adopts a public key infrastructure (PKI). These servers know the public keys of other servers and can establish secure links among each other. The signature is given by the use of a threshold signature method [Desmedt].s1) m S2 Server 2 (compromised) Combiner <m>k S3 Server 3 PS(m.
compared to the expected behavior of a node. In ad hoc networks the identity of a node might be less important. Using entity recognition. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . To obtain authentication a simple shared secret is used to generate symmetric encryption/decryption key per trust level. major events organization etc. This has the advantage that entities can establish relationships without having pre-determined knowledge of each other. by binding a secret key to an identity. The results showed that even though the overhead per control message were higher. this binding does however not give any information about how the entity is expected to act.3 Entity Recognition Seigneur et al recognizes that traditional authentication mechanisms such as Public Key Infrastructure (PKI) or Kerberos [Kohl] might not be in suitable for ubiquitous computing [Seigneur]. The issue of how to distribute this secret in the first place is not treated.State of the art hierarchies may exist in many forms of ad hoc networks. The protocol is implemented as an augmentation to the AODV protocol and simulations were carried out using the Ns-2 [NS2] simulator. which means that nodes on a different level cannot read the packets.Sc. Seigneur et al proposes the. No proposals are presented on how to handle a situation were no organizational hierarchy exists.2 . Entity Recognition The Entity Recognition (ER) process is compared to the normal Authentication Process (AP). Packets are encrypted on each trust level. The protocol requires that nodes can be authenticated. the performance were sustainable. e.3. Authentication Process A1:Enrollment Entity Recognition A2:Triggering E1:Triggering A3:Detective work E2:Detective work E3:Retention A4:Action E4:Action Figure 2-6: Comparison of Authentication Process and Entity Recognition 19 M.g. However. A Peer Entity Recognition scheme (APER). search and rescue operations. an entity recognizes another entity but does not care about its identity. Traditional authentication schemes help to establishing the identity of an entity. to be used to achieve entity recognition. The comparison is illustrated in Figure 2-6. 2.
If the recognizer has one of these hashes the claim can be treated as “fresh”. A Watchdog is used to monitor and identify malicious nodes in the network and a Pathrater to adjust nodes trust rating based on the number of packets they forward. Level 2 requires Level 1 to be fulfilled.3. E3 Step E3 is optional. APER offers three levels of recognitions: Level 1 requires that a claimant’s signature be verified over a set of recently fresh claims. APER requires that public key encryption is possible.4 The Watchdog – Pathrater approach Marti et al describes two techniques that can improve the throughput in an ad hoc network [Marti]. that normally acquires an administrator. Transmission of the DSR ROUTE REQUEST could be an example of self-triggering. If the response is correct.2 . One way to do this recognition is to use the APER scheme. which means that an entity takes initiative to recognize potential surrounding entities. The basic approach is that the claimant occasionally broadcasts a digitally signed packet. E4 Step E4 is also optional. 2. Level 3 requires Level 2 to fulfilled. A Peer Entity Recognition scheme (APER) The APER scheme can be used to perform the step E2: Detective work of the ER scheme.State of the art E1 In step E1 some kind of triggering takes place. At any time the recognizer can challenge the claimant if desired. When the recognizer sends a challenge to a claimant using the claimant’s public key. that the wireless M. and further requires that the claimant can respond successfully to a challenge. is unessesary for Entity Recognition. since no action has to be performed if the only objective of the process was to collect recognition information.Sc. E2 In step E2 some detective work is done in order to see if the entity can be recognized. It is a requirement for the watchdog technique to work. the recognizer and the claimant. which is described in further details later. and gives entities the possibility to establish relationships build on previous recognitions. APER provides a strong recognition scheme when using level 3. the claimant needs its secret key to produce a correct response. Figure 2-6 illustrates the first step of the normal Authentication Process A1: enrollment. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 20 . Further. the recognizer can re-associate the public key with some context information such as the claimants network address or similar. since the recognition information does not need to be stored – for instance if the entity has been seen before. APER uses two roles. Triggering can be selftriggering. to ensure that the claim is “fresh” and not just copied from some another broadcast network. the claimant’s claim must include the hashes of the last n claims.
The Watchdog cannot detect a misbehaving node in the presence of • • • • • • Ambiguous collision Receiver collision Limited transmission power False misbehavior Collusion Partial dropping Marti et al.5 The CONFIDANT protocol The CONFIDANT protocol works as an extension to reactive source routing protocols like DSR [Buchegger1].3. Thereby. will be identified and expelled by the other nodes. showed that the throughput in the network. when nodes are dropping packages. Marti et al identifies that the mechanism has some weaknesses that are listed below. The monitor registers “’bad” behavior and notifies the reputation system so suitable actions can be taken. the node will update the trust rating of the forwarding node in a positive manner. 2.2 . Simulations executed on the Ns-2 simulator. a disadvantage is combined with practicing malicious behavior. The trust ratings are then used to determine which routes to use. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . If packets are forwarded. This means that other nodes have to detect a malicious node on the path and report it back to the destination. which allows nodes to receive all packets that are transmitted within their range. to avoid that innocent nodes are punished. When an ALARM message is received the Trust Manager determines whether there is sufficient trust in the node that send the message. The Trust Manager sends out ALARM messages to warn friendly nodes of malicious nodes. This actually means that malicious nodes are rewarded for their behavior. The increase in throughput can however lead to a routing overhead of up to 24%. It is important to notice that a node can only monitor if a neighbour forwards or not. etc.State of the art interface supports promiscuous mode. The basic idea of the protocol is that nodes that does not forward packets as they are supposed to. if packets are forwarded as supposed. Malicious nodes are not punished for the misbehavior. could be increased by up to 27 % by adopting the Watchdog and Pathrater techniques.Sc. It is possible to monitor. have implemented the Watchdog and Pathrater techniques in the DSR protocol. ALARM messages are only communicated amongst friendly nodes. If a packet is not forwarded the Pathrater will adjust the nodes trust rating in a negative way. unusually frequent route updates. The Watchdog monitors whether neighbour nodes forward packets as they were supposed to. and they still get their own packets forwarded while they at the same time is relieved of forwarding packets from others. not nodes that are two or more hops away. How to 21 M. The protocol consists of four components: • • • • The Monitor The Trust Manager The Reputation System The Path Manager The Monitor is used to monitor the behavior of neighbour nodes.
DSR fortified with CONFIDANT lost less than 3% of the packets. duck. here the packet is traded for nuglets. Each forwarding node then takes some amount of these nuglet in order to cover the cost of forwarding the packet. Several security mechanisms such as the presence of trusted and tamper proof hardware and a public key infrastructure is necessary in order to introduce nuglets. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 22 . so eventually the destination node will pay for the packets. It also handles request for routes from malicious nodes by simply ignoring them. Two methods for performing this task in practice are proposed.) as their mother. Two methods for implementing the nuglets are proposed: The Packet Purse Model (PPM) and the Packet Trade Model (PTM). presents the idea of using so called nuglets as a virtual currency in ad hoc networks [Buttyan]. The sending node then takes the lowest bid and forwards the packet.Sc. This rating is changed when a node behaves malicious. Buchegger et al. The ratings are only changed in a negative manner.2 . M. was that the introduction of nuglets did not decrease the performance of network significantly. Further simulations showed that the DSR fortified with CONFIDANT performed well with a fraction as high as 60% malicious nodes. One is to calculate a fixed charge u for each hop on the route and use a protection mechanism to ensure that each forwarding node only takes u of the nuglets. This approach requires that the sending node have knowledge of the total number of hops on the route. there is no way to win it back. The PTM works a bit opposite. The resurrecting Duckling [Anderson]. The Path Manager ranks the routes according to their reputation and ensures that no malicious nodes are used in routes. To implement this method Buttyan et al.State of the art establish friend relationships among nodes are still in the area of research but the CONFIDANT protocol adopts an approach known as. The main result of the simulations run by Buttyan et al. were DSR alone lost up to 70% of all packets [Buchegger2].3. 2. The other method is to have an auction where all neighbouring nodes bid on the price for forwarding the packet. Further there are several unsolved issues such as how to get new nuglets. It is usually described as the scenario. Simulations showed that in some situations. cat. which can be a significant problem for nodes in the periphery of the network. It is most often used in computer science by establishing a friend relationship with the first entity that sends a secret key to the duckling [Anderson]. where ducklings emerge from their shell and identifies the first living creatures they see (dog. etc. This is done since malicious behavior ideally is identified as an exception [Buchegger1]. In PPM the sending node attach some amount of nuglets to the packet being send. propose to let nodes use an agent to perform the bidding on their behalf. The nuglets are introduced to motivate nodes to corporate and provide services to each other. which means that once a nodes trust is broken. The Reputation System keeps a trust rating of nodes. Whether or not a nodes behavior is malicious is determined according to a threshold function. has implemented the CONFIDANT protocol on top of the DSR protocol and done simulations using the GloMoSim [Bajaj] simulator.6 Nuglets Buttyan et al.
Authentication and non-repudiation has been described. Integrity. uses a Watchdog to identify misbehaving nodes and a Pathrater to manage nodes ratings. The CONFIDANT identifies misbehaving nodes. which has to be handled in order to obtain a secure ad hoc network. however unsolved issues related to the case when a node runs out of nuglets. the CONFIDANT protocol punishes misbehaving nodes by refusing to forward their packets. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . Nodes use nuglets to pay other nodes for forwarding their packets. confidentiality and availability and builds on threshold encryption and distribution of keys among several trusted servers. There are. The SAR protocol incorporates trust levels in the network that reflects hierarchical structures of the domain where the ad hoc network is used. Another interesting aspect of Keane’s work is that the results clearly showed that malicious nodes had very low trust values. This is different from the CONFIDANT approach because nodes only rely on their own observations. These trust values are adjusted based on the nodes experiences. Several proposed solutions on how to achieve one or more of the security properties: Confidentiality. By storing and maintaining trust values for nodes he was able to identify malicious nodes in the network. Unlike Marti et al solution. Availability. The key management system is designed to secure integrity. By using a shared secret on each level authentication and confidentiality is achieved. John Keane [Keane] developed and applied trust based routing DSR. The main idea behind trust based routing is to store information about the trust that one node has in other encountered nodes. By examining these areas the preliminary objective PRE-O 2 was fulfilled. The solution proposed by Marti et al. had a higher throughput than standard DSR.7 Trust based routing In his master thesis from 2002. The source routes are evaluated based on some heuristic that uses the nodes trust value as criteria.Sc. Keane introduced trust based routing and applied it to DSR and achieved increased throughput in some situations. Simulations showed that introduction of nuglets did not decrease the networks performance significantly.State of the art 2.2 . The results were however not ambiguous since they also showed that standard DSR outperformed the trust based routing in situations with a high number of malicious nodes. Zhou et al key management system and The Security Aware Ad-Hoc Routing Protocol (SAR) is designed to function in environments where a single trusted authority is present and therefore they build on some strong assumptions that does not hold in collaborative ad hoc networks where such an authority is not present.8 Summary This section has covered some of the security issues. alarm friends about the misbehaving nodes and keeps a trust rating of nodes. Simulations of both solutions showed an increase in throughput when malicious nodes were introduced in the network.3.3. Keane’s results showed that his implementation. in some situations. such as packet drops or acknowledgements receipts. which indicated that they were identified as malicious nodes. Buttyan et al introduce the use of nuglets as a virtual currency. 2. 23 M.
one might trust a neighbour to look after ones goldfish. M. and c) he perceives the strength of Va. The use of the word perception implies that trust is subjective [Marsh] and differs from person to another person. he makes a distrustful choice. Trust is also difficult to measure.4 Trust Even though trust is widely used in our daily life. both before he can monitor it (or independently of his capacity ever to be able to monitor it) and in a context in which it affects his own action. Many trust-based decisions are made on a subconscious level. which adds to the complexity of the subject. Some definitions seem to be more widely accepted than others. Another definition of trust comes from Diego Gambetta who has gathered thoughts from diverse areas such as economics and biology. Furthermore.Sc. If he chooses to take an ambiguous path with such properties. I shall say he makes a trusting choice. but not ones child. One of the reasons for its complexity is that it is difficult to define exactly what trust is. and by many people it is an extremely complex subject to work with. 2.4. if he chooses not to take the path. The definition also implies that some kind of analysis of the benefit of Va+. symmetrical distrust) is a particular level of subjective probability with which an agent assesses that another agent or group of agents will perform a particular action. compared to the cost of Va-. In his work from 1990 he gives the following definition of trust [Gambetta]: Trust (or. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 24 . One might be bold to state that trust lies in the eye of the beholder. one person’s reasons for trusting somebody might differ from another persons. The perhaps most popular and recognized definition is stated by Morton Deutsch in 1962 (copied from [Marsh]): a) The individual is confronted with an ambiguous path. a path that can lead to an event perceived to be beneficial (Va+) or to an event perceived to be harmful (Va-). together with two frameworks that can be used to express trust in a formalized manner. b) He perceives that the occurrence of Va+ or Va. This section introduces some of the most widely accepted definitions of trust and some of the properties of trust. several people have defined trust in various ways. is performed in order to choose the path.1 Definitions of trust As mentioned earlier. and it is often difficult for people to determine why and if they trust one person and not another.2 . Further it seems that trust in some way is related to the risk that is associated with a given situation or action [Marsh].in contingent on the behavior of another person.State of the art 2. In the following some of the most recognized definitions of trust is introduced.to be greater than the strength of Va+. This is reflected by the many different definitions that exist in literature.
In the exhaustive work “The meaning of trust” [Mcknight]. Further the definition indicates that the ability to monitor whether the trusted action is performed is of importance. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . Trusting Intention. even though it is realized that it can have negative consequences. A difference between Gambetta’s and Deutsch’s definitions is that Deutsch uses trust in a person. which means the extent to which one believes that proper impersonal structures are in place to enable one to anticipate a successful future endeavor. Gambetta also notes the subjectivity of trust. Dispositional Trust. Similar to the definition of Deutsch.4. and facilitates scientific measurements and predictions. which is the extent to which one consistently trust in a wide variety of situations and in different persons. 2. where Gambetta includes trust in a group of agents. Trusting Belief. which makes it difficult to specify general rules. which means the extent to which one intends to depend on a non-specific other party in a given situation. is able and willing to act in ones best interest. The trust constructs are: • System Trust. which means that it can be given a value in the range from 0 to 1.2 . that builds on analysis of more than sixty papers related to the area of trust. To cope with this issue several attempts have been made to make some classification of trust. It differs from situational trust in the way that the person is known in this situation and there fore prior experiences can be used to determine the degree of trusting belief. uses trust construct to categorize trust.Sc.State of the art Gambetta expresses trust as a probability. which is the extent to which one party is willing to depend on another party in a given situation with a feeling of relative security. 25 M. Situational Trust.2 Different categories of trust Trust is subjective and depends on both agent and situation/action. • • • • • • Figure 2-7 illustrates how the trust constructs are related. Belief Formation Process. which is the process where experience and information is used to create new trusting beliefs. The trust constructs relates to each other as antecedents and consequents. Mcknight et al. Trusting Behavior is the extent to which a person voluntarily depends on another person in a specific situation with a feeling of relative security. which is the extent to which one believes another person in a situation. though it is realized that it can have negative consequences.
which is derived from an agents past experiences in all prior situations. but simpler classification [Marsh]. However the introduction of recommendations or similar can be used to construct transitive trust relations. Trust depends on the situation that an agent is in. This is illustrated in Marsh’s framework by the introduction of situational trust. • Basic trust. There is however no unambiguous agreement on how this evolution is expressed.State of the art T ru s tin g b e h a v io r T ru s tin g in te n tio n T ru s tin g b e lie fs S itu a tio n a l tru s t D is p o s itio n a l tru s t B e lie f fo rm a tio n p ro c e s s e s S y s te m tru s t Figure 2-7: Relations between Mcknight et als. It could be in a linear. is a decision laced with risk [Marsh]. There seems to be a general agreement in the literature that trust evolves over time. General trust. exponential function or other kind of way.3. Situational trust.4. gains from a situation. which can be illustrated by the following statement: ”If Ann trusts Bob and Bob trusts Cathy. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 26 . and can be adjusted in both positive and negative directions dependent on experiences. which is the trust that one agent has in another agent in a given situation. It represents how trustful an agent is. Basic trust corresponds to dispositional trust. Trust Constructs The construct above gives an insight in how one type of trust can lead to another. then Ann trusts Cathy”. which is covered in section 2. which expresses the utility an agent. Importance and utility. Further it is recognized that some sort of relation exists between risk and trust. M. • • • The classification of trust leads to a more formal way of describing trust.Sc.2 . Stephen Marsh uses a somewhat similar. inspired by the work of Mcknight et al. from Mcknight et als categories. which represents the trust of one agent in another agent. since a decision to trust someone or something. There seems to be a general understanding that trust is not transitive.
The more complex example in Figure 2-9 illustrates how a general trust value for agent z in agent x can be derived.g.g.+1].. It is considered out of the scope of this thesis to cover all of these.g.+1] [-1. Several basic rules are introduced in Marshs framework from which others rules can be derived.2 .4. The notation can be found in Table 2-3 and builds on the trust categories described in section 2. x knows y at time t) Importance (e. Since crisp values are used it is possible to do a numerical comparison and ordering. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . …. b. Marsh’s Framework Marsh’s framework makes it is possible to express trust values over time. Jonker and Treurs Framework Jonker and Treurs framework focuses on the dynamics of trust based on experience [Jonker]..3 Frameworks for Working with Trust This section briefly introduces two frameworks that can be used to describe and work with trust in a formal manner. of α to x at t) Basic Trust (e. α)t Values True/False [0.g. .2. or Sx ∈ A Kx(y)t Ix(α)t Ux(α)t Txt Tx(y)t Tx(y.+1] [-1. … A S1. … a. β. ∨ (OR) and ¬ (NEGATION) it is possible to express and derive complex rules.+1] [-1. but to give the reader an idea and overview of how the rules looks some examples is given below in Figure 2-8 and Figure 2-9. of x in y at t) Situational Trust (e.g..Sc.+1] [-1.g. By applying operators such as ∧ (AND).+1] Table 2-3: Temporally indexed notation in Marshs framework It is notable that trust can be assigned a crisp value in the interval [-1. The framework introduces a basic notation and two types of functions: The 27 M. of x at t) General Trust (e. The example in Figure 2-8 shows how the cooperation of y can lead to a higher trust value.4. of α to x at t) Utility (e.. Description Situation Agents Set of agents Societies of agents Knowledge (e. c.State of the art 2. of x in y for α at t) Representation α. Cooperate(y)x ⇒ Tx(y)t+1 ≥ Tx(y)t Figure 2-8: The cooperation of y in a situation a leads ¬ K z (x ) ∧ K z ( y ) ∧ K y (x ) ⇒ K z (x ) t t t t +a ∧ Tz ( x ) ( t +a ≤ T y (x ) t ) ∧(Tz (x )t + a ≤ Tz ( y )t ) Figure 2-9: Example showing how trust can be derived. S2. As Figure 2-9 illustrates z’s trust in x does not exceed the trust z had in y. Marshes framework does not focus on a particular way to express the functions used to determine the crisp values of the different trust types.
Set Description E A partially ordered set of experience classes for N The set of natural numbers ES The set EN of experience sequences T A partially ordered set of trust qualifications/trust values Possible values {-.1] 0. 4.State of the art trust evolution function and the trust update function. Definitive having trust: which means that after a certain number of positive experiences a state of unconditional trust is reached and remained in. The following types of initial trust are used: 1. the agent has a unconditional trust of maximal trust value b. Initially distrusting a.2 . Blindly negative. HIGH} . which can be either: a.+}. 1. 5. Blindly positive. which can be either: a.-. Always unconditional distrust b. In the framework several possible properties of these functions are identified and expressed in a formal way. 6. …. The basis of the framework is the four sets shown in Table 2-4. Without prior trust influencing experiences. {+. Without prior trust influencing experiences. the agent has a conditional trust value below the maximal trust value 2. Jonker and Truer identifies the following six types of trust dynamics: 1. Definitive losing trust: after a certain number of negative (sequenced) experiences a state of unconditional distrust is reached and remained in. Always unconditional trust b. 3. Initially trusting a. Balanced fast: The evolution in both positive and negative direction is fast. Balanced slow: The evolution in both positive and negative direction is slow. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 28 . the agent has a unconditional distrust of maximal distrust value b. fast positive: It is easy to gain trust but hard to loose it.1]. [-1.+. MEDIUM. -1. fast negative dynamics: It is hard to gain trust but easy to lose trust. the agent has a conditional distrust above the minimum distrust value. 1} {LOW.-} or {1. 2. Slow positive.[-1. Without prior trust influencing experiences.Sc. 2. Slow negative. Without prior trust influencing experiences. 1. +. Table 2-4: The four sets of the framework M.
2.4 Summary This section has introduced different definitions and key aspects of trust. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . The dynamics of trust is described by 29 M. only uses past experiences to determine the trust value. This property is interesting since its value can lead to quite different results. The trust update function is defined as: tu: E × T → T Equation 2-2 A trust update function uses a prior determined value of trust and a new experience to calculate a new value for trust. The framework presented by Marsh is suitable for describing trust in different situation where the framework presented by Jonker and Treur focuses on describing the dynamics of trust based on experience. Trust Evolution Function A trust evolution function. 1. -1. An interesting property is the degree of memory based on window n that expresses the number of experiences back in time that should be used in the calculation. the trust update function and several properties of the functions. Two categorizations of trust have also been covered. -1. of trust evolution functions. 1. Trust Update Function The trust update functions differ from the trust evolution function since it uses the current experience and the last calculated value of the trust to calculate the new trust value. such as minimal and maximal initial trust.4. Figure 2-10 illustrates a small example: Trust evolution function T= ES [-1.2 . 1] Tn=8 0 Tn=4 -1 ∑ ES 1 n n Figure 2-10: Using the degree of memory based on window n for trust evolution functions As the example illustrates quite different result is achieved by using a window size of 8 instead of a window size of 4. The trust evolution function is defined as: te: ES × N → T Equation 2-1 Jonker and Treur identify sixteen possible properties. -1. Furthermore some of the most important properties of trust have been identified.Sc.State of the art The four sets are used to define the trust evolution function. To illustrate the complexity and versatility of trust. some of the most common definitions of trust have been discussed. 1. The categorizations lead to a better understanding of how the different types of trust are related. Two frameworks that make it possible to describe and work with trust in a formal way has been introduced.
is the next node on the route.2 trust management systems were introduced. However. In section 2. The completion of the investigation of trust and formal trust frameworks. DSR and AODV were described. Investigations showed that by using the APER protocol it is possible to establish relationships with nodes and recognize encountered nodes.2 . Several assumptions for the protocols where summarizes. this is not really applicable to the type of ad hoc routing that is the foundation for this thesis and therefore none of the covered trust management systems is incorporated in the designed protocol. where AODV only stores information about the next hop on the route and used hop-by-hop routing. Both frameworks propose to use the interval [-1.3 several different approaches for achieving different levels of protection against malicious behavior in ad hoc networks were introduced. The results of the evaluations indicated that DSR and AODV both delivered a high percentage of the send packets. The above observations have contributed to the decision on applying trust based routing to the DSR protocol.5 Subjective evaluation of methods and techniques Where the previous sections has sought to keep an objective perspective of the introduced areas. Solutions. By using APER it is possible to achieve authentication in ad hoc networks. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 30 . In section 2. offers encryption and a relatively high level of security. this section includes subjective evaluations of some of the covered areas and put into perspective if. 2. Marti et al [Marti] identifies that none of the routing protocols described in this chapter handle security issues.State of the art introducing the two functions: the trust evolution function and the trust update function. Section 2. It would be quite a challenge to apply trust based routing to AODV since the only information that is available to build some sort of trust based decision on. In section 2. TORA. These requirements make them less applicable to the ad hoc routing used for this thesis.1 the four protocols DSDV. but also requires trusted servers to achieve this level of security. M. All assumes that no nodes are malicious and are willing to participate in the routing protocol.6 dealt with performance evaluations done for some of the protocols.1] to represent trust values.Sc. such as the Security Aware Ad-Hoc Routing Protocol (SAR) and Zhou et als key management system.1. Since DSR is a source route protocol and therefore stores the entire routes it is possible to make a much better trust based evaluation of the route. has lead to the fulfillment of stated objective PRE-O 3.and how they can be applied to develop trust based routing. One of the main differences between DSR and AODV is that DSR uses source routing and stores the entire routes. Trust management systems can be used to handle authorization and access issues.
Keane’s results where somewhat ambiguous since standard DSR could outperform his implementation even though the percentage of malicious nodes where high. Most of the results that are summarized from other sources [Johnson1]. but it is not really clear what happens if a friend acts malicious. which is a C based language where Ns-2 is based on C++. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . Further. Keane achieved improvements on throughput in some situations by applying trust based routing to DSR. However. since friendly nodes send out ALARM messages.State of the art Other protocols such as CONFIDANT and the Pathrater – Watchdog mechanism monitor nodes to detect packet drops. Both methods have problems with detecting collusion because they rely on other nodes to report malicious behavior. Keane’s methods differs considerable from the Pathrater – Watchdog and CONFIDANT because he does not rely others to report and observe malicious behavior. Further he showed that storing and updating trust information could be used to identify malicious nodes. GLOMOSIM is implemented in the language Parsec [Parsec]. It is chosen to use the Ns-2 simulator because it has a C++ implementation of DSR. [Buchegger2] are achieved by doing simulations on either the Ns-2 simulator [NS2] or the GloMoSim simulator [Glom].5 Buchegger et al achieved good results with DSR fortified with CONFIDANT. However the mechanism of using ALARM messages to adjust the rating of paths seems rather vulnerable to misuse. [Broch1]. As mentioned in section 2.Sc. Jonker and Treurs framework is aimed at describing the dynamics of trust and is found well suited to describe the evolution of trust. How collusion can be handled is not treated which is somewhat a deny of a problem. it is found important to use some formal ways to describe the trust processes that is going to be used in this work. Since trust can be a rather informal area. 31 M. Marsh’s framework is found well suited to express the different types of trust that are used in certain situations. In section 2. the process of establishing friends is still under investigation.2 .3. which eliminates problems with collusion and establishment of friends.4 the two frameworks by respectively Marsh and Jonker and Treur were briefly presented.
.
It is a possibility to perform a ring search as described in section 2. 33 M.1.1 Analysis of DSR This section presents an analysis of the different events that can take place during communication within the DSR protocol. This represents a serious problem in the case where only one route that contains a malicious node is available. Since ring search will limit the number of routes that are actually discovered and thereby increase the risk that all returned routes to a node include malicious nodes this might not be a good approach to use. favoring short routes. such as increased ROUTE REQUESTs is somewhat unclear.1 Sending of packets The following issues concerning the sending of packets are identified: Using ring search to discover routes When a node has to send a package it queries its route cache for a route. An important observation is the fact that once DSR has a route to a destination it will use this route as long as it believes that it is working.1. In order to fortify the DSR protocol it is necessary to find ways to estimate whether a node is malicious or not. This route selection strategy must instead be based on trust heuristics. 3. the DSR protocol is analyzed to identify different situations where malicious nodes may exploit vulnerabilities in the protocol. During the analysis situations were one nodes trust in others can be established or updated are identified. Forwarding of packets – the case where a node is a hop on the route to the final destination. The relevant events can be divided into the following three categories: • • • Sending of packets – the case where a node is the source of the packet.3. Some vulnerabilities cannot be handled by introducing trust and therefore the analysis also identifies situations were trust is found insufficient to make a useful defend. If no route is found it broadcasts a ROUTE REQUEST. Furthermore some of the extensions that are made to the DSR protocol are investigated. There are several vulnerabilities in DSR that can be exploited by malicious nodes. The identified issues are prioritized by assigning high priorities to issues where trust can be applied. Selection of the “best” route DSR selects routes from the cache based on the number of hops on the route. meaning until it receives a ROUTE ERROR. Possible solutions on how to handle these exploitable situations are presented. The area of trust based route selection strategies are investigated further in section 4. 3. the possible outcome and possible reactions to the outcome.4. Therefore introducing new mechanisms to discover new routes in the case where only one route containing a potential malicious node is available is considered out of scope of this assignment.3 .Sc.1.Analysis 3 Analysis To meet the main objective M-O 1. Receiving of packets – the case where the node is the final destination of the packet. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . It requires changes to DSR to poll for new routes if the routes available have to low a trust value and the consequences.
When a packet is received it also means that all nodes on the route actually forwarded the package correct. The area of acknowledgements strategies is covered in further details in section 4. Forming trust relationships and updating trust When a packet is received. Therefore the only suitable solution is to use another route to the destination. for instance by issuing false ROUTE ERRORs. Trust updating is described in further details in section 4.1.2 and trust formation is described in section 4. ROUTE REPLYs It is possible that malicious nodes return fictive non-usable routes in ROUTE REPLYS. This M. One way to deal with this is to evaluate the received route based on the trust in the sender and not trust. ROUTE ERRORs When a ROUTE ERROR is received it means that a link is broken which causes DSR to select a new route and truncate the broken route from the route cache. route reply’s from nodes with low trust. with a low trust value and the route cache contains a recently used route that the link was part of the trust value of the node could be adjusted in a negative manner. It would involve cooperation of nodes in the neighbourhood to monitor the link. A malicious node forwarding a ROUTE ERROR might alter it so it looks like a different link on the route is broken or it might issue a false ROUTE ERROR.1. Since it is difficult to identify positive node behavior that could lead to an increase in trust without the use of acknowledgements there must be some mechanism for requiring acknowledgements.1. There is a chance that the source of the route is malicious and does not forward packages. This would however mean that nodes that act according to the DSR protocol could be punished and for this reason it is decided to let DSR handle ROUTE ERRORs. 3. To discard a ROUTE ERROR message and still use the route would be useless since it would not be possible to decide whether the link was really broken or if a malicious node had forged the ROUTE ERROR. The route might contain unknown nodes which means that an initial trust relationship with these nodes must be established. Therefore some extra fields are added to the packet header for this purpose. Therefore the trust value for the source of the route is not updated. If the ROUTE ERROR comes from a node.5.1.2 Receiving packets This section describes and evaluates issues that can occur when a node receive a packet. It could be beneficial to increase trust for the nodes that forwarded the ROUTE ERROR and decrease trust for the node that caused the error. If malicious nodes flip this bit it can prevent the receiver from returning acknowledgements or cause the receiver to send acknowledgements that was not requested.1. There is also a risk that a malicious node uses ROUTE ERRORs for framing.Analysis The use of DSR acknowledgement mechanism As illustrated in Table 2-2 there is an option that allows the sender to set an acknowledgement bit in the DSR packet header in order to request an acknowledgement of the packet. the reversed route is stored in the cache. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 34 . This knowledge is used to update trust values for the nodes on the route. It is difficult to determine if the link between two nodes is broken without relying on one of them.Sc.3 .
A solution to verify that the address list is not defective has been proposed in the section ROUTE REPLYs were the reception of ROUTE REPLYs was discussed. Some of the information stored in the cache might not be valid because nodes can have moved out of range. which will probably cause the route to be useless. There is no way for the initiator of the ROUTE REQUEST to directly detect that the route has passed through a node that has not added it self. The new nodes are therefore given a trust value based on a trust formation strategy.3.Analysis evaluation would however apply to all returned routes and cause extra computations and it would not solve the problem where a malicious node forged the reply so it seemed to be initiated by some other node.3. This might represent a problem because it can cause bad routes to be distributed. turned their power of.5. 35 M. but simply noticed that the problem exists. Another method for verifying the route is to let all nodes create a hash value based on the address of the node that forwarded the packet and thereby successive confirming each step of the route. The following issues concerning the forwarding of packets are identified: Drop of forwarding packet All forwarding packets can be dropped.1. To avoid the risk that nodes alter routes. it is not investigated further here. the entire route could be signed and the signature included in the payload as well as in the packet header. On the other hand it might prevent new routes from being discovered.Sc.3 . Even though Hu et al proposes a solution. to this problem. Another issue is that the cache represent some a learned part of the topology.1. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . the route might contain previously unencountered nodes. As pointed out in section 2. Hu et al points out that. This means that the node should establish an initial trust relationship with these nodes. This problem is known as cache staleness. There is nothing that can be done to prevent that a nodes drops a packet. replying from the route cache and at the same time allowing route snooping might result in stale routes circulating the network indefinitely [Hu]. When a ROUTE REPLY is received. 3. uses a monitor technique to detect when a node is not forwarded packages. By replying with a route from the route cache the number of forwarded route replies are limited which decreases the overhead on the network.3 Forwarding of packets Issues of forwarding packets are mostly related to behavior of malicious nodes. This would of course increase the size of the payload and it would require that cryptographic methods were available. Tampering with ROUTE REQUESTs When forwarding a ROUTE REQUEST message a malicious node can choose not to add its own address to the address list. etc.4 it is optional to reply to route replies from the route cache.4 and 2. The Pathrater – Watchdog technique and the CONFIDANT protocol that was described in section 2. If only one route that includes a malicious node is contained in the cache this route is returned. These techniques do however not adequately solve the problems of framing and collision among malicious nodes and therefore it is decided to use another approach where nodes only base decision on their own experiences and not on events that other nodes inform them of.
it might never discover the two routes going through E and F. In order to avoid that nodes remove other nodes from the address list it would require each node to sign its own address in the list. a malicious node can choose to remove prior encountered nodes on the route from the address list or insert other nodes. The figure illustrates a situation where node D has broadcasted a ROUTE REQUEST. However it is likely that the route can be snooped from some other route. M. Due to the increased overhead that disallowing snooping will cause. which means that when a node forwards or overhear a packet it can snoop the route and cache it for later use. This means that the routes going through E and F will not be discovered and D will be stuck with a route with a malicious node. Node C has propagated this to nodes E.3 . since it eventually would result in a useless route.1.4 it is possible to let nodes reply to the first received route request and discard subsequently received route request with the same unique id. it is chosen to allow route snooping.Sc. This would especially be critical if the packet was a ROUTE REQUEST.Analysis Tampering with the address list When forwarding a packet. If a snooped route contains unknown nodes initial trust relationships must be established. DSR has the possibility of snooping routes. Only forwarding the first route request received As described in section 2. Figure 3-1 illustrates how node C might not discover some routes. but in some situations it might limit the number of routes that are discovered to a destination because nodes that has a route to a destination will not issue new ROUTE REQUESTs to discover new routes to that destination. This would most likely result in a useless route. B and F. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 36 .4. The use of route snooping will decrease the amount of ROUTE REQUEST packages that are send.1. E A B C D F Figure 3-1: If node C snoops the route from D to A. As Figure 3-2 illustrates this can lead to potential routes being undiscovered. Snooping of source routes As described in section 2. Node B is malicious and its ROUTE REQUEST is first received at node A.
3 - Analysis
E
A
First received Route Request
B
C
D
F
Figure 3-2: Only forwarding the first received ROUTE REQUEST can result in undiscovered routes.
It is expected that it is beneficial to let nodes reply to all route requests because it can increase the number of discovered routes and thereby decrease the probability of only discovering routes with malicious nodes.
3.2 Extensions to DSR
The above analysis revealed that the use of the DSR acknowledgement mechanism might not be suitable, since it is easy for malicious nodes to flip the acknowledgement bit and thereby tangle up the protocol. The only possibility for evolving trust relationships has this far been on receipt of packages. This is however insufficient, since a node might never receive packages that was forwarded by a certain route and therefore not be able to identify bad routes. In order to create a mechanism that can be used to base trust evolution on extra fields should be added so acknowledgement could be requested. The analysis also revealed that the route selection criteria used by DSR should be altered to trust based instead of using a shortest path heuristic.
3.3 Assumptions made about malicious nodes
In order to have a simple setup as a starting point, the following assumptions will be made about the malicious nodes in the scenarios. • Malicious nodes will not forward any packages for other nodes. This behavior is the most common one used by other people [Buchegger1] doing research in the same area and therefore it is a natural choice if the results from the simulations should be comparable. Malicious nodes will not return acknowledgements. This assumption is made to start with a simple scenario. By making this assumption it will be reasonable to increase trust for all nodes on a route that returned an acknowledgement. If malicious nodes also returned acknowledgements the source of an acknowledgement should have its trust value increased. However, it will also mean that nodes that successfully forward packets to malicious nodes will have their trust values decreased. Unfortunately time did not allow evaluation the impact of this assumption had compared to letting malicious nodes return acknowledgements.
•
37
M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
3 - Analysis
The malicious behavior specified above, means that malicious nodes does not forward route replies, but they do however reply to route replies, meaning that if a malicious node has a route to a destination it will return it. If the returned route includes the malicious node a route containing a malicious node is returned. This makes impossible to avoid routes that do not contain malicious nodes. Furthermore, one should keep in mind, that good nodes can also drop packages unintended due to queue overruns, low battery etc, which means that a good node unintended can exercise malicious behavior.
3.4 Attacks that are not covered by the analysis
There are some attacks against the DSR protocol that are not analyzed in this thesis. This does however not mean that they does not represent possible problems, but simply means that there were considered out of the scope of this project. Some of these attacks are: • • Denial of service attack where a node is bombarded with traffic. Traffic analysis, which is not a real attack. Introducing trust based routing might cause traffic analysis to become a problem since nodes that forward packages will be preferred. This could be exploited by forwarding all packages for a node and thereby achieving a high trust value. A node with a high trust value would most likely be exposed to a high traffic flow that could be analyzed.
3.5 Prioritization and general assumptions
A prioritization of the solutions is done in order to restrict the design and implementations. The solutions are prioritized using an estimate of the importance to the overall goals, of fortifying DSR against the presence of nodes that does not forward packages, by introducing trust based routing, and the expected complexity (and the involved expenditure of time) of implementing the solution. It is chosen to design and implement the following: • • • • Trust formation mechanisms. Methods for updating trust based on experiences Methods to handle receipt and time outs of acknowledgements Trust based route selection
A solution that implements these areas is found to be sufficient to fortify DSR against malicious behavior that express it self as nodes dropping packets that they were supposed to forward. This means that all issues concerning tampering with packet are not handled as well as issues concerning authentication and confidentiality. Therefore the solution will build on the assumptions that these issues are handled. As section 2.3 illustrated solutions to handle these issues exists and therefore the assumptions are considered reasonable.
M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
38
3 - Analysis 3.6 Summary
This chapter has presented an analysis of the DSR protocol where vulnerabilities has been identified and discussed. Solutions to handle these vulnerabilities have been proposed. It has been decided to design a solution that will implement the following: • Nodes will store trust values of each encountered node that express the nodes trust. These values will be adjusted based on the experiences that a node has with other nodes. In order to require acknowledgements for received packages an extension to the existing DSR header will be implemented. When nodes receive acknowledgements or data packets they will update trust values for the nodes on the route, based on some trust updating policy. Nodes that are encountered for the first time, will have an initial trust value assigned based on some trust formation strategy. If a requested acknowledgement is not received within some timeframe the nodes on the used route should have their trust values decreased. Route selection will be based on some strategy that uses the trust in the nodes on the route to conduct an evaluation of the entire routes trust value. The extension will only seek to deal with malicious behavior that express it self as nodes dropping packets that they were supposed to forward.
• •
• • •
How these task are handled is described in chapter 4. The decision to implement a solution covering the above tasks have also meant that issues concerning identification and tampering with packets is not treated further, but is assumed to be dealt with.
39
M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
.
1 Identification of components From the analysis conducted in section 3. The chapter also covers design of the different components that are used to incorporate trust in the DSR protocol. a component that can store and manage access to trust values is also needed. which means that functions will be referred to as methods even though there is a general agreement among C++ programmers that the word function is used.1 some major trust related processes are revealed: • • • Initializing trust relationships Updating trust values Route selection based on trust These processes provides the foundation for the trust based routing protocol that is going to be designed and will be implemented in one or more modules. 4. An implementation of the DSR protocol exist in the Ns-2 simulator that is used for the simulations and therefore parts of the design will have to be compatible with the existing code. • • • • Further more. A component that evaluates routes according to the trust values of nodes on the route. the existing code is analyzed and a UML class diagram is derived. method will also be used in chapter 5 that deals with the implementation. Based on the analysis. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . The notations from section 2. Furthermore. 41 M. To keep consistency. It must also be possible to store the experiences that a node have had with other nodes since this is required in order to apply a trust evolution function as described in section 2.4 is used to describe the types of trust that are used in the different situations. A component that implements methods to update trust for known nodes. Finally a description of how the design can be integrated with the existing code is given.4.Design 4 Design This section presents the overall design of the modules and strategies that are going to be applied to the DSR protocol in order to incorporate trust formation and trust updating which are necessary to meet the main objective M-O 2. Since the design is object-oriented.Sc. object-oriented notations will be used. A component that manages incoming and outgoing acknowledgements. components to manage the following tasks are needed: • A structure to represent the trust that one node has in another node. Figure 4-1 illustrates the overall design. A component that determine the degree of trust to unknown nodes when they are encountered for the first time.4 .3.
1. Nodes will be encountered from ROUTE REPLYs or when routes are snooped.y2…yn) = Tx) ∃y Kx(y) ⇒ Tx( K(y1. the initial trust value will be the nodes basic trust. meaning that the node would be initially distrusting and therefore having a low basic trust. several other strategies can be thought of for this purpose. As mentioned earlier trust is subjective and depends on a given nodes experience in a given situation.2 Trust updating The trust updating component implements the functions for updating trust.y2…yn))) Where y1.4.4 . When the first routes are discovered all nodes on the route will be unknown and therefore a default value trust value for unknown nodes needs to be determined.1.y2…yn ∈ Route ¬ Equation 4-1 4. that the route is not stronger than its weakest link. This strategy is described using Marsh’s notation from section 2. If a route contains known nodes the trust value of these nodes is used to base the assignment of initial trust. This means that it is not reasonable to construct a general method for updating trust values that will be applicable to all applications in all domains. a strategy were the lowest trust value of the known nodes are assigned to the unknown nodes. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 42 . However. ∀y ¬Kx (y1.Design TrustUpdater TrustFormater ACKMonitor TrustManager T-value T-value RouteSelector DSR Figure 4-1: Overall architecture of the trust based extension 4. The function designed here is aims to function in domains with several malicious nodes. The argument for choosing this strategy is.y2…yn) ⇒ ( Tx(y1. Because of the expected importance of this parameter it is estimated from simulations as described in section 6.y2…yn) ) = Min(Tx(K(y1. which is the node with the lowest trust. In an environment with many malicious nodes it would be expected that it would be best to assign a low value trust value.1. Since the route is later going to be evaluated based on the trust value of each node. The value of this parameter is quite important because it determines how close the node is to achieve maximal trust. In a situation where the route does not contain known nodes.Sc. M.3 on Equation 4-1.5.1 Trust Formation The trust formation component implements methods to assign trust values to nodes when they are first encountered.
because an acknowledgement is a response and confirmation of the trust that a node put in other nodes. where the receipt of data packet can be seen as a recommendation from the source to the destination. which means that nodes on the route have forwarded the package. tv) = d ∗ tv + (1 − d ) ∗ ev Where tv: The existing trust value ev: The experience d: A constant used to express the inflation of trust Equation 4-2 Based on the observation that Jonker and Treur propose the intervals [-1. The opposite counts when an acknowledgement is not received within the timeframe. Figure 4-2 illustrate the impact that the inflation constant d has on the behavior of the function. This is not considered as powerful as an acknowledgement. • • • • Previous trust values. Acknowledgement timed out and Data packet received. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . that interval is used for both experiences and trust values. Since the cause cannot be determined a value of –1 is assigned to this experience.7.Design A function for updating trust can depend on several parameters.4 . Lowest/Highest trust value ever assigned. This means that it must be assumed that the packet never reached its destination.Sc. Ideally the behavior of the function should depend on the expected trust dynamics in a given situation. The experience set will consist of three experiences that correspond to: Acknowledgement received ok. The situation/value of an experience. In the list below some of the possible parameters are listed. Nr of positive/negative experiences in the past. only one function is used. Therefore this experience will be given a value of 0. 43 M. The final experience is receiving a data packet. Since the trust values are used to base decision on which route to choose. An acknowledgement indicates that all nodes on the route could be trusted and therefore a value of 1 (maximum trust) will be assigned to this experience.1]. Jonker and Treur propose the following trust update function [Jonker]: f d (ev.
0. M. A good route is considered to be a route that does not contain malicious nodes. Defining a route selection strategy is not an unambiguous task.0. This makes it quite difficult to argue for one routing strategy over another and therefore several route selection strategies will be proposed and used in the simulations.1.4 . This means that good nodes that accidentally drop packages will not loose trust to fast. It can be concluded that a route that contains a malicious node is not good because it will always result in a packet drop.Design Trust update function based on Equation 4-2 1. This means that the best route will be considered as the one that has the highest trust rating. The routes are evaluated and the route with the highest rating should be used.5 maximum trust will be placed in node after only a few experiences.5 1 0.3 Route selection The main task of the route selection component is to evaluate routes based on the trust value of the nodes that constitute the route and selects a route based on this evaluation. but actually they do not have anything in common that. determining the best route can actually lead to a good route being discarded and a route containing a malicious node being chosen. Here metrics such as latency could be used.5 -1 -1. With a d value of 0.9. from a sociological point of view. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 44 . As the coming discussions of route strategies will illustrate.9 0 -8 -6 -4 -2 10 12 14 16 18 -2 0 -1 8 -1 6 -1 4 -1 2 -1 0 20 0 2 4 6 8 d =. With a d value of -0.5 TrustValue d =.5 -0. Only full positive experiences with a value of 1 and pure negative experiences with a value of -1 are used and the initial trust is set to 0.9 trust will evolve as balanced slow. At the same time it means that a node with a high trust value that causes a negative experience will have its trust value lowered in a perceptible way.Sc. Based on the fact that a good node can also drop packages unintended d will be given the value -0. This corresponds to trust evolving as balanced fast. Nodes are grouped as one because they are on the same route. To decide whether one route that results in a packet being delivered is better than another that achieves the same is difficult.5. It is also possible to use one value for d when for positive experiences and another for negative experiences and thereby let trust evolve faster in one direction than the other.5 Sum of experiences Figure 4-2: Trust update function based The graph illustrates that a high d value will lead to a faster trust evolution towards maximum (or minimum) trust value. 4. can substantiate the grouping.
It is chosen to design simple strategies. y2…yn ∈ Route Using the average presents the issue. because it will make it easier to determine the effect and difference between the strategies. because the destination might be identified as a malicious node and therefore have a low trust value. Route 1 2 Trust ratings for nodes on the route 0. Route 2 consists of four nodes where three have maximum trust value and one has minimum trust value. since that means that the destination is a neighbour.7 and 0. This increase in latency is the expected prize of an increase in throughput. illustrated in Table 4-1.75 Table 4-1: Evaluation of routes using the average of nodes trust value to evaluate the route Table 4-1 illustrates an example where two routes are evaluated by route selection strategy 1. the trust values change to the values shown 45 M. the route is used without examining further routes. all strategies return a maximum rating if the route only consists of two nodes. If a maximum rating is returned.7 0. This is actually a performance improvement compared to the implemented strategy used by standard DSR in Ns-2.5 1 1 -1 1 Rating 0.5.5 this would mean that the node evaluating the route have had positive experiences with all nodes. and therefore malicious nodes will also be the destination of packets. It is expected that the application of other route strategies than the shortest path used by DSR. This is necessary because the traffic is generated randomly for the simulations.4 . Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . will lead to a higher latency. Route consists of four nodes with values between 0. Furthermore. With an initial trust value below 0.Sc. as the Rating column shows route 2 is rated higher than route 1. The designed routing strategies are basic strategies that can be considered archetypes from which more complex and sophisticated strategies can be derived. That the node has minimum value indicates that it is a malicious node.Design Common for all routing strategies is that must not take the destination of the packet into account when the rating of the route is calculated. where all routes to a destination is examined even though the destination is a neighbour. By using Equation 4-2 with a negative experience with value –1.7 0. Tx ( Route) = ∑T (y ) x n 1 n Equation 4-3 n Where y1. Whether or not a node would actually send packets to a node that was identified as malicious is not treated here. However. The example illustrates an extreme case and it is difficult to predict how often such a situation occurs.6 0. Routeselection strategy 1 The first route selection strategy will be to return the average of all nodes on the route.5 0. that routes containing nodes with very low trust values might still be rated high.
32 Average of the experiences 1 1 1 0.175 Table 4-3: Route selection strategy 2 favor shorter routes The strategy does still present the issues that strategy 1 has. This illustrates that the there is a fast response to experiences. In order to favor shorter routes the average of the trust values. This has the advantage that nodes with a high trust value that suddenly starts to drop packages will be identified faster than by using the trust value. routing strategy 3 evaluates the nodes based on the average value of the past experiences. Tx ( Route) = ∑T (y ) x n 1 n Equation 4-4 n2 Where y1.64 0.2 where the trust value of the node.7 0.2 Table 4-4: Route selection strategy 3 will detect a good node that starts to drop packets fast The table illustrates that the use of the average of experiences will identify a good node that starts to drop packets faster than the use of trust value.Sc.60 0. Route 1 2 0.7 Rating 0.8 -1 0.7 0. However. In a domain where short routes are more frequent. which is the number of experiences that are remembered. This is illustrated in Table 4-4. y2…yn ∈ Route This strategy will favor shorter routes from longer.8 Rating 0.7 0.55 0.7 Trust ratings for nodes on the route 0. which results in route 1 having a higher rating than route 2. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 46 .5 0.23 0. Route 1 2 0.7 0.4 .32. will be set to 5. calculated using Equation 4-2.Design in Table 4-2.5 0. this strategy might result in a lower latency than strategy 1.7 0.5 0. is divided by the number of nodes.6 0. The size of the experience window.8 Trust ratings for nodes on the route 0. After three positive and to negative the average of the experiences is 0. Experience nr 1 2 3 4 5 Experience value 1 1 1 -1 -1 Trustvalue calculated based on initial trust of 0.35 Table 4-2: The values from table Table 4-1 after having had a negative experience with value –1 and route 2 Routeselection strategy 2 The second route selection strategy is an extension of the first. is 0. as illustrated in Table 4-3. routing strategy 3 requires more M.7 # 0.5 using Equation 4-2 0.7 0. Routeselection strategy 3 Instead of using the trust value of the nodes.47 0.
. it has the disadvantage illustrated in Table 4-5. by using a sliding window mechanism [Sharp]. It also functions as the main interface between the existing implementation of the DSR protocol and the trust updater and trust formatter module.2 it is necessary to use an acknowledgement mechanism to base trust updating on.1. 4.0 0. In general acknowledgements leads to a packet overhead that of course should be minimized.9 0..Design computations compared to strategy 1 and 2 because it uses the experiences and not only the trust values. In a real life scenario it is likely that nodes will move about in the same environment for some time. One way to minimize the packet overhead is to limit the amount of acknowledgements send. For this reason the trust management module implements IO methods for storing trust values in a persistent way so they can be loaded again. Route 1 2 Trust ratings for nodes on the route -0. 4. 47 M.4 . If a node has a value below some threshold value the route is rated with the lowest possible value.35 As seen strategy 5 will select route 1 over route 2 even though all nodes on route 1 has low trust values.3 -0. It will however also have the disadvantage that the highest rated route might is discarded in the case where all routes have a rating below the threshold.5 Acknowledgement monitoring As described in section 3. y 2 . However.1. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .3 -0.35 Table 4-5: Example of routing strategy 5 Equation 4-5 Rating -0. To keep it simple it is decided not to use a sliding window mechanism but instead require acknowledgements for all data packets and not for protocol packets. Routeselection strategy 5 This strategy returns the lowest trust value of the nodes on the route and thereby the route is evaluated based on the least trustworthy node.Sc. Tx ( Route) = min (Tx ( y1 .3 1. y n )) Where y1.3 -0. Instead of returning the average a threshold is used..3 -0. y2…yn ∈ Route This has the advantage that the route with the highest of the lowest trust values is used. This will have the advantage that routes with low trust values are not used.9 -0. Routeselection strategy 4 Route selection 4 is applied to strategy 3 but can be applied to all other strategies. and offers methods to query for information about stored trust values. This means that the same nodes can be encountered on a regular basis.4 Trust management The trust manager module stores trust information about all known nodes during run time.
to base decisions on retransmission on. TO = (2 L − 2 ) * tc Where TO = Total time out value.2.Sc. and because a node can be part of many routes it is important that a missing acknowledgement is detected fast. it might be considered to M. Calculation of the time out value means extra processing. A B C D Time from source to destination Time from from reception to forward Figure 4-3: Estimation of total timeout value As Figure 4-3 illustrates the number of links a packet will pass is one less than the number of nodes on the route.4 . In this case the nodes trust values should be adjusted in a negative way. Since the node will not be in a state where it is waiting to receive the acknowledgement before it can continue. as known for many other protocols. the packet is considered dropped.5. On the other hand a large timeframe might result in a bad route being used several times before it has its trust values decreased. tc = Time out constant Equation 4-6 The time the packet will spend on the actual physical wire is considered small compared to the time it will take for a node to process it and therefore these two times has been combined to one timeout constant. to be rated low. Simulations used to estimate an appropriate value for the timeout constant is described in section 6. The time it takes for a packet to reach its destination will depend on the length of the routes. If a requested acknowledgement is not received within some time frame. but forwarded data packets and acknowledgements. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 48 . Since the return route of the acknowledgement will depend on the destinations route selection it is unknown how many nodes it will include and therefore the double of the length of the outgoing route is used as the ebst estimate.Design The purpose of the acknowledgement mechanism is to use received acknowledgements or lack of acknowledgements to adjust trust values and not. An acknowledgement id is stored when the packet is send. Trust relationship should be formed with any unknown nodes on the reply route and known nodes on the reply route should also have their trust values updated. Since the trust values are used to base routing decisions on. it is expected that a relatively high timeout value can be accepted. and if an acknowledgement is received within the time frame nodes on the stored route have their trust values updated. A short time frame might cause routes that where simply slow. If the system were to be used on a device where the available CPU where limited. The following formula for estimating the total time that a node will wait for an acknowledgement will be used.
1. This simulator already offers an implementation of the DSR protocol. can be made at run time by an application that use the protocol.4 . This is however not done in the implementation. often used nodes trust values. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .Sc. Since the implementation of the DSR protocol has a considerable size. Figure 4-5 is a class diagram of the Ns-2 implementation of DSR that shows the most relevant classes and their relations. Therefore it is used for the TrustUpdater module. the analysis presented here only covers the most basic functionality and classes. 4. TrustValue * 1 RouteSelector TrustUpdater 1 1 1 1 1 TrustManager 1 1 ACKMonitor 1 * ACKData 1 RouteSelectorS1 RouteSelectorS2 TrustFormater TrustUpdater1 TrustUpdater2 TrustFormater1 TrustFormater2 Figure 4-4: Class diagram of the trust related modules It should be possible to change the different strategies by changing a minimum of the code.Design cache timeout values for the most common route lengths or simply use a fixed value.6 Combining the trust modules Since most modules need access to the trust values the trust manager module offers methods that can be accessed by the other modules for this purpose. based on analysis of parameters such as the number of timed out acknowledgement requests (which indicates the number of dropped packets). the TrustFormation module and for the RouteSelector module. The Strategy design pattern [Gamma] is suitable for such designs since its application makes it possible to change modules/strategies during run time. Decisions of which strategy to use.1.7 Existing DSR Implementation in NS-2 As mentioned earlier the Ns-2 simulator is used to simulate the protocol. In order to ease the implementation of the design. Since no such application is designed for this project the strategies are selected before a simulation is started. an analysis of the existing DSR implementation is presented in this section. 4. 49 M. etc.
There are several possible types of packages but only the ROUTE REPLY is included in the diagram since it is the most relevant. M.Sc.Design DSRAgent inherit from several other classes than agent RouteCache Agent DSRAgent 1 1 * «datatype» SRPacket DSR packets 1 1 1 MobiCacheClass +FincRoute() «datatype» hdr_sr Header information Figure 4-5:Class diagram of the most relevant classes used in the Ns-2 DSR implementation Figure 4-6 illustrates the process that takes place when a packet is received. If no route is available in the route cache a ROUTE REQUEST is broadcasted. If the packet has a source route it means that it has either reached its destination or it needs to be forwarded. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 50 . To obtain a source route the route cache is queried. When a ROUTE REPLY is received the route is added to the cache. If a route is returned the packet is placed in a queue where it waits to be sent of by the underlying layer (the interface queue). If the packet has reached its destination its type is determined.4 . If it is an outgoing packet it needs a source route to the destination. First it is determined if it is an incoming or outgoing packet.
Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .Sc. is called to handle further processing of the packet. When the type of the packet is determined a method called handleXXX. The packet header is implemented in the hds_sr class and methods from this class are used to examine if the packet has a route and which type of packet it is.Design start packet received true source route vallid False true Destination False Forward packet Outgoing packet False Error True find route False Send ROUTE REQUEST True Send packet Packet type ROUTE REPLY Add route Other packet Handle other packets Figure 4-6: Illustration of the flow that occurs when a packet is received The process from Figure 4-6 involves corporation between several classes. The Mobicache class is used to store routes and offers methods to add and get routes. The main branching is performed in the DSRAgent class where the recv() method is called upon receipt of packages.4 .1. where XXX indicates the type of packet. When a packet is received and it has been determined that the packet has reached its final destination the handlePacketReceipt() method in • 51 M.8 Merging the trust modules with the existing DSR code The trust extensions interface with DSR in the following situations: • In order to implement the acknowledgement mechanisms extra fields to indicate whether the packet is an acknowledgement or an acknowledgement receipt has to be included in the hdr_sr class. 4.
This method is altered so the route selection strategy defined in the RouteSelector class is used.Sc. When a packet is being forwarded the handleForward() method in the DSRAgent class is called. When the route cache is queried for routes the findRoute() method in the MobiCache class is called.4 . The findRoute() methods is also used to find routes that are returned as answers to ROUTE REPLY’s. Further a method for constructing and sending the acknowledgment packet has to be implemented. Therefore processing of acknowledgement request is handled here.Design DSRAgent is called. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 52 . • Every time a route is added to the route cache by a call of the addRoute() method the TrustManager has to be called to examine the route for previously un-encountered nodes and form initial trust relationships according to the strategy implemented in the TrustFormater class. M. Introducing trust based route selection to this DSR implementation therefore has the side effect that a node will return the route it evaluates as the most trust worthy. • • Figure 4-7 shows a class diagram of the combined classes. In this method malicious behavior is implemented to force packet drops.
The Trust Manager propagates the call to the TrustFormater. There are three major sequences that involves interaction between several classes: • • • Adding a route and initializing trust values Processing a received acknowledgement Selecting a route Figure 4-8 illustrates the different methods that are called during the process of adding a route to the cache.4 . the TrustFormater successively calls the createTrustValue() method in TrustManager to create new TrustValue objects.Design DSRAgent inherits from several other classes than agent packets RouteCache Agent «datatype» SRPacket * 1 MobiCacheClass +FincRoute() 1 1 * 1 1 DSRAgent 1 1 Header information «datatype» hdr_sr 1 TrustManager 1 1 * 1 1 1 1 1 1 * TrustValue ACKMonitor 1 * ACKData RouteSelector 1 TrustUpdater 1 RouteSelectorS1 RouteSelectorS2 TrustFormater TrustUpdater1 TrustUpdater2 TrustFormater1 TrustFormater2 Figure 4-7: Class diagram of the combined NS-2 implementation of DSR and the trust classes. The TrustFormater successively query the TrustManager for trust values for known nodes.Sc. When the DSRAgent discovers a route by either snooping it or receiving a route reply it calls the addRoute() methods in the route cache to add the route. 53 M. When the minimum value is found. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . After this it calls the initTrustValues() method in the trust manager to initialize trust values for nodes that are encountered for the first time.
4 . If it is. If the acknowledgement request is registered it means that it has not been removed because it has timed out and therefore the updateTrust() method in TrustManager class is called. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 54 . M.Sc. it calls the handleACKReceived() method in the ACKMonitor. This method propagates the call to the TrustUpdater class by successively calling the update()method that updates the trust. The DSRAgent examine the source header to determine if the packet is an ack.Design DSRAgent route-reply RouteCache TrustManager TrustFormater {OR} route-snooped addRoute() initNewTrustValues() f ormate() getTrustValue() createNewTrustValue() Figure 4-8: Sequence diagram describing the process for adding a new route to the route cache Figure 4-9 illustrates the methods calls that are made when an acknowledgement is received.
4 . 55 M. The RouteSelector then calls the TrustManager to get the TrustValue for the nodes on the route. To evaluate the routes the RouteCache calls the evaluatePath() method for each route to the destination. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .Sc. if thereceiv ed packet is an ack isRegisterred() updateTrust() update() setValue() () () Figure 4-9: Sequence diagram describing method calls involved when receiving an acknowledgement Figure 4-10 illustrates the method calls that are involved when a packet is being send.Design DSRAgent ACKMonitor TrustManager TrustUpdater TrustValue recv () handleACKReciev ed() The operations are only perf ormed. DSRAgent calls the findRoute() method in the route cache.
The TrustManager that stores trust values for nodes and coordinates trust related processes. that handles assignment of trust to nodes when they are encountered for the first time.Sc. The following modules has been designed: • • • • • The TrustFormater. The TrustUpdater that increases or decreases nodes trust values based on different strategies. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 56 . The RouteSelector that will select routes using a trust based evaluation. The ACKMonitor that will handle receipt and requests of acknowledgements. which has lead to the fulfillment of the main objective M-O 2. M.Design DSRAgent RouteCache RouteSelector TrustManager TrustValue send() f indRoute() ev aluatePath() getTrustValue() getValue() () () () () send() Figure 4-10: Sequence diagram describing route selection 4.4 . Further.2 Summary This chapter has covered design of modules needed to incorporate trust and trust based routing in the DSR protocol. the implementation of the DSR protocol that exists in Ns-2 has been analyzed and methods where the trust based modules interface with the existing implementation have been identified.
The OTcl scripts are used to specify node behavior such as movement and traffic generation. It offers implementations of many famous and less famous protocols. to a Medium Access Control (MAC) layer.1 Overview of Ns-2 The Ns-2 simulator consists of two major parts: • • An Otcl (Object Oriented Tcl) interpreter A C++ library Implemented protocols can be accessed and used trough OTcl scripts. etc. For the simulation performed in this project. Therefore it has been chosen to include specific details in appendices.5 . Several modifications have been made to existing DSR classes but since full credit cannot be taken this code it is not included in appendix.Implementation and tests 5 Implementation and tests This chapter covers the implementation of the designed protocol. which means that changes or extensions to protocol behavior have to be done in the C++ code. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .1. The source code for the designed trust classes are included in the appendix P.1 Introduction to the Ns-2 simulator This section gives a brief introduction to the Ns-2 simulator. The DSRAgent is connected.Sc. It is also used to specify simulation details such as simulation time. via a link layer through an interface queue. A more detailed description of the structure of the mobile node appendix I. a Constant Bit Rate (CBR) traffic generator agent has been attached to a DSRAgent. The use of OTcl has the advantage that users do not need to know anything about the actual implementation. nr of nodes in simulation. This makes it possible to start simulations with a sparse knowledge of Ns-2. The manuals and tutorials mostly focus of the OTcl part of Ns-2. The link layer is connected to an Address Resolution Protocol (ARP) that finds hardware addresses that corresponds to a packets next destination. This means that agents of different types can be attached thereby running one protocol on top of another. 57 M. However. The Ns-2 simulator has been around since 1989 and several institutions and societies has supported and contributed to its development. which means that parts related to OTcl interaction and set up is well documented. Protocols are implemented as agents that can be thought of as part of a device that is running the protocol. 5. The C++ part of Ns-2 is not similar well documented and often requires examination of the source code to get information about certain topics. The code has been implemented so it corresponds well to the design described in 4. etc. The actual implementation of the simulator and the protocols are done in C++. traffic sources. Ns-2 is an event driven simulator targeted especially at network research. all related DSR source code is included on the enclosed CD. 5. The protocol builds on a C++ implementation that is included in the Ns-2 [NS2] simulator and therefore a small introduction of the Ns-2 simulator is presented in this chapter. protocols used for simulation.
18b has been used. Because packets are created outside the DSRAgent class and pass through the class it is extremely difficult to construct packets and force events. which is necessary to perform the structural testing. Standard Template Library (STL) types such as maps and lists have been used.5 .3. The following details are included in appendices: • • • A discussion of the implementation of the acknowledgement time out mechanisms. tool that extracts information from source code and generates HTML output. 5. A description of the file format that is used when trust values are store between simulations. Searches in the Ns-2 mail archives indicate that wireless simulations on this version are not recommended [NS2-M1]. This is included in appendix O. This version was first used but after having experienced severe problems with DSR simulations it was discarded. An explanation of the implementation of malicious behavior. To construct a dynamic and scalable implementation. The test of the system can be divided in to parts: • • A structural part A functional part Due to the complexity of the system functional test have not been performed for all methods and classes. The generated HTML documentation is included on the enclosed CD. This output can then be verified. Where it has been found possible small testIt() methods have been implemented in classes. Since the implementation reflects the described design. This is included in appendix O. Since some of the test it methods create trust values they should only be called during testing. Instead version 2.Sc. Version of Ns-2 used in this project The most recent released version of Ns-2 is version 2. This provides valuable information for anyone who might continue work on the code and emphasize areas where the implementation could be improved. These methods can be called at the start of simulations and write output and expected output to the screen. The functional tests have been performed by writing and verifying output. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 58 . this section will concern some specific areas of the implementation. Furthermore the code has been commented and based on these comments HTML documentation has been created with Doxygen [Heesch].Implementation and tests Output is written during simulations to a trace file. not under actual simulations because this might influence the results.3 Tests This section explains the test of the implemented system that has been performed.2 Implementation details The classes are implemented according to the design and reflect the diagram from Figure 4-7. much similar to the Javadoc. Appendix N include a small description of this output.26.1. 5. which can be processed after simulation. M. This is included in appendix O.2. Doxygen is tool.
5 .h file.h file that can be used to control which output that is written. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . 5. 59 M.Implementation and tests Several flags have been implemented in the TrustConstants.4 Summary This chapter has presented a short introduction to the Ns-2 network simulator explaining the overall architecture of the simulator. HTML documentation of the source code have been created using Doxygen and is included on the CD. such as the acknowledgement timeout method and the file format for saved trust values have been included in appendices. The functional tests have focuses on verifying the following: • • • • That acknowledgements are send and received That routes are selected and evaluated That trust values are updated That malicious nodes drops packets The output can be generated for verification by using the VERBOSE flags in the TrustConstants. Further some of the tests of the system that have been performed have been discussed.Sc. Specific details about the implementation.
.
Since the objective of the simulations is to compare the standard DSR and DSR with trust based route selection. due to the complex nature of the ad hoc network. to elucidate their expected impact on the results. analyzed and discussed.1. with the same scenario. The scenario is generated randomly. Randomness of the scenarios that have been used for the simulations are discussed. The traffic scenarios specify which nodes should start transmitting to some destination at a specific time. it seems to be best practice to use CBR for ad hoc simulations [Broch1] [Buchegger2]. Instead of determining the effects of trust based routing by simulations other methods such as analysis could have been used. which can cause nodes to make different choices of route selection during one 61 M. Furthermore. When the destination is reached the node waits for a specified time. However. As mentioned in section 4. Several parameters have been subject to examination and the most important is accentuated. trust values are stored between simulations. using one scenario is considered satisfying.1 The randomness of simulations This section presents a discussion of the randomness of the simulations. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . to ensure that the results are not obtained by using an exaggerated positive scenario. the pause time.4. which is a very time consuming task.Sc. 6.6 . as long as one protocol does not gain advantages over the other from the scenario. simulations to determine the impact of using different scenarios are carried out. Details related to the simulation platform is included in appendix L. CBR is chosen over TCP because the protocol is much simpler which makes the results easier to analyze. but similar to the movement scenarios they are deterministic once created. The Random Waypoint model is a commonly used mobility model for simulations with ad hoc networks.Simulations and Results 6 Simulations and Results This chapter covers the simulations that have been conducted with the implemented system to meet the post objective. To simulate traffic Constant Bit Rate (CBR) traffic scenarios are used. Since the outcome of a simulation is the same when the same scenario and same number of malicious nodes is used only one simulation is conducted with the DSR protocol. Simulating random movement and traffic requires several simulations with changing scenario and traffic files. P-O 1. It is clear that the choice of which nodes should act as malicious is tightly related to the scenario. analysis verification has not been considered realistic within the time frame of this project. However. There are two main parts that has an impact of the outcome of the simulations: • • The movement scenario The traffic scenario Ns-2 provides tools to create both of these. before it starts moving again. but once it has been generated it is deterministic which means that the topology will always be the same. To simulate movement the Random Waypoint model is used. The traffic scenarios are also generated randomly. It functions in the way that nodes pick a random destination towards which they start moving along a straight line with some maximum speed. Finally some of the achieved results are presented.
However. a possible route to the acknowledgement destination is discovered.Sc. [Buchegger2]. might be as low as zero. This is calculated by Equation 6-1. which leads to an increased routing overhead. which in the end. which is the difference between the number of hops the packet took and the length of the shortest path.6 . 6. This means that the results can vary between simulations with trust based route selection. which is the ratio between the number of packets send by the application layer and the number of packets received at the application layer. M. is the primary task of the protocol. For every received acknowledgement request. Throughput.Simulations and Results simulation than during the previous simulation. Routing overhead. which is expected to lead to the use of longer routes.5. as the packet is received. Because the fortified DSR protocol uses the acknowledgement strategy described in section 4. To account for this. Studies of performance evaluations of protocols for mobile ad hoc networks indicate that the following metrics is usually used [Broch1]. Therefore it is not considered a primary objective to select a short route. which expresses the total number of routing packets that are send. non-malicious nodes return an acknowledgement. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 62 . Instead a different metric based on how well the routing strategies was to avoid using routes with malicious nodes is used.1. When a new simulation batch of five simulations is begun with a different number of malicious nodes. which means that the number of extra routing packets. all received data packets results in an acknowledgement being send. Using path optimality in the common way is not considered relevant because trust based routing is based on the avoidance of malicious nodes. ∑ received Throughput = ∑ send n 1 n 1 Equation 6-1 Path optimality. the trust values are deleted so the nodes start without any stored trust information. because it is a very common metric and because it expresses how well the protocol is at delivering packets for an overlying (application) layer. The throughput is used to compare the standard DSR and DSR fortified with different trust based routing strategies.2 Metrics There are several different metrics that can be applied to measure protocols performance against. This overhead is not determined because it was considered of less importance. five subsequent simulations are performed and the trust values are stored after each simulation. beside the acknowledgements.
To account for these deviations. As mentioned in section 6. This means that it can be stated with a 90% confidence that the mean lays within the confidence interval [Jain]. Tracefile java parser txt file manual Ns-2 simulator (C++ code) Spreadsheet manual cachestatistics java parser txtfile Figure 6-1: Data processing of simulation results Besides the trace file. that are the main result of a simulation. They are stored on a drive at DTU and can be obtained by contacting the author of this thesis. 6. DSR and DSR with trust based route selection need to be compared to make a statement whether or not they are different. A trace file from a simulation can consist of more than 100. The code for this parser in written in Java (because it offers easy IO and string handling) and is placed in appendix P. is by using confidence intervals [Jain]. methods to write data from the cache have been implemented. z1−α / 2 = (1 − α / 2) − quantile A 90% confidence interval has been used for the route selection strategies. This is used when the throughput of a route selection strategy has been compared to that of standard DSR. The processed results are stored in a spreadsheet were they can be examined further. time complexity and packet size have also been defined [Zou]. which results in deviations. they are not included on the CD. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . x = mean.3 Processing the output As mentioned the output that is generated is mainly written to the trace file. 63 M. Due to the size of the trace files. n = samplesize S = Standard deviation. statistical methods to analyze the results are used. z *s z *s Con = x − 1−α / 2 . This data that relates to the routes that are selected is written to a text file that can be preprocessed. The process of handling and processing the data is illustrated in Figure 6-1. but have not been used.000 lines and therefore a parser to process it is necessary.Sc. x + 1−α / 2 n n Where: Equation 6-2 Con = Confidence interval.Simulations and Results Other metrics such as storage complexity. An often-used method to verify that results can be used to decide that two systems are different. Confidence intervals for the mean can be calculated using Equation 6-2.6 .1 storing trust values have an impact on the results.
6 - Simulations and Results 6.4 Parameters
Several parameter that can be adjusted and thereby influence the outcome of the simulations exist. This section gives a brief presentation of the most important parameters. The parameters are presented in tables that also contain information about the value of the parameter that was used during simulations and whether this value was fixed or not. The names in the Parameter column in Table 6-1 and Table 6-2 correspond to the name the parameters have in the source code.
6.4.1 Table of standard DSR parameters
Parameter Snoop_source_routes Description Flag used to indicate if source routes should be snooped. The possible impact of snooping source routes is covered in section 3.1.3 Flag used to indicate if a node should only reply to the first route reply it receives. The expected impact of this parameter is covered in section 3.1.3 Flag used to indicate if a node should send out gratuitous replies to shorten routes. The expected impact of this parameter is covered in section 3.1.3 Flag used to indicate if a node should, when receiving a route request, reply with a route from its cache if possible. Flag used to indicate if a node should, use ring search to discover new routes. The impact of this parameter was discussed in section 3.1.1. Table 6-1: DSR parameters Fixed Yes Value False
Reply_only_to_first_ routereq Send_grat_replies
Yes
False
No
True/False
Reply_from_cache_on propagation Use_ring_search
No Yes
True/False False
Furthermore, several parameters related to route reply timeouts, buffer size, route cache size, etc. exists. These parameters have just been assigned the default value from the implementation.
6.4.2 Trust related parameters
This section covers the parameters that are related to the trust based extension. The parameters can be changed in the TrustConstants.h file. Since they have already been covered in details in chapter 4, they are only summarized here.
Parameter AVR_ACK_TIMEOUT_VAL NOACKRECEIVED ACKRECEIVED DATARECEIVED MAXTRUSTVAL S1_DEFAULTTRUSTVALUE Description Average timeout value for acknowledgment Value of no acknowledgement received event Value of acknowledgement received event Value of data packet received event Maximum trust value Default trust value when no nodes are known on the route during trust initialization. (S1 relates to trustformation strategy 1) Fixed No Yes Yes Yes Yes No Value # -1.0 1.0 0.7 1.0 #
Table 6-2: Parameters related to the trust extension.
M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
64
6 - Simulations and Results
6.4.3 Other parameters
This section summarizes some parameters related to topology, traffic rates etc. These parameters are all specified in the OTcl script, which is included in appendix P.3. Most of the values have been assigned based on a decision on what was used in the documentation and the examples that have been studied [Fall], [Greis], [NSEx].
Parameter Application traffic Radio Range Packet Size Transmission rate Pause time for nodes Maximum speed Simulation time Number of nodes Area Available bandwidth Value CBR 250 m 512 bytes 4 packets/s 60 s 1 m/s 500 s 25 1000 m × 1000 m 1 Mb/s
Table 6-3: Parameters used to specify node behavior and simulation details
The speed of 1 m/s is chosen because it corresponds to slow walking. The number of nodes in the network is set to 25, which corresponds to the assumption, pointed out in section 2.1.4, that DSR operates in a network with a diameter of 5-10 nodes. For a simulation that last 500 seconds, approximately 30000 CBR packets are send. This number is considered high enough to eliminate any deviations influence on the results. A remark needs to be tied to the value of the available bandwidth. It has not been possible to find available information on the bandwidth of the mobile wireless networks that are used for the simulations in the documentation of Ns-2 [Fall]. Searches of the ns mail archives indicate that the available bandwidth is 1 Mb/s [NS2M2]. With this bandwidth, a packet size of 512 bytes and a transmission rate of 4 packets/s, congestion of the network is not likely to occur.
6.4.4 Malicious nodes
A minimum of 0% and a maximum of 40% malicious nodes have been used. The same nodes always act as malicious, which means that if node 2 was malicious in a simulation with three malicious nodes it is also malicious in a simulation with five malicious nodes. Table 6-4 contain the nodes that were malicious during simulations. The upper row indicates which nodes were used when the total number of nodes was varied. If, for instance three malicious nodes were used, node 1,2 and 7 act as malicious. The nodes that act as malicious have been selected randomly and then kept fixed for all simulations.
Total nr of malicious Node nr 3 1 2 7 10 5 16 19 7 23 13 24 10 5
Table 6-4: The numbers of the nodes that were malicious during simulations.
65
M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
6 - Simulations and Results 6.5 Preliminary simulations
This section presents preliminary simulations that have been conducted in order to make a first fit of certain parameters. The estimation of these parameters has not been of primary interest, which means that the fitting was simply done by trying different values and choosing the one which lead to the highest throughput.
6.5.1 Estimation of initial trust
To estimate the optimal value to assign to nodes when they are first encountered some simulations are performed. Assignment of the initial trust value occurs, as described in section 4.1.1, when a new route composed of un-encountered nodes is discovered. Table 6-5 shows the parameters that were used for the simulation.
Trust related parameters Routing Strategy Average timeout value for acknowledgment Malicious nodes Value DSR parameters Value
1 0.5 7
Send_gratiuos_replies Reply_from_cache_on propagation
True True
Table 6-5: Parameters used when estimating the optimal value of initial trust.
The results from the simulation are presented on Figure 6-2. As seen, the highest throughput just above 48% is achieved when initial trust of -0.4 is used.
Estimate of best initial trust value
0.5 0.48 0.46 0.44 0.42 0.4 Intial trust values Initial trust = 0.6 Initial trust = 0.4 Initial trust = 0.2 Initial trust = 0.0 Initial trust = -0.2 Initial trust = -0.4 Initial trust = -0.6 Throughput (%)
Figure 6-2: Results from running simulations with different values of initial trust.
The purpose of the simulations was merely to estimate a value of initial trust. The results indicate that -0.4 results in the highest throughput and therefore this value is used for the remaining simulations. A value of -0.4 means that the node is initially distrusting which in a scenario with 28% malicious nodes is considered sensible.
6.5.2 Estimation of acknowledgement time out
The importance of the time that the acknowledgement monitor should wait before treating an acknowledgement as not received is discussed in section 4.1.5. To estimate a suitable value for this parameter simulation were carried out using the settings from Table 6-6.
M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
66
Simulations and Results Trust related parameters Routing Strategy Value DSR parameters Value 1 7 Send_gratiuos_replies Reply_from_cache_on propagation True True Malicious nodes Table 6-6: Parameters used when estimating acknowledgement time out value Figure 6-3 below shows the results of the simulation. For the remaining simulations an acknowledgement timeout value of 0. simulations have been performed with the parameters listed in Table 6-7. Trust related parameters Routing Strategy Malicious nodes Value DSR parameters Value 1 7 Send_gratiuos_replies Reply_from_cache_on propagation False False Table 6-7: Parameters used during simulations with different scenarios. Five different traffic scenarios and five different movement scenarios were used for the simulations. this means that for a route of length 4 a node will wait 0.Sc.3 sec Figure 6-3: Results from estimation of acknowledgement timeout value As the figure shows the highest throughput is attained with a timeout value of 0.07 seconds has been used. Estimate of timeout value 0.5. Considering that a transmit ratio of 4 packet/s is used.38 Timeout value (sec) Timeout = 0.6 .03 sec Timeout = 0. this means that in the case with a wait time of 0.42 second only 2 packets can be send by a route before a possible acknowledgement time out occurs and the routes trust values adjusted.42 seconds before the request of an acknowledgement is forsaken.07 Timeout = 0.2 sec Timeout = 0.07 seconds.44 0.42 0. 6. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . 67 M.48 0.4 0.3 Impact of using different scenarios To investigate the effect of using different scenarios.5 Throughput (%) 0. By using Equation 4-6.1 sec Timeout = 0.46 0.
The nodes positions at the start of the simulation are presented on Figure 6-5 and Figure 6-6. and the highest.7 0.1 0 Scenarios Throughput (%) Scenario 1 Scenario 2 Scenario 3 Scenario 4 Scenario 5 Figure 6-4: Results from different scenarios.5 0. To examine the cause of this significant disparity the nodes physical position during the simulation is examined. The figures are only sketches.Simulations and Results Figure 6-4 displays the results of the simulations. This means that a node as the maximum can have moved 500 m during the simulation. M. The lowest throughput of approximately 50 % is experienced with scenario 1. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 68 .6 0. which leads to a difference of more than 20 % between the best an the worst result. Comparison of different randomly generated scenarios (RS1) 0.3 0.6 . Malicious nodes are marked with red on the figure.Sc. of approximately 70% with scenario 5.4 0. As seen there is a significant difference between the results.2 0. The simulations were run for 500 seconds. The area is 1000 m2 and nodes move with a maximum speed of 1 m/s with a pause time of 60 seconds.8 0. which means that the scaling does not hold.
Being one hop away from a malicious node increases the risk of being part of a route with that node and also increases the risk of routing over that node. These considerations can also be used to explain the difference in the throughput for the two scenarios. are located in the rightmost section. It is likely that any packets that are being send across the area in some way is likely to pass over the mid section.Simulations and Results 2 14 3 5 16 18 24 17 21 15 9 1 12 4 0 7 8 13 10 23 6 20 22 11 19 Figure 6-5: Nodes position at start of simulation with scenario 1. As seen on Figure 6-5 the mid section contains three malicious nodes.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . In Figure 6-6 it can be observed that no malicious nodes are present in the mid sections in scenario 5 and furthermore. This means that the malicious nodes will most likely be on many of the routes. It is clear that the number of nodes that are only one hop away from a malicious node is larger in scenario 1 than in scenario 5 since the malicious nodes in scenario 5 is placed close to the border of the area.6 . 69 M. packets send from the right section will also be likely to reach their destination since the risk of encountering a malicious node in the mid or left section is low. which can explain the low throughput. all malicious nodes except one. This means that packets send from the leftmost section to the middle section or from the middle section to the left section is likely to be transported by routes with no malicious nodes. Further more.
6.Simulations and Results 11 12 5 13 4 23 22 2 19 20 21 1 9 6 24 17 7 0 10 15 18 16 8 14 3 Figure 6-6: Nodes position at start of simulation with scenario 5 Whether or not it is realistic with a scenario where the nodes are positioned as in scenario 5 is difficult to make a statement about.6 . Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 70 . but to take a pessimistic view of the results and consider the worst-case scenario. The throughput is compared to determine the influence of the trust based routing compared to standard DSR. These results show that an increase in throughput of approximately 20 % could have been achieved by using scenario 5.Sc. Simulations with standard DSR are performed with the same scenarios and the results presented in appendix K.6 Comparison of Route selection strategies This section presents and discuss results and simulations related to the comparison of route selection strategies. The first results were obtained by simulating with the parameters from Table 6-8. scenario 1 is used for the simulations. Trust related parameters Routing Strategy Malicious nodes Value DSR parameters Value 1 0-40 % Send_gratiuos_replies Reply_from_cache_on propagation True True Table 6-8: Parameters used for first comparison of route selection strategy 1 and standard DSR M.
This is most likely the explanation of the low throughput experienced for standard conditions. This result is somewhat surprising compared to some of the results mentioned in section 2.3 0. “would affect any on demand protocol running on top of an ARP implementation similar to that of BSD Unix” [Broch1 pp 11].6 where DSR is said to deliver as much as 95 % of the packets [Broch1]. Broch et al actually identifies a serious layer integration problem with the ARP mechanism that.4 Malicious nodes (%) RS 1 Standard DSR Confidence mean upper Confidence mean lower Figure 6-7: Comparison of route selection strategy 1 and standard DSR The first noticeable thing is that both standard DSR and route selection strategy 1 only manage to deliver around 72 % of the packets even though no malicious nodes are present in the scenario.6 . but it is considered out of scope of this assignment to implement a similar solution.1 0 0 0.5 0.Simulations and Results The values used for the DSR protocol simulations are presented in Table 6-9.2 0. This result in all packets. 71 M. However.12 0. Comparison of RS1 and standard DSR 0. The two curves following the RS1 curve are lower and upper confidence intervals. and were chosen simply because they are default. because it cannot be determined if the packets dropped by the ARP. were to be send by route with or without malicious nodes.8 0. but the last added.Sc. These values have been used for all simulations.7 Throughput (%) 0. Due to these circumstances comparison of throughput might not reveal the full effect of trust based route selection. DSR parameters Reply_only_to_first_ routerequest Send_gratiuos_replies Reply_from_cache_on propagation Use_ring_search Value False True True True Table 6-9: Parameters used for the DSR protocol The resulting throughput derived from the simulations is presented on Figure 6-7. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .1. The problem occurs when a series of packets with a next-hop destination whose link-layer address is unknown are passed to the ARP.28 0.2 0. being dropped by the ARP. as they state. The most recent version of the Ns documentation states that the ARP in Ns-2 is implemented in BSD Unix style [Fall]. Johnson et al implemented a solution to this problem.6 0.4 0.
As seen the throughput for standard DSR and route selection strategy 1 approach each other when the number of malicious nodes moves towards 40%. The figure illustrates that all routing strategies offers a higher throughput than standard DSR. Comparison of route selection strategies 0. With 28 % malicious nodes the throughput is approximately 50 % for route selection strategy 1. The maximum difference is approximately 15 % between standard DSR and route selection strategy 1 at a level of 28% of malicious nodes.28% malicious nodes is the difference markedly. Route selection strategy 4 used a threshold value of -0.3. When the number of malicious nodes increases there is a higher probability that good nodes will participate in routes with malicious and thereby be part of a route that drops a packet.28 0. but routing strategy 1.4 0. 2 and 5. As expected the throughput decreases as the number of malicious nodes in the network increases. which is a 15% improvement compared to standard DSR. with 1 as the best.4 a value of -0.Simulations and Results Further more.25 would indicate that the node had been part of a positive experience or part of a route with a node that had resulted in a positive experience. Routing strategy 4 performs worse than the other strategies when the percentage of malicious nodes increases. Figure 6-8 shows the results of simulations with the five different routing strategies that were covered in section 4.5 0.8 0. The interval beyond 40 % malicious nodes is not examined because the results clearly indicate that the effect of trust based routing decreases beyond this point.2 0.3 0. If no routes have nodes without trust values below the threshold value. the last available route will be selected due to the way the route selection is implemented.25 as threshold value because with an initial value of 0.12 0.1 0 0 0. M.1. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 72 . these observations indicate that achieving a throughput much above 70% is most likely unrealistic. Especially in the interval 20% .7 0. seems to perform slightly better than routing strategy 3. This means that good nodes can also (momentarily) be assigned low trust values.6 . which can result in a route with minimum trust value being used.25.Sc.6 0.4 Maliciuos nodes (%) RS 1 RS 2 RS 3 RS 4 RS 5 Standard DSR Throughput (%) Figure 6-8: Comparison of different routing strategies. As seen the difference between the other routing strategies are not that significant.2 0. Since routing strategy 3 and 4 are related it is expected that their performance to some extent are similar. It was chosen to apply -0.
15 and 24 does also have relatively low trust values even though they are not malicious. Node 5 is not. no good explanation can be given to why so many packets are dropped when no malicious nodes are present.7 Evolution of trust values In this section it is investigated how well the nodes identify malicious nodes. The results are similar with other routing strategies and for standard DSR.6 . This means 73 M. The trust values are calculated as an average of all the nodes trust values in each node. It has also been observed that are large number of packets are dropped internally in the node from the Sendbuffer. There are many other factors besides malicious drops that can cause packets to fail to reach their destination. It can be observed that node 15 is positioned in the mid section very close to the malicious nodes 10 and 23. Node 5. which was mentioned earlier. because it cannot be decided whether a packet where to be forwarded over a good route. be explained by studying Figure 6-5 that shows the nodes position. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . This can explain the increase in sendbuffer drops. particularly close to any malicious nodes.Sc. The figure clearly illustrates that the seven malicious nodes: 1. 2. This means that it is with some uncertainty that it. For these simulations the parameters from Table 6-10 were used. can be concluded that one strategy is better than the other. It is expected that it becomes more difficult to discover routes as the number of malicious nodes increase. They are dropped from the buffer after a certain amount of time or if the buffer is full. 10. This can. which means that it cannot be concluded with a 90% certainty that the mean lies between the interval. This is believed to be the case for nodes 15 and 24. which make it a bit more difficult to explain why it has a low trust rating. as node 15 and 24. which means that the node can be part of a negative experience for other nodes. Data and routing packets are stored in the Sendbuffer if no route is found to their destination. Therefore no further results related to comparison of throughput are presented. This is done by saving the content of each node’s TrustManager after each simulation. Trust related parameters Routing Strategy Malicious nodes Initial trust Value DSR parameters Value 1 7 0.Simulations and Results The results are however. The explanation might be sought in the fact that all nodes do not send packets to all nodes. Being close to malicious nodes increases the risk that a node is on a route with this malicious node. so close that the confidence intervals overlap. One factor is the ARP protocol. based on these results.5 Send_gratiuos_replies Reply_from_cache_on propagation True True Table 6-10: Parameters used for simulations for analyzing trust values evolution. which occurred during simulations with route selection strategy 1. to some extent. 19 and 23 all have low trust values and that the trust value has decreased for each simulation. because malicious nodes do not forward any type of packets. 7.16. Appendix M shows a graph of the drops from the Sendbuffer. However. 6. The packets drops caused by other factors makes it difficult to analyze the results. Node 24 is placed in the upper right section very close to the malicious nodes 2 and 16. Figure 6-9 shows how the nodes trust values evolve.
This might be what has caused node 5’s low trust value. 6.Sc.8 Malicious packet drops To determine the amount of packets that are dropped by malicious nodes further simulations have been carried out. For these simulations the parameters in Table 6-11 have been used. However no empirical data exist to support this hypothesis.5 1 Figure 6-9: Evolution of trust values The nodes ability to identify malicious nodes corresponds well to the results that Keane achieved with his implementation of trust based routing [Keane].6 .Simulations and Results that some nodes do not have experiences with other nodes and that nodes might not be part of good routes.5 0 Trust Value 0. M. If malicious nodes drops traffic for node 3 and node 5 is part of the route it will have its trust value decreased. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 74 . Evolution of trust values 24 23 21 19 16 18 17 14 12 10 7 5 2 1 3 0 9 6 4 13 11 8 22 20 Node nr 15 Simulation 3 Simulation 2 Simulation 1 -0. Trust related parameters Routing Strategy Value DSR parameters Value 1 7 Send_gratiuos_replies Reply_from_cache_on propagation False False Malicious nodes Table 6-11: Parameters used for simulations to measure the number of malicious drops The results from the simulations are presented in Figure 6-10. If traffic for node 3 comes from the rightmost section node 5 might be part of the route.
Due to the possibility of other causes than malicious drops. a linear relation between the throughput and the percentage of malicious drops cannot be expected.8 and therefore the same parameters from Table 6-11 were used. Based on these results a metric that expresses how well the strategy selects routes is presented. by the use of trust values. only results for 28% percent malicious nodes are M.8 that showed that fewer packets were dropped by malicious nodes when trust based routing was used.28 0. approximately 47% of the packet drops are caused by malicious nodes. To dig deeper into the trust based route selection the route selection it self is examined. This is done because it at the time of simulation was not possible to differentiate the two. The code for this parser is included in appendix P. 6. far less packet drops are caused by malicious nodes during simulations with the trust based routing strategies.Sc.9 Examining the Route Cache The results presented in section 6. of the ability of the trust based strategies to avoid malicious nodes and supports the conclusion drawn in section 6. that nodes were able to identify malicious nodes. One observation mentioned in section 3.Simulations and Results Comparison of malicious drops Malicious drops/Total dropped (%) 50 40 30 20 10 0 0 0. before a ROUTE ERROR indicating that the route is broken.7 showed. which is achieved with routing strategy 2 and 5 are approximately 17%. the node will not actively try to obtain new routes.12 0. The results where created during the same simulations that the results from section 6. These results gives a better indication. These results were supported by the results from section 6. However. The lowest result.2.7. Packets dropped by malicious nodes are both data packets and routing packets where the total number of dropped packets are only routing packets. is that once a route to a destination exist. As the figure illustrates. is received. than with standard DSR. This might result in situations where a node is forced to use a route with malicious nodes.1. Later measurements have showed that approximately 80% of the malicious drops are data packets. There are still some uncertainties related to the results because it cannot be determined how many packets that were dropped internally.6 .2 0. which results in a difference of 30%. The extent of this problem is examined by gathering information about all routes that were available to a destination and the actual route chosen. For standard DSR. The route information is written to a file at run time and preprocessed using a parser. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 75 .4 Malicious nodes (%) RS1 RS2 RS3 RS4 RS5 Standard DSR Figure 6-10: Comparison of drops caused by malicious nodes The graphs express the number of packets dropped by malicious nodes divided by the total number of packets. than the results based on throughput.1.
The results are presented in Figure 6-11. These results show that the trust based route selection has a high percentage of correct route selections.Simulations and Results presented. is used for finding routes for a packet and for finding routes to return as reply to ROUTE REQUEST’s. To examine causes for the relatively high percentage of malicious drops compared to the above results. Strategy 4 has the lowest results of 90% good routing choices. the same method. These results are presented in Figure 6-12. As mentioned is section 4. The formula expresses the percentage of correct routing choices that were made. C=∑ 1 n g *100 g + gd Equation 6-3 C: Correct choice Where g: Number of good routes selected gd: Number of good routes discarded n: number of simulations The total number of possible good routes that could be selected is the sum of the number of good routes that were selected and the number of good routes that were discarded.7. M.Sc.6 .1. These results are based on 5 simulations with each strategy (resulting in n = 5). The results show that routing strategy 1 and 2 outperforms the others with approximately 98% good routing choices. To avoid calls to findRoute() that occurs due to ROUTE REQUEST’s it is chosen to set the Reply_from_cache_on propagation flag to false. it has been investigated how often a node is forced to choose a route containing malicious nodes. findRoutes(). Route selection 100 98 96 94 92 90 88 86 Routing strategies Correct Choice RS 1 RS2 RS3 RS4 RS5 Figure 6-11: Comparison of routing strategies based on observation of the cache The y-axis of the graph shows values calculated by Equation 6-3. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 76 .
5.1. The opposite is also the case.Simulations and Results Comparison of forced choices 30 Forced maliciuos routes 25 20 15 10 5 0 Routing Strategies Figure 6-12: Graph showing how many times a route containing malicious nodes were the only choice. This corresponds to the observation described in section 3. as another scenario could lead to better result than the ones achieved with the best scenario here.6 . an even worse might exist. F =∑ 1 n fb *100 t Equation 6-4 F: Percentage of total route choices that were forced to be malicious. time did not allow further investigation of this area. Unfortunaltly. The scenarios only consisted of 25 nodes moving with a maximum speed of 1 m/s.1. In this section some of these uncertainties will be discussed. RS1 RS2 RS3 RS4 RS5 The y-value of the graph was calculated using Equation 6-4.10 Uncertainties Due to the large number of variable parameters and the generated output some uncertainties are related to the results. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . 6. As the graph shows between 18% and 27% of the routes with malicious nodes where selected because no alternative route were available. Where fb: Number of bad routes selected with no alternative t: Total number of routes selected The equation expresses how many times a route with malicious nodes was selected because no alternative route was present. The results from section 6. This result indicates that there is a bottleneck for trust based routing when only one route is available.Sc. 77 M. Even though the most pessimistic scenario was used. Fewer nodes would mean less possible routes and in such situations the trust based route selection strategies might not have the same ability avoid malicious nodes.3 shows that the deviation in the results obtained from simulating with different scenarios could be more than 20%.
6 - Simulations and Results
Using more nodes would mean more possible routes, which could give trust based routing a greater advantage. All the parameters were estimated with one scenario and it cannot be excluded that other scenarios could have resulted in different values. And at the same time it cannot be ruled out that one trust based routing strategy performs better than others in certain unforeseen situations. Only one set of parameters values were used for simulations of standard DSR and whether better or worse results could have been achieved with other values is not investigated. To minimize these uncertainties a larger number of different scenarios should be used for the simulations, which would lead to a better statistical foundation. This is however a time consuming task, since one simulation with the used simulation platform takes approximately 8 minutes, which leads to a minimum of 3 hours to perform simulations for one routing strategy. However, it can be stated with 90% certainty, that trust based routing achieves a higher throughput than DSR under the circumstances that have been simulated.
6.11 Summary
This section presents a summary of the simulations and derived results that have been discussed in chapter 6. Preliminary simulations have been carried out to determine • The impact of using different simulation scenarios. The results showed that as much as 20% deviation between the highest and lowest achieved throughput was experienced. Based on these results the worst-case scenario was used for the remaining simulations. The Acknowledgement time out value was estimated to 0.07 seconds The initial trust value was estimated to –0.4
• •
These values were used for the further simulations. Besides the preliminary simulations, several other simulations were described and the results analyzed. This has lead to the following results: • Both standard DSR and DSR with trust based routing managed to deliver 72% of the packets with no malicious nodes in the network. This result can to some extent be explained by some integration problems in the existing Ns-2 implementation of DSR. All trust based route selection strategies outperformed standard DSR when malicious nodes were present in the network. The best result was a 15% increase in throughput, which was achieved with route selection strategy 1. The throughput for strategy 2 and 5 were close to that of strategy 1, where the throughput for strategy 3 and 4 were a bit smaller.
•
M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
78
6 - Simulations and Results
• Results based on nodes trust values and on the percentage of dropped packets that were dropped by malicious nodes, clearly indicated that malicious nodes where identified. Simulations that generated output directly from the route cache were presented. A metric that describes how good a strategy was to select good routes over routes with malicious nodes were used. The results from these simulation revealed that route strategy 1 and 2 selected the best possible route 98% times. Routing strategy 4 performed the worse with a correct choice 90% of the times. From the same simulation results, knowledge about how many times a route with malicious nodes where the only possible route, where deduced. These results showed that 18%- 25% of the times a route with malicious nodes were selected no alternative route was available.
•
79
M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
This means that A increases its trust in B. in others is still under investigation. Therefore only one area for using the existing trust values for other purposes are proposed. which seams to correspond better to real life situations where trust can broken. which would decrease the routing overhead. there is nothing that can change its evaluation. the area of using trust relationships. which it will be beneficial to decrease. This results in an increased packet overhead. an it is not clear how.Future Work. described in section 2.5. uses a mechanism to detect malicious behavior and punish these. This means that malicious nodes that start to act according to protocol have their trust ratings increased. The evaluation of packet drops can be made more sophisticated. established in one content. as always been a limiting factor. trust can be transferred from one content to another. Figure 7-1 illustrates a situation that could be used to make a more sophisticated adjustment of trust values. Improvements and Perspective 7 Future Work. A first receives a packet from C that has been successfully forwarded by B. One problem with the current system is that nodes are punished collective. 7. Therefore. but also re-established.2 Using a sliding window mechanism for acknowledgements With the current implementation acknowledgements for all data packets are requested. 7.3. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .3 Derivation of knowledge by examining received packets By analyzing the received packets and their source routes much information can be derived. As the preceding chapter has indicated. the combinations of the trust related parameters and DSR parameters are almost infinitive. Improvements and Perspective Time has. Whether a perfect combination exists and is still undiscovered and uncertain. Furthermore.1 Introduction of grudging behavior The CONFIDANT protocol. The current result is that both B and 81 M. As mentioned in section 4.7 .Sc. a sliding window mechanism could be used to minimize the number of requested acknowledgement. the existing trust components could be used to apply grudging behavior to the protocol. If a node identifies another node as being malicious it starts to bear a grudge against that node. it could be used for other purposes than just route selection.5. This chapter is related to the future work that could be performed to investigate interesting areas or lead to clarifications or improvements of the existing work. a perspective of the achieved results is presented. A subsequently sends data to C but does not receive any acknowledgement.1. The grudge is put into practice as the node stops forwarding packets for the malicious node. 7. This means that good nodes can be identified as malicious if they are on routes with malicious nodes. The idea that malicious behavior has a negative consequence corresponds well to the perception that people has when other people acts malicious. and if. This leads to a strong indication that C is malicious because B just proved trustworthy. and several areas and solutions has been examined in thought but has not been put into practice. Since the architecture for forming and updating trust is designed and implemented. The trust based system that has been developed here adjust the trust that one node has in other nodes based on the events experienced. The protocol has the flaw that once a node is identified as malicious. However.
the drops can be avoided. the storage of trust information for all encountered nodes could lead to storage of a lot of stale information. Making further differentiates between the causes for packet drop. By recognizing such situations the trust updating could be refined. leave the scenario and then never again be encountered again. The trust update function from Equation 4-2 involves inflation constant. Some nodes might be encountered at some point in time. By including some time based adjustment mechanism trust values could be disposed if they had not been used within some timeframe. Therefore it is recommended that further simulations should be carried out with particular emphasis on examining where and under which circumstances packets are dropped. will make it far much easier to evaluate whether or how. meaning that until an event occurs no adjustment of the trust value occurs.7 . the throughput is not only affected by packets dropped by malicious nodes. 1 A A receives data from C forwarded by B B C 2 A subsequently send data with acknowledgement request but does not receive any acknowledgement A B C Figure 7-1: A situation where A can derive information from the received packets 7. By applying trust based routing to DSR a higher throughput was achieved when malicious nodes were present in the network.Sc. The results indicate that several packets are dropped internally in the node because no route is found. Based on the knowledge gained with DSR and the Ns-2 implementation.Future Work. which means that the trust value is automatically decreased based on this inflation constant. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 82 . Furthermore.4 Examining cause and location of packet drops As the analysis of the simulation results revealed. the ARP implementation and the methods for adding and deleting routes from the route cache should be examined. such as broken routes. but also by other factor such as the ARP implementation. but the gained knowledge could be used to only adjust C’s value. The inflation is based on events and not on time. 7. Therefore.5 Decrease trust over time Dependent on the size of the scenario. it should be investigated how nodes can request more routes when only one route with possible malicious nodes is available. The effect on throughput of trust based M. especially the packet buffer in the DSRAgent. d.6 Perspective This section present a perspective of the application of trust based routing. queue overruns or missing routes. many nodes can be encountered. 7. Improvements and Perspective C have their trust values decreased.
a perspective of trust based routing and its advantages and disadvantages were presented. Finally.7 Summary Based on observations and gained knowledge from working with DSR and Ns-2 the future improvements and areas for further investigation listed below have been proposed: • • • • Using the existing trust values to let nodes bear grudges against nodes identified as malicious. Others.7 . The mechanism for evaluating routes is more complicated and requires more computations than the one used by standard DSR.Future Work. The application of trust based routing have only focused on detection of malicious behavior that is expressed by nodes not forwarding packets and it does not cover other areas such as authentication and integrity. These approaches does however use different methods for identifying malicious nodes which presents some problems. based on situation recognition. 7. Furthermore.Watchdog mechanism have achieved better results on throughput with their methods than the results achieved with trust based routing. trust based routing makes use of acknowledgements to adjust trust values. for trust updating. Improvements and Perspective routing when no malicious node was present seems insignificant. trust values and acknowledgement information is stored during run time which requires more storage capacity of the device. which increase both routing overhead and power consumption. The increased computations will lead to a higher power consumption. Using a sliding window mechanism to limit the number of acknowledgement request. and it also means that the application of trust based routing results in a higher latency than that of standard DSR. 83 M.Sc. This means that if a higher throughput is required trust based routing can be recommended. Examining where and under which circumstances packets are dropped by nonmalicious nodes. Creating more sophisticated mechanisms. The increase in throughput does however have a cost on other areas. which can present a problem for mobile devices. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . such as the CONFIDANT and the Pathrater . such as collusion detection. Furthermore. This increases transmissions. that are not experienced with trust based routing.
.
the area of trust management systems has been investigated. The project has been carried out in the period 1st of July to 31st of December 2003 at the Department of Informatics and Mathematics Modelling. TORA. Several security mechanism. several methods for increasing throughput in ad hoc networks where malicious nodes refuse to forward packets were described. Furthermore. design and implementation of a system that incorporates trust based route selection. Further. 85 M. which can increase throughput in situations where malicious. nodes are present in the network. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . The aim of the project has been to design and implement a system that can be used for trust based routing. which are networks where nodes move around and establish connections with no fixed infrastructure. This investigation revealed that obtaining security properties such as confidentiality and integrity is possible. DTU. They have been met by covering the following: • In order to identify weaknesses and situations where trust could be incorporated to fortify the DSR protocol. in order to fortify the protocol and improve route selection. The project has focused on routing in mobile wireless ad hoc networks.8 . The preliminary objectives for the project have been to examine ad hoc routing protocols. • In main objectives have involved analysis of the DSR protocol. that can be used to establish different levels of security in ad hoc networks have been covered. • • The four ad hoc routing protocols DSDV. Thesis work that has been carried out in relation to the project ”Secure Routing in Mobile Ad Hoc Networks”.Sc. Primary objective: To apply trust based route selection to the Dynamic Source Routing (DSR) protocol. DSR and AODV have been examined with special emphasis on the DSR protocol. at the Technical University of Denmark. trust management systems and the concept of trust. security in ad hoc networks. The stated primary objective is presented below.Sc. This analysis revealed several possible vulnerabilities and identified how trust based route selection can be applied to DSR. In order to meet these objectives the following has been covered. the DSR protocol was analyzed. Trust as a concept has been studied and several frameworks that can be used to express and use trust in a formalized way has been accentuated. also difficult.Conclusion 8 Conclusion This chapter presents the key contributions and conclusion of the M. but due to the lack of an existing infra structure in the network. In order to accomplish the primary objective several areas has been examined.
the results clearly indicate that malicious nodes are identified. To investigate how well the trust based routing strategies selects routes without malicious nodes. a correct choice is made. The best results are achieved with a trust based routing strategy that used the average of the nodes on the routes trust values. which is supported by the fact that far less drops are caused by malicious nodes. The overall conclusion is that the stated aim has been fulfilled.8 . With this strategy a 15 % increase in throughput. which has been analyzed. to fortify the protocol against the presence of malicious nodes in the network. M. is selected because no alternative route is present. The results show that in as much as 98% of the times. These are listed below: • • • • • Introduction of grudging behavior Applying a sliding window mechanism for acknowledgements Deriving information from received packets Examine cause and location for packet drops further Decrease of trust over time The key contributions to the area of secure routing in ad hoc networks have been: • • Design. several simulations with the implemented systems has been carried out using the Ns-2 simulator. This mechanism is used to apply trust based route selection to the DSR protocol. The simulations have provided empirically data about the protocols behavior. was achieved. compared to standard DSR. Evaluation of trust based routing with emphasis on: Ability of the to detect malicious nodes. These results also reveals that as much as 28% of the routes that contained malicious nodes. select correct routes and causes for route selection. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 86 . The results show that DSR fortified with trust based routing achieves a higher throughput than standard DSR when malicious nodes are present in the network.Conclusion • A mechanism that establish and updates trust relationships are designed. The trust based routing is achieved by experimenting with five different routing strategies that have been designed and implemented. The designed system is implemented in C++ and the components are integrated with an existing DSR implementation in the network simulator Ns2. • To meet the post objective of analyzing the impact that trust based route selection has and identify areas of improvement. application and evaluation of different trust based routing strategies. Several proposals to improvements and areas of further investigation are suggested and described. This result corresponds well to results presented by John Keane. further simulations was conducted. Moreover.Sc.
Finally. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .Sc.Sc. it is my conclusion.Conclusion Concerning the objectives the conclusion is. 87 M. that the trust based routing mechanism can be refined which can lead to improvement of the results presented in this M. Thesis. based on the results that others have achieved with the DSR protocol and the results produced during this project. In order to achieve improvements I recommend that focus be placed in the area of requesting routes when only one route with possible malicious nodes is available in the cache.8 . that the presented contribution and work fulfills the stated objectives.
. A Bibliography [Anderson] Ross Anderson. Tang.com/trustmgt/kn. in 10th Euromicro Workshop on Parallel. David B Johnson. In Proceedings of the 7th International Security Protocols Workshop page 172-194. Frank Stajano: The Resurrecting Duckling: Security Issues for Ad Hoc Networks. Jack Lacy: Decentralized Trust Management. R. Proceedings IEEE Conference on Security and Privacy. January 2002 Sonja Buchegger. June 2002 [Bajaj] [Bertsekas1] [Blaze1] [Blaze2] [Blaze3] [Broch1] [Buchegger1] [Buchegger2] 89 M. last visited November 2003. Distributed and Network-based Processing. Joan Feigenbaum. Josh Broch. Jorjeta Jetcheva: A Performance Comparison of Multihop Wireless Ad Hoc Networking Protocols. Schwitzerland. Proceeding of the Fourth Annual ACM/IEEE International Conference on Mobile Computing and Networking (MobiCom98). K. Angelos D.Sc. 1999 Dimitri P. 1991 Matt Blaze. Bertsekas. Bagrodia. Jean-Yves Le Boudec: Nodes Bearing Grudges: Toward Routing Security. 1998. Bajaj. Prentice Hall. Yih-Chun Hu. and M.A . In Proc. Joan Feigenbaum. Keromytis: KeyNote: Trust Management for Public-key Infrastructures. Cambridge 1998 Security Protocols International Workshop. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . Takai. November 1999. Gerla: GloMoSim: A Scalable Network Simulation Environment. David A Maltz. UCLA Computer Science Department. 1998 Sonja Buchegger. Updated 1 March 2001. In Proceedings of IEEE/ACM Symposium on Mobile Ad Hoc Networking and Computing (MobiHOC). R. pages 59--63. Fairness and Robustness in Mobile Ad Hoc Networks. Oakland CA. M. Robert Gallager: Data Networks (2nd Edition). Jean-Yves Le Boudec: Performance Analysis of the CONFIDANT Protocol Cooperation Of Nodes – Fairness in Dynamic Ad-Hoc Networks.html. Lausanne. Matt Blaze.crypto. Ahuja. 1999 L. 1996 Matt Blaze: Using the KeyNote Trust Management System. Technical Report 990027.
2003 [Corson1] [Desmedt] [Fall] [Gambetta] [Gamma] [Glom] [Greis] [Guoyou1] [Heesch] [Hu] [Jain] [Johnson1] [Johnson2] M. 1994 David B Johnson.1. Johnson: Ensuring Cache Freshness in On-Demand Ad Hoc Routing Protocols. last visited 11-12-2003 Diego Gambetta.Sc. POMC’02. Richard Helm. 2002 Raj Jain : The art of computer systems performance analysis. 1995 Y Desmedt: Treshold Cryptography. 1994 Kevin Fall. Jean-Pierre Hubaux. European Transactions on Telecommunication. Kannan Varadhan: The ns Manual (formerly ns Notes and Documentation). Ralph Johnson. measurement. Josh Broch: DSR: The Dynamic Source Routing Protocol for Multi-Hop Wireless Ad Hoc Networks. David A Maltz. Journal of ACM/Baltzer Wireless Networks Vol.A . Page 217. Technical Report DSC/2001. John Vlissides (The Gang Of Four): Design Patterns: Elements of Reusable Object-Oriented Software. John Wiley and Sons Inc. and modelling. last visisted 3012-2003 Yih-Chun Hu.edu/nsnam/ns/doc/index.isi. Can we trust trust?. Anthony Ephremides: A Distributed Routing Algorithm for Mobile Wireless Networks.. last visited December 2003 Guoyou Ho: Destination-Sequenced Distance Vector (DSDV) Protocol. 1990 Erich Gamma. Dimitri van Heesch creator of Doxygen. Doxygen website :. The Dynamic Source Routing Protocol for Multi-Hop Wireless Ad Hoc Networks (DSR). Nuglets: a Virtual Currency to Stimulate Cooperation in Self-organized Mobile Ad hoc Networks.ucla. David A Maltz. simulation. Trust. Scott Corson. Addison Wesley. Blackwell.nl/~dimitri/doxygen/. 2001 M... 1994 GloMoSim website.html. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 90 .Bibliography [Buttyan] Levente Buttyan.edu/projects/GloMoSim/. last visited 1212-2003 Marc Greis: Tutorial for the simulator “ns”. Yih-Chun Hu.cs. 1 no. RFC Internet Draft. techniques for experimental design.edu/nsnam/ns/tutorial/ns. David B. 1991 David B Johnson.
Chervany: The Meaning of Trust. Park.berkeley. September. Scott Corson: A Higly Adaptive Distributed Routing Algorithm for Mobile Wireless Networks. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .isi. Carlson School of Management. Stephen Paul Marsh. Floyd: ns--Network Simulator. last visited December 2003 Vincent D. S. published in the proceedings of INFOCOM 97. 1993. Kevin Lai. last visisted 17-12-2003 Ns by Example.A . Jan Treur: Formal Analysis of Models for the Dynamics of Trust based on Experience. dissertation submitted to the university of Dublin. Germany". Department of Mathematics and Computer Science. in MILCOM '97 panel on Ad Hoc Networks.isi. Royer: Ad-hoc OnDemand Distance Vector Routing. 1997 Parsec language website:. 1994 Sergio Marti. Proceedings of the 9th European Workshop on Modelling Autonomous Agents in a Multi-Agent World : MultiAgent System Engineering ({MAAMAW}-99)". last visisted 12-12-2003 NS-2 mail archive. volume 1647.. Ph.. Jonker. Clifford Neuman: The kerberos network authentication service (V5). last visited 27-122003 Charles E.edu/pipermail/ns-users/2003May/031977. Internet Engineering Task Force. Request for Comments (Proposed Standard) RFC 1510. 2000 D.edu/projects/parsec/.J Giuli. NS-2 mail archive John Keane: Trust based Source Routing in Mobile Ad Hoc Networks.cs.cs. McCanne. 1997 [Keane] [Kohl] [Marsh] [Marti] [Mcknight] [NS2] [NS2-M1] [NS2-M2] [NSEx] [Park1] [Parsec] [Perkins1] 91 M. Perkins.html. Working paper. Mobile Computing and Networking pages 255265. Thesis. Springer-Verlag: Heidelberg. Norman L. Mary Baker: Mitigating Routing Misbehaviour in Mobile Ad Hoc Networks. pages. Elizabeth M. 2002 John Kohl.Bibliography [Jonker] Catholijn M. Harrison Mcknight. B.wpi. Formalizing Trust as a Computational Concept.221--231.edu/pipermail/ns-users/2003November/037234.edu/ns/. University of Minnesota. University of Stirling.ucla. T. Nov. 1996 S. M.html.
DTU-TRYK. Ad Hoc Networking. Chen: End-to-end Trust Starts with Recognition. Cybernetics. ISBN 0-201-72914-8. 1997 Seung Yi. IEEE Network Magazine. and Informatics--SCI. Farrell and C. November/December 1999 Xukai Zou. 2003 Robin Sharp: Principles of Protocol Design Draft Second Edition. Byrav Ramamurthy. no. Joan Feigenbaum. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 92 . Lie-Quan Lee. ISBN: 0-201-30976-9. Seigneur. Paul Resnick.Bibliography [Perkins2] [Seigneur] Charles E. Andrew Lumsdaine: The Boost Graph Library: User Guide and Reference Manual Addison-Wesley. Technical University of Denmark. Perkins. Proceedings of the First International Conference on Security in Pervasive Computing. Siek.6. 13. 2001 Lidong Zhou. chapter 8 . In IEEE Symposium on Security and Privacy. Martin Strauss: REFEREE: Trust Management for Web Applications. DTU. 2002 Jeremy G. Proceedings of the Sixth World Multiconference on Systemics. 2001 Yang-Hua Chu. Gray. Computer Networks and ISDN Systems Vol 29.A .2001 J. E. Haas: Securing Ad Hoc Networks. Spyros Magliveras: Routing Techniques in Wireless Ad Hoc Networks – Classification and Comparison. Proceedings of the 2001 ACM International Symposium on Mobile ad hoc networking & computing. S. Brian LaMacchia. Prasad Naldurg. 2002 Stephen Weeks: Understanding Trust Management Systems. Y. Addison Wesley Professional.Sc. Zygmunt J. vol. July 2002 [Sharp] [Siek1] [Weeks] [Yang] [Yi] [Zhou] [Zou] M. Robin Kravets: Security-Aware Ad Hoc Routing for Wireless Networks. Damsgaard Jensen.
such as cell phones. A specific protocol packet. A mobile device that is being held by a person or integrated into another device. A server that can be trusted to distribute cryptographic keys. The node that is the source of a message. A device. certificates etc. Mobile Wireless Ad Hoc network Node Packet Proactive/table driven protocol Reactive/On-demand Source routing Throughput Trusted server Unknown node 93 M. A routing protocol designed and aimed especially at Mobile Wireless Ad Hoc networks.B .List of used terms and definitions B List of used terms and definitions Ad Hoc network Ad hoc routing protocol Collaborative Ad hoc Network Hop-by-hop routing Initiator Known node Malicious node Message Mobile device Short for Mobile Wireless Ad Hoc network. forge packets etc.Sc. An ad hoc network where the nodes does not have any common task (other than to have their own packets forwarded) to achieve by forming the network. It can be application data or routing related data. and handle authorization. The number of received application packets divided by the number of send application packets. Routing where only the next hop towards the destination is known. Data that is being transmitted between to nodes. Routing where the sender includes the entire route to the destination in the packet header. A network made op of mobile devices that communicates via wireless communication. A node that has not been encountered during communication. A node that does not act according to protocol. A routing protocol that periodically transmits routing information. A routing protocol that only transmits routing information on demand. when a route is needed. A node that has been encountered during communication. PDA’s or laptops that operates on battery power and can be carried around. for instance by dropping packets. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .
C .Nomenclature C Nomenclature x z1−α / 2 C Con d E ES ev F fb g gd N n S T t tc TO tv Mean (1-α/2) interval Correct choice Confidence interval A constant used to express the inflation of trust A partially ordered set of experience classes for The set EN of experience sequences The experience Percentage of total route choices that were forced to be malicious Number of bad routes selected with no alternative Number of good routes selected Number of good routes discarded The set of natural numbers Sample size/ number of simulations Standard deviation A partially ordered set of trust qualifications/trust values Total number of routes selected Time out constant Total time out value The existing trust value M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 94 .
D .List of used acronyms D List of used acronyms AODV AP APER API ARP CBR DSR DSVD ER MAC NS PKI SAR STL TORA UML Ad Hoc On Demand Distance Vector Authentication Process A Peer Entity Recognition scheme Application Programmer’s Interface Address Resolution Protocol Constant Bit Rate Dynamic Source Routing Destination-Sequenced Distance Vector Entity Recognition Medium Access Control Network Simulator Public Key Infrastructure Security Aware Routing Standard Template Library Temporally Ordered Routing Algorithm Unified Modelling Language 95 M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .
List of used acronyms M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 96 .D .
..............................................50 Figure 4-6: Illustration of the flow that occurs when a packet is received .............27 Figure 2-10: Using the degree of memory based on window n for trust evolution functions....................29 Figure 3-1: If node C snoops the route from D to A...............................................................75 97 M.................11 Figure 2-5: Threshold signature...................... even though server 2 is compromised it is still possible generate a signature......................................................51 Figure 4-7: Class diagram of the combined NS-2 implementation of DSR and the trust classes.......................................................66 Figure 6-3: Results from estimation of acknowledgement timeout value ......................................................................................... ...................55 Figure 4-10: Sequence diagram describing route selection ....................... Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 ............53 Figure 4-8: Sequence diagram describing the process for adding a new route to the route cache .37 Figure 4-1: Overall architecture of the trust based extension ...............................................72 Figure 6-9: Evolution of trust values ........ Trust Constructs..................................................................63 Figure 6-2: Results from running simulations with different values of initial trust.....67 Figure 6-4: Results from different scenarios.........54 Figure 4-9: Sequence diagram describing method calls involved when receiving an acknowledgement ......................... .....................................27 Figure 2-9: Example showing how trust can be derived............................................................................................................................71 Figure 6-8: Comparison of different routing strategies.............................. .............................7 Figure 2-4: The acknowledgement mechanism works like a chain.........................................44 Figure 4-3: Estimation of total timeout value .......................36 Figure 3-2: Only forwarding the first received ROUTE REQUEST can result in undiscovered routes.....3 Figure 2-1: Node A transmits a package to node C by routing it through node B...................................................................................48 Figure 4-4: Class diagram of the trust related modules .................................................18 Figure 2-6: Comparison of Authentication Process and Entity Recognition....................................... node A can transmit to node B and B to C................5 Figure 2-2: Unidirectional links.....................................................6 Figure 2-3: A simple topology. .................................Sc. .................E ................................ . ......................69 Figure 6-6: Nodes position at start of simulation with scenario 5 ..........................................49 Figure 4-5:Class diagram of the most relevant classes used in the Ns-2 DSR implementation ................ ...............................70 Figure 6-7: Comparison of route selection strategy 1 and standard DSR...................................................... but node C cannot transmit to node B and must use a different route to A..........................56 Figure 6-1: Data processing of simulation results .................................... .................... it might never discover the two routes going through E and F........................................................42 Figure 4-2: Trust update function based ....68 Figure 6-5: Nodes position at start of simulation with scenario 1......................................74 Figure 6-10: Comparison of drops caused by malicious nodes .......1 Figure 1-2: Primary objective................................................................................................................................................26 Figure 2-8: The cooperation of y in a situation a leads...............Appendices (F – P) E Appendices (F – P) F List of figures Figure 1-1: Mobile wireless ad hoc network ...... .......................................................................................................................................................19 Figure 2-7: Relations between Mcknight et als...........
.......................................................82 Appendix Figure Appendix Figure Appendix Figure Appendix Figure Appendix Figure Appendix Figure 1: Directory structure of enclosed CD ........................76 Figure 6-12: Graph showing how many times a route containing malicious nodes were the only choice..............................List of figures Figure 6-11: Comparison of routing strategies based on observation of the cache ................. ......................77 Figure 7-1: A situation where A can derive information from the received packets...................................101 2 .......F ................... Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 98 ..............................106 5 : Two lines from a trace file.....................108 M..........................................Sc.................................................................107 6: EBNF describing the file format for saved trust information..........................................................................................................104 4 .102 3 .......................................
................................................................................65 Table 6-5: Parameters used when estimating the optimal value of initial trust.......64 Table 6-3: Parameters used to specify node behavior and simulation details ....28 Table 4-1: Evaluation of routes using the average of nodes trust value to evaluate the route ....45 Table 4-2: The values from table Table 4-1 after having had a negative experience with value –1 and route 2......................................................................Sc...................... ........................27 Table 2-4: The four sets of the framework ....................47 Table 6-1: DSR parameters................................65 Table 6-4: The numbers of the nodes that were malicious during simulations...G .................... ........... .............................................................................74 99 M.........................................................................10 Table 2-3: Temporally indexed notation in Marshs framework ........................................................46 Table 4-4: Route selection strategy 3 will detect a good node that starts to drop packets fast..........................................................46 Table 4-3: Route selection strategy 2 favor shorter routes ....................................66 Table 6-6: Parameters used when estimating acknowledgement time out value.................................................................................. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 ...........................List of tables G List of tables Table 2-1: Routing table for H4 node in the DSDV protocol.....................71 Table 6-10: Parameters used for simulations for analyzing trust values evolution.73 Table 6-11: Parameters used for simulations to measure the number of malicious drops.......................................... The Italic font are used to indicate fields used for the more advanced features of DSR................................. ...................64 Table 6-2: Parameters related to the trust extension...................................................................................67 Table 6-7: Parameters used during simulations with different scenarios............................... .70 Table 6-9: Parameters used for the DSR protocol ....................7 Table 2-2: Fields of the ROUTE REQUEST message..........67 Table 6-8: Parameters used for first comparison of route selection strategy 1 and standard DSR ...............46 Table 4-5: Example of routing strategy 5 ...................................................................................................
.....................................47 Equation 4-6............................76 Equation 6-4............................................Sc....................................48 Equation 6-1...............................................................................................................29 Equation 2-2........................................................................43 Equation 4-3........................................................................................................45 Equation 4-4...........................62 Equation 6-2...............................................................................................46 Equation 4-5........................................................................................................................................77 M.................................................................................................................................. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 100 ....................63 Equation 6-3.......................................................................................42 Equation 4-2..H ............................................................................................................................................................................................................................................................................29 Equation 4-1.........................................................................................................List of equations H List of equations Equation 2-1..........................................................
Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . The screenshot shows the folder structure of the CD. Appendix Figure 1: Directory structure of enclosed CD 101 M. A readme file with a brief description of the material is included on the CD.Content of the CD I Content of the CD Enclosed with this thesis is a CD containing different material.I .
Because simulations results have M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 102 .Structure of mobile node in Ns-2 J Structure of mobile node in Ns-2 Node Upper Layer (CBR) E DSR AGENT LL ARP MobileNode IFQ MAC PHY Radio Propagation Model CHANNEL C: Classifier LL: Link Layer IFQ: Interface Queue ARP: Address Resolution MAC: Medium Access Control PHY : Network Interface Appendix Figure 2 The structure of the mobile node implementation in Ns-2 is quite complex and is described to some details in the Ns manual [Fall].J .
An important task for the link layer is adding a MAC destination address in the MAC header of the packet. The link-layer is responsible for simulating the data link protocols. The link-layer is connected to an Address Resolution Protocol (ARP) module. The ARP is responsible for finding the hardware address that corresponds to a packets next destination.Structure of mobile node in Ns-2 turned out to be influenced by this implementation an ultra brief description is given here. the packet is inserted into the interface queue.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . 103 M. Once the hardware address of a packet's next hop is known. As seen both incoming and outgoing packets pass through the interface queue. To bind the link-layer and the MAC layer an interface queue is used. As seen the DSRAgent is only one part of the mobile node. This queue gives priority to routing packets.J .
Result from simulating DSR with different scenarios K Result from simulating DSR with different scenarios Comparison of scenarios (standard DSR) 0.5 Throughpu t(%) 0. M. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 104 .K .4 0.1 0 scenarios Scenario 1 Scenario 2 Scenario 3 Scenario 4 Scenario 5 Appendix Figure 3 Seven malicious nodes where used for these simulations.3 0.2 0.6 0.Sc.
Sc.96 was used to compile Ns-2 and the trust related extension. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . 105 M.Simulation platform L Simulation platform All simulations have been performed on a PC that used an Intel Pentium III 1150 MHz processor and had 256 MB RAM.2. This equipment was used because it was what DTU provided. Ns-2 version 2. The operating system was a Linux Red Hat version 7.18b was used for simulations and the g++ compiler version 2.L .
2 0.4 Malicious nodes (%) RS1 Appendix Figure 4 The figure presents the number of packets that are dropped internally from the sendbuffer.M .Sc.12 0. M.Sendbuffer drops during simulation with RS1 M Sendbuffer drops during simulation with RS1 SendBuffer drops .RS1 12000 SendBuffer drops 10000 8000 6000 4000 2000 0 0 0. Packets are dropped for two reasons: The buffer is full or no route is found within a specified timeframe.28 0. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 106 .
18 cbr 512 [0 0 0 0] ------. In order to register malicious drops and other self defined events the method exttrace() has been implemented and used to write to the trace file.[7:1 8:1 32 0] [6] 0 1 Appendix Figure 5 : Two lines from a trace file The first line describes a packet being received at time 7.Output from simulations N Output from simulations While a simulation is running. output is written to a trace file. The packet is a CBR packet.550313772 at agent 8.[7:1 8:1 32 8] [5] 1 1 --. To give the reader an idea of the level of details that are contained in the trace file. This trace file holds information about sent. r 7. 107 M.770552227 _7_ AGT --. The trace file also contains information about the route the packet was sent by.N . It is possible to specify the levels of trace that one wish to trace.16 cbr 556 [a2 8 7 800] ------.Sc. for instance MAC level or Routing level. the figure shows to lines from the trace file.550313772 _8_ AGT s 7. forwarded or dropped packets. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . received. IP headers and packet size. Several explanations of the trace file format exist on the Internet [Fall].
true will be returned and stored in a class variable. For easiness the content is saved in a binary format. This makes it easy to read from a programming point of view but difficult to read with human eyes. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 108 . In the current implementation the malicious nodes are hard coded in the method initEvilNodes().1 Scanning for timed out acknowledgements The method scanForOldACKs() is used to examine the map that contains all transmitted acknowledgement requests. meaning that the node is a neighbour. Therefore the EBNF for the format is presented in Appendix Figure 6 here in case anyone should want to port it to other applications. Ideally. It should be noticed that acknowledgements are required from neighbours due to the malicious behavior described in section 3. The ids are used to determine whether or not a node should act as malicious.Implementation details O Implementation details O. O. This value can be determined by Equation 4-6. This can however also result in unessesary computations. O. If a node is generating a lot of traffic it might be beneficial to run the scanForOldACKs() method in a separate thread that is activated according to the minimum timeout value determined by Equation 4-6.3 were malicious nodes does not return acknowledgements. This first happens when the command() method is called.3 File format The content of the TrustManager can be saved after each simulation by calling the save() method. Several examples exist on how to bind a method or a variable from OTcl to C++ [Fall] but none of them seems to work for mobile nodes because mobile nodes in Ns-2 consist of several different objects. <Nodes>::= {<Node>} <Node>::<Nodeid><TrustValue><NrOfExperiences>{<Experience>} <Nodeid>::= integer <TrustValue>::= double <NrOfExperiences>::= integer <Experience>::= double Appendix Figure 6: EBNF describing the file format for saved trust information M. The minimum time out value for an acknowledgement is in the case where the route is of length two.2 Malicious behavior When a DSRAgent is created from the OTcl script it is not assigned an id in its constructor. This ensures that a bad route is never picked because the trust in the nodes has not been updated due to a timed out acknowledgement. the ids for the nodes that should carry out malicious behavior should be provided through the OTcl script so compilation of C++ code could be avoided. If the id of a node is contained in an array in the method initEvilNodes().O . . These ids are integers between 0 and the number of nodes minus one.Sc. At this point this method is called every time a new acknowledgement is requested.
109 M. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . BufferedReader reader = new BufferedReader(in).//evil drop of data int ED = 0. //By Lennart Conrad //Used to parse Trace files public class DSRParser { public DSRParser(){} /* ** THe methods reads from the file given as argument ** Only the first parameter in every line is parsed.Source code P Source code P.//nr of lines int r =0.//do we read more than the first col? while(line != null) { line = reader.//forward int SF = 0.//forwarded in DSR forward int int int int AS= 0.java import java.hasMoreTokens()) { value =st.P .//ack send SO=0. //send buffer drop int f = 0.//received int EDATA = 0.//DSR send s = 0.io. if(value. if(line != null) { StringTokenizer st = new StringTokenizer(line). if(value.//others int colerrors =0. String line ="". while (st.*.//new format int Ssb = 0.equals("END"))//END of simulation { D-.StringTokenizer.nextToken().//send S = 0.readLine().//make sure we only read the first column String value =st.//drop old format int d = 0. int col = 0.Sc.//Send DSR int others = 0. import java. while (st.nextToken().//evil drop of ack int D = 0. int i = 0.//count 1 down break.the rest is ignored */ public void read(String filename) { try { FileReader in = new FileReader(filename).1 DSRParser.hasMoreTokens()) { col++.equals("D"))//old format D { //several drops can occur when the simulation ends and these are not counted D++.//evil drop int EAD = 0.util.
P - Source code
} } } else if(value.equals("d"))//new format d { d++; } else if(value.equals("EAD"))//new format d { EAD++; } else if(value.equals("EDATA")) { EDATA++; } else if(value.equals("ED")) { ED++; } else if(value.equals("Ssb")) { Ssb++; } else if(value.equals("SO"))//new format d { SO++; } else if(value.equals("AS")) { AS++; } else if(value.equals("s")) { s++; } else if(value.equals("S")) { S++; } else if(value.equals("r")) { r++; } else if(value.equals("f")) { f++; } else if(value.equals("SF")) { SF++; } else { break;//we only read the first column } //tjeck column if(col > 1) { colerrors++; } } i++;//we read 1 more line } } System.out.println("Read: "+i+" lines"); System.out.println("D (old format): "+D+" "); System.out.println("s: "+s+" "); System.out.println("r: "+r+" "); System.out.println("ED: "+ED+" "); System.out.println("EAD: "+EAD+" "); System.out.println("AS: "+AS+" ");
M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
110
P - Source code
System.out.println("Ssb: "+Ssb+" "); System.out.println("SO: "+SO+" "); System.out.println("f: "+f+" "); System.out.println("d (new format): "+d+" "); System.out.println("EDATA: "+EDATA+" ");
//total send (DSR) int ts = SO +AS+s; System.out.println("Total number of send( SO+AS+s ): "+ ts); //total dropped int td = EAD+d+D+ED+Ssb; System.out.println("Total number of dropped( EAD+d+D+ed ): "+ td); //total received System.out.println("Total number of received( r ): "+ r); //s -(r+d) System.out.println("(Send - (dropped + received )): "+ (ts(td+r)) ); //total forwarded int tf = f+SF; System.out.println("Forwarded: (f +SF) "+ (tf) ); int intr = td+r+ts+tf; System.out.println("Read: "+i+" lines, and identified: " +(intr) + "interresting tokens"); System.out.println("Column errors: "+colerrors); double percent = ((s-r)*100)/s; System.out.println("Percentage dropped of send: "+percent+" "); } catch(IOException ie) { System.out.println("Usage: DSRParser filename"); //System.out.println(ie.getMessage()); } } public static void main(String args[]) { System.out.println("DSRParser!"); String file = args[0]; DSRParser dsr = new DSRParser(); dsr.read(file); }
}
P.2 RouteParser.java
import import import import /* ** ** ** */ java.io.*; java.util.StringTokenizer; java.util.Stack; java.util.Iterator; By Lennart Conrad used to parse information written from Mobicahce. This is used to see which routes are picked, and when bad routes are picked
public class RouteParser { int NR_OF_NODES = 25;//specify according to scenario int NROFEVILNODES; cd ..//specify according to scenario Stack stack = new Stack(); public RouteParser(int a) { NROFEVILNODES = a; } /*
111
M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
P - Source code
** The methods reads from the file given as argument
** Only the first parameter in every line is parsed- the rest is ignored */ public void read(String filename) { try { FileReader in = new FileReader(filename); BufferedReader reader = new BufferedReader(in); String line =""; int linenumber = 0; int ok = 0; int notok = 0; int good_discarded = 0; int[] nodes= new int[NR_OF_NODES]; int[] discarded= new int[NR_OF_NODES]; String[] parsedline; //Arrays.fill(nodes,0); while(line != null) { line = reader.readLine(); if(line != null) { parsedline = line.split(" "); StringTokenizer st = new StringTokenizer(line); int col = 0; while (st.hasMoreTokens()) { String value =st.nextToken(); if(value.equals("NotOk:"))// { String id =st.nextToken(); int nid = Integer.parseInt(id); nodes[nid] = nodes[nid] +1; notok++; //now go through the stack and detrmine if good routes were discarded Iterator it = stack.iterator(); while(it.hasNext()) { String[] l = (String[])it.next(); boolean hasevil = false; if(!l[1].equals(id)) { break; } for(int e = 4;e <l.length;e++) { if(l[e].equals("]"))//We are done with the nodes on the route { if(!hasevil)//this route actually was OK! { discarded[nid]=discarded[nid]+1; //register who discards good routes good_discarded++; //write the one used System.out.print("Used: "); for(int kk = 0;kk<parsedline.length;kk++)//see which we didn't use
M.Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003
112
println("Good routes picked: "+ok).print("Discarded: ").println("Bad routes picked: "+notok).out.equals("Ok:"))//clear stack { stack. } } } } //clear stack stack.println(" ").k++)//see which we didn't use { System.out. } 113 M.out.println("Node: "+j+" picked: "+nodes[j]+ " bad routes and discarded: "+discarded[j]+"good ones").println("Total number of routes: "+(notok+ok)).//save it } else { break. ok++.print(l[k]+" ").length.out.Source code { System. } System. } System.println("Total number good routes that was discarded: "+good_discarded). System.k<l.println(" ").equals("Node:")) { stack.P .out. } else if(value. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .parseInt(l[e]).j++) { System. //write the one we discarded for(int k = 0.print(parsedline[kk]+" ").push(parsedline). } System.out. } else { int nodeid = Integer.out. System.Sc. for(int j = 0. if(isUsingEvil(nodeid)) { hasevil = true. } else if(value.clear(). } break.j <nodes. System.out.//we only read the first column } } } linenumber++.length. System.clear().out.out.
RouteParser parser = new RouteParser(nrofevil).1b8/ns2.# MAC type set val(ifq) Queue/DropTail/PriQueue .# channel type set val(prop) Propagation/TwoRayGround .P .# antenna model set val(ifqlen) 1000 . #The scenario (nodes movement and connections) is defined in this file and assiociated with sc #set val(sc) "/home/s973586/ns-allinone-2.println("RouteParser!").Sc. ex 1 -----------------#set val(nn) 4 .# routing protocol set val(seed) 1.//.# link layer type set val(ant) Antenna/OmniAntenna .i++) { if(id == evilnodes[i]) { return true.read(file).19. } } P.parseInt(args[0]). } } return false. int nrofevil = Integer.simulation with 4 nodes.println(ie.out.18.16.# network interface type set val(mac) Mac/802_11 .Source code } catch(IOException ie) { System. M.5}.out.# X dimension of the topography #set val(y) 1000 .24.22. i<NROFEVILNODES.1b8/tcl/ex/lcsims/4nodes/cbr-lc-4nodes".out.//max of 10 //rmnsaddr_t evilnodes[] = {14.println("Usage: RouteParser -nrofevilnodes filename").# radio-propagation model set val(netif) Phy/WirelessPhy .# number of mobilenodes #set val(x) 1000 . System.3 Otcl script #LC tcl file for trust simulations with DSR # ====================================================================== # Define options # ====================================================================== set val(chan) Channel/WirelessChannel .# interface queue type set val(ll) LL .19.# #LC remember to set nodes correct # ---------------.# max packet in ifq set val(rp) DSR .23}.11.# Y dimension of the topography #The cbr pattern is defined in this file and assiociated with cb #set val(cp) "/home/s973586/ns-allinone-2.println(nrofevil). } public static void main(String args[]) { System.out.13.getMessage()).3. parser.0 . for(int i = 0. String file = args[1]. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 114 .7.13.5}.10. //System.2. } } boolean isUsingEvil(int id) { //evil nodes id are in this array //for now they are hardcoded but they should be read from a file int evilnodes[] = {1.1b8/tcl/ex/lcsims/4nodes/scen-lc-4nodes".20.1b8/ns2.12.
0 set configured_range -1.5 Antenna/OmniAntenna set Gt_ 1.0 # ====================================================================== # Main Program # ====================================================================== #Create a simulator object set ns_ [new Simulator] #Open the trace file set tracefd [open lc-out-tdsr.1b8/ns2.# simulation time # ====================================================================== Agent/Null set sport_ Agent/Null set dport_ Agent/CBR set sport_ Agent/CBR set dport_ 0 0 0 0 # unity gain. #set chan [new $val(chan)] #Open the nam file set namtrace [open lcout.Source code #LC remember to set nodes correct # ------------------.1b8/tcl/ex/lcsims/25nodes/scen-lc-25-ex2".1b8/ns2. #set val(sc) "/home/s973586/ns-allinone-2.simulation with 25 nodes ------------------------------set val(nn) 25 .# number of mobilenodes set val(x) 1000 . #slow movement 1 m/s pause 60s set val(sc) "/home/s973586/ns-allinone-2. #set val(sc) "/home/s973586/ns-allinone-2.P . Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .1b8/tcl/ex/lcsims/25nodes/cbr-lc-25".Sc. omni-directional antennas # set up the antennas to be centered in the node and 1. #no movement #set val(sc) "/home/s973586/ns-allinone-2. #The scenario (nodes movement and connections) is defined in this file and assiociated with sc #set val(sc) "/home/s973586/ns-allinone-2. #50 connections #set val(cp) "/home/s973586/ns-allinone-2.1b8/tcl/ex/lcsims/25nodes/cbr-lc-25-50con".1b8/tcl/ex/lcsims/25nodes/scen-lc-25-nomove".nam w] $ns_ namtrace-all-wireless $namtrace 1000 1000 115 M.1b8/tcl/ex/lcsims/25nodes/scen-lc-25-p60-m1.1b8/tcl/ex/lcsims/25nodes/scen-lc-25-ex4". #set val(sc) "/home/s973586/ns-allinone-2. #set val(sc) "/home/s973586/ns-allinone-2.1b8/tcl/ex/lcsims/25nodes/scen-lc-25-ex3".1b8/ns2.0".0 Antenna/OmniAntenna set Gr_ 1.0 .1b8/ns2.1b8/ns2.1b8/ns2. set val(stop) 500.1b8/ns2.1b8/tcl/ex/lcsims/25nodes/scen-lc-25-ex5".# Y dimension of the topography #The cbr pattern is defined in this file and assiociated with cb #20 connections set val(cp) "/home/s973586/ns-allinone-2.5 meters above it Antenna/OmniAntenna set X_ 0 Antenna/OmniAntenna set Y_ 0 Antenna/OmniAntenna set Z_ 1.1b8/ns2.1b8/tcl/ex/lcsims/25nodes/scen-lc-25-ex1".0 # the above parameters result in a nominal range of 250m set nominal_range 250.0 set configured_raw_bitrate -1.# X dimension of the topography set val(y) 1000 .tr w] $ns_ trace-all $tracefd #$ns_ use-newtrace # set the new channel interface.1b8/ns2.
. must adjust it according to your scenario # The function must be called after mobility model is defined $ns_ initial_node_pos $node_($i) 35 } .Source code #Set up topography object to keep track of movement of nodes set topo [new Topography] #Provide topography object with coordinates $topo load_flatgrid $val(x) $val(y) # Create God OFF \ -macTrace OFF \ -movementTrace ON #-channel $chan #Create the specified number of mobilenodes [$val(nn)] and "attach" them #to the channel.P .." source $val(sc) # Define node initial position in nam for {set i 0} {$i < $val(nn)} {incr i} { # 15 defines the node size in nam.0 prop $val(prop) ant $val(ant)" $tracefd $tracefd $tracefd $tracefd puts "Starting Simulation.0002 "puts \"NS EXITING." source $val(cp) #Define traffic model puts "Loading scenario file. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 116 ." $ns_ run M. $ns_ halt" "Lennart Wrote this!" "M 0..Sc.0 nn $val(nn) x $val(x) y $val(y) rp $val(rp)" "M 0.0 sc $val(sc) cp $val(cp) seed $val(seed)" "M 0....# disable random motion #Tell nodes when the simulation ends for {set i 0} {$i < $val(nn) } {incr i} { $ns_ at $val(stop).. } $ns_ at puts puts puts puts $val(stop)..\" .0 "$node_($i) reset". for {set i 0} {$i < $val(nn) } {incr i} { puts "i: $i" set node_($i) [$ns_ node] $node_($i) random-motion 0 } #Define node movement model puts "Loading connection pattern.
void initNewTrustValues(Path& replyroute.//holds trust info for all known nodes nsaddr_t name. double).int route_len. private: map<nsaddr_t. //Do Not forget the trailing semi-colon 117 M.//for writing //(de) serializing bool load(int id). double event).//for reading on start up bool openWFile(int id). nsaddr_t src). TrustManager(nsaddr_t id). double getTrustValueForNode(const nsaddr_t nid). //IO void toPrint(void). nsaddr_t getId().//for loading bool save(int id). void updateTrustForNodes(Path& path. //TrustUpdater TrustUpdater* getTrustUpdater(). //formate trust double formate(). //for reading TrustUpdater* trustupdater.h and .//used when nodes are first encountered FILE* fdata. bool writeToFile(void). }. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .nsaddr_t src).h" //NS2 includes #include "path. 12-10-2003 ** This class is used to store trustinformation about all known nodes */ class TrustFormater. void setTrustUpdater(TrustUpdater*).h" /* ** By Lennart Conrad. void setTrustFormater(TrustFormater*).//close file after read void closeWFile(void).//the calcultare for updating trust TrustFormater* trustformater.//for writing ifstream infile. //TrustFormation TrustFormater* getTrustFormater().P . void closeRFile(void). class TrustManager { public: //constructor TrustManager(). double event). //update trust //double update(TrustValue*).double event).h" #include "TrustFormater.cc) #ifndef TRUSTMANAGER_H #define TRUSTMANAGER_H #include <fstream.//setter for id for this manager bool isKnown(nsaddr_t).//close file after write bool openRFile(int id).Sc. void updateTrust(nsaddr_t nid.h" #include "TrustConstants.4 TrustManager (.//id for this node ofstream outfile. TrustValue*). void initNewTrustValues(nsaddr_t replyroute[].TrustValue*>& getTrustValues(void). void setId(nsaddr_t n).//create a TM for the node with id //methods map<nsaddr_t.TrustValue*> tvalues. void addTrustValue(nsaddr_t.//for one //for all known in route void updateTrustForKnownNodes(list<nsaddr_t>&.h> #include <string> #include <map> #include "TrustValue.Source code P.h" #include "TrustUpdater.//for saving //testing void testIO(). void createTrustValue(nsaddr_t.//writes some testinfo to file void testIt(). bool readFromFile(void). TrustValue* getTrustValue(const nsaddr_t nid).
this->updateTrust(*i.//max of 10 //rmnsaddr_t evilnodes[] = {14.2.dump()<<endl.13. ++i) { //cerr <<"updating trust TM"<<endl.13. } //updates trust for all known nodes in the path according to the eventtype void TrustManager::updateTrustForKnownNodes(list<nsaddr_t>& known_route.12. event). j<NROFEVILNODES.j++) { if(id == evilnodes[j] && i <path.20. } //getter for name (id) nsaddr_t TrustManager::getId() { return this->name.11. for(int j = 0.P .5}. i++) { //cerr <<"updating trust TM"<<endl. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 118 .18.19.16. } } this->updateTrust(id. for(i=known_route.22.end(). i <path. double event) { //just go through and call updatetrust for the nodes we know //NOTE ! it is important that i = 1 because evil nodes send // data packets as well for(int i=1.10.3. } if(TRUSTVALUEUPDATEVERBOSE)//testing cout <<"Node: "<<this->name<<"Finished updating for route: "<<path.length() . } //updates trust for all nodes in the path according to the eventtype void TrustManager::updateTrustForNodes(Path& path.length()-1) { //cerr<< "We are updating trust for a evil node:"<<id <<endl.Source code #endif //TRUSTMANAGER_H #include #include #include #include "TrustManager. event). } //updates trust for the node with id according to the eventtype void TrustManager::updateTrust(nsaddr_t nid.getNSAddr_t().24.19. double event) { M.23.7. } //setter for id void TrustManager::setId(nsaddr_t n) { this->name = n.begin().5}.Sc. double event) { //just go through and call updatetrust for the nodes we know list<nsaddr_t>::iterator i. i != known_route. } //cerr <<"Finished updating trust TM"<<endl. //evil nodes id are in this array //for now they are hardcoded but they should be read from a file nsaddr_t evilnodes[] = {1. int id = path[i].h" <string> <iostream> <sstream> TrustManager::TrustManager() {} TrustManager::TrustManager(nsaddr_t n) { this->name = n.
.:"<<nid <<endl.0.. if(nid == this->name)//Always assign max trust to ourselves { double res = this->trustupdater->update(getTrustValue(nid).. } else { double res = this->trustupdater->update(getTrustValue(nid).. 119 M. } //TrustFormater setter void TrustManager::setTrustFormater(TrustFormater* tm) { this->trustformater = tm.. } //returns all trustvalues map<nsaddr_t... //this->update(getTrustValue(nid).. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .. } else { return tvalues[nid]->getValue(). 1.Source code //get the new value from the trustupdater if(isKnown(nid)) { if(TRUSTVALUEUPDATEVERBOSE)//testing cerr << "Node" << this->name <<"is updating trust for..TrustValue*>::iterator it.P . event).... return 0. this->createTrustValue(nid.Sc. } //TrustUpdater getter TrustUpdater* TrustManager::getTrustUpdater() { return this->trustupdater. event).. //establis trust with some standard value //cerr << "Node" << this->name <<"is establishing trust for node:"<<nid <<endl. } //TrustUpdater setter void TrustManager::setTrustUpdater(TrustUpdater* tu) { this->trustupdater = tu. } } //Trustformater getter TrustFormater* TrustManager::getTrustFormater() { return this->trustformater. } else { //cerr << "a node was not known in TrustManager::updateTrust" << endl.. cerr << "Node: "<<this->name << " does not have any trust value for "<<nid<<endl. } //cerr << "REs "<<res <<endl....0)..TrustValue*>& TrustManager::getTrustValues() { return tvalues.. cerr << "valie of: S1_DEFAULTTRUSTVALUE" <<S1_DEFAULTTRUSTVALUE<<endl. } //return ( (double)rand()/(double)RAND_MAX+1 ).end()) { cerr <<"Error gettrustValueForNode()"<<endl.. if(!isKnown(nid) ) //if(it == tvalues..S1_DEFAULTTRUSTVALUE). } //return the value from trustvalue for a node with id = nid double TrustManager::getTrustValueForNode(const nsaddr_t nid) { //LC This should not happen but i does! map<nsaddr_t.
//we have to create it! //cerr << "But now it has the value " << tvalues[nid]->getValue()<<endl. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 120 .Sc.size(). } //adds a the trutsvalue tval wwith the key id.begin().str() <<" opened for writing by save" << endl.Source code } //return the trustvalue for a node with id = nid TrustValue* TrustManager::getTrustValue(const nsaddr_t nid) { //LC This should not happen but i does! //map<nsaddr_t. //go through the map and let tvalues store them selves map<nsaddr_t." << endl.. if(!isKnown(nid) ) //it == tvalues.1. } } //prints the cotent of the Trustmanager void TrustManager::toPrint() { map<nsaddr_t. fdata = fopen(ss..c_str().tval).dtmf". double tval) { if(!isKnown(id)) { tvalues[id] = new TrustValue(id..P . //cerr << "Node: "<<this->name << " does not have any trust value for "<<nid<<endl. //did it open ok int nroftrustdata. //create file name ss << id << ".TrustValue*>::iterator it. if it allredy exists it is deleted cout << "Opening file: " << ss. } //LC : note could be a possible memory leak since the arg TrustValue* is not deleted //if the value allready exist } //creates and adds a new TrustValue to this trustmanager void TrustManager::createTrustValue(nsaddr_t id.sizeof(nroftrustdata). if(fdata == NULL)//error on opening file { cout << "Error on opening file: " << ss... return false.it!= tvalues...TrustValue*>::iterator it.end()... //this happens when node X gets a route with node X (itself)therefore we assign a high trustvalue tvalues[nid] = new TrustValue(nid. } } //Saves all data so it can be loaded again later bool TrustManager::save(nsaddr_t id) { ostringstream ss.TrustValue*>::iterator it..fdata). cout << "and the number was" << ss..str() <<" for writing. } else//ok { cout << "File: " << ss.9)."w").end()) { //cerr <<"ERROR getTrustValue "<<endl.str().it++) { (it->second)->toPrint().. for(it = tvalues. TrustValue* tval) { if(!isKnown(id)) { tvalues[id] = tval.dtmf in save()" << endl. } return tvalues[nid]. //open the file. nroftrustdata = tvalues... cout << "The TrustManager contains:\n" << endl.WE NEED IT FOR LOADING! void TrustManager::addTrustValue(nsaddr_t id. //go through the manager an let the TrustValues handle IO M.str() << endl.str() <<".0.//nr of stored trustvalues fwrite(&nroftrustdata.
.it++) { (it->second)->save(fdata). //go through the map and let tvalues store them selves //go through the manager an let the TrustValues handle IO for(int i =0.tmf" << endl... tmf file for the node to write trust info to bool TrustManager::openWFile(nsaddr_t id) { ostringstream ss. } } fclose(fdata)...fdata).. //open the file. //test by printing content //this->toPrint().c_str().str() << endl.it!=tvalues. outfile. //did it open ok if(!outfile.str() <<" opened for writing" << endl.P .. //open the file.. if it allredy exists it is deleted cout << "Opening file: " << ss.Source code for(it = tvalues.str() <<" for loading.str() << endl. //create file name ss << id << ".str() <<" for writing.1...c_str(). return false. return true. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . //let it load it self v->load(fdata). } //open a . } else//ok { cout << "File: " << ss.sizeof(int)... int nroftrustdata.. v).ios::out | ios::app | ios::trunc)..dtmf in TrustManager::load()" << endl. //did it open ok if(fdata == NULL)//error on opening file { cout << "Error on opening file: " << ss.str(). fread(&nroftrustdata. return true.i < nroftrustdata.. return true. } cout << "File: " << ss. TrustManager::load()" << endl..i++) { TrustValue* v = new TrustValue()... //store it addTrustValue(v->getId()..str() <<" opened for loading by TrustManager::load()" << endl. if it allredy exists it is deleted cout << "Opening file: " << ss. } } fclose(fdata).... } //load trustvalues bool TrustManager::load(nsaddr_t id) { ostringstream ss. } 121 M. //create file name ss << id << "." << endl.str() <<"..Sc.str() <<".is_open()) { cout << "Error on opening file: " << ss....dtmf".tmf". cout << "and the number was" << ss. return false..open(ss."r").str().begin(). cout << "Saved ok with"<< nroftrustdata <<"nodes saved" << endl." << endl. cout << "and the number was" << ss..//nr of stored trustvalues cout << "Load contains: " << nroftrustdata <<" Trustvalues.end(). fdata = fopen(ss.
close(). outfile << "Trustmanager for Node:" << name <<"\n".TrustValue*>::iterator it.P .eof()) { infile. } bool TrustManager::readFromFile() { //better tjeck that it is open char buf[100]. //go through the manager an let the TrustValues handle IO for(it = tvalues.tmf opened ok!" << endl.it!=tvalues.remember to call closeWFile() ! } return true.Sc. //create file name ss << id << ". return false. infile.10). } cout << "Infile" << id << ".is_open()) { cout << "Error: file:" << id << ". tmf file for the node to Read trust info from bool TrustManager::openRFile(nsaddr_t id) { ostringstream ss. } } return true.close().end(). Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 122 .begin().Source code //open a .str().tmf could not be opened" << endl.read(buf. return true. if(infile. //read everything if(!infile. cout << "Read from infile"<< buf <<endl.is_open()) { cerr << "Out file is not opened" << endl.it++) { (it->second)->writeToFile(outfile). } //initialises trust values for unkown nodes by examining the entire path //call with Path M.open(ss. } //Writes the content of the trust manager to a file bool TrustManager::writeToFile() { //we better check that it's opened if(!outfile. //open the file ifstream infile. } //the file is NOT closed .is_open()) { cout << "File not opened" << endl. } else { map<nsaddr_t. //char buf[100]. } else { //read everything while(!infile.c_str()). } //closes the outfile void TrustManager::closeWFile() { outfile. return false. } //closes the in file void TrustManager::closeRFile() { infile.tmf".
//if id doesn't exist it returns iterator to the end return(!(it == tvalues.P .// we need this declaration here 123 M.is_open()) { cerr << "Out file is not opened (testIO())" << endl.. this->trustformater->initNewTrustValues(replyroute.route_len. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . } else { cout << "Trustmanager for Node:" << outfile << "Trustmanager for Node:" outfile << "Trustmanager for Node:" outfile << "Trustmanager for Node:" closeWFile()." <<endl.. << name <<"created!\n". it = tvalues..h" #include "TrustConstants. this->trustformater->initNewTrustValues(replyroute..int route_len. nsaddr_t src) { //cout << "TrustManager::initNewTrustValues. << name <<"created!\n". //cout << "TrustManager::initNewTrustValues Survided" <<endl..h and .. } //initialises trust values for unkown nodes by examining the entire path // call with array void TrustManager::initNewTrustValues(nsaddr_t replyroute[]. } //for internal testing void TrustManager::testIt() { cout << "Trustmanager testIt() called" << endl. } } name <<"created!\n" << endl...Source code void TrustManager::initNewTrustValues(Path& replyroute....5 TrustFormater (.." <<endl.find(id).h" #include "TrustManager..Sc.. << name <<"created!\n"... //cout << "TrustManager::initNewTrustValues Survided" <<endl.... } //does this entry exist -> the node is known bool TrustManager::isKnown(nsaddr_t id) { map<nsaddr_t.src). implementation are found in TrustFormater.nsaddr_t src) { //cout << "TrustManager::initNewTrustValues.. } //writes some testinfo to file void TrustManager::testIO() { //we better check that it's opened if(!outfile.h" /* ** ** ** ** */ By Lennart Conrad 12-10-2003 The TrustFormater class is an abstract class.end())).cc) #ifndef TRUSTFORMATER_H #define TRUSTFORMATER_H #include "TrustValue.src).TrustValue*>::iterator it.cpp class TrustManager. P.
Sc.const nsaddr_t src) = 0.strategy 1 class TrustFormaterS1 : public TrustFormater { public: //Constructor TrustFormaterS1(). }. //implementing class . const nsaddr_t src) = 0 .P . //methods //first argument is the trustValue that needs updating and holds data. } //initializes trust for unknown nodes from known nodes (Call with nsaddr_t[]) void TrustFormaterS1::initNewTrustValues(const nsaddr_t replyroute[].const int route_len.h" #include "TrustValue. void initNewTrustValues(const nsaddr_t replyroute[]. secodn is the experience value //virtual double update(TrustValue&.h" //----------. const nsaddr_t src).const nsaddr_t src). //fields }.const int route_len.const nsaddr_t src). TrustFormaterS2(TrustManager*). TrustFormaterS1(TrustManager*). //methods void initNewTrustValues(const Path& replyroute. //methods void initNewTrustValues(const Path& replyroute. //This is how is done: //1 go through the nodes and indentify the known ones -> //put the unknown in one list and the known in anoter //2 find min value of known nodes trust values M.const int route_len.strategy 2 class TrustFormaterS2 : public TrustFormater { public: //Constructor TrustFormaterS2(). const nsaddr_t src) { //cout << "TrustFormater Called" << endl. double)=0. //fields }.const int route_len.h" #include "TrustConstants. void initNewTrustValues(const nsaddr_t replyroute[].//abstract methods virtual void initNewTrustValues(const Path& replyroute.Strategy 1 -----------------------TrustFormaterS1::TrustFormaterS1() {} //we need to be able to reference trustmanager to getinfo on known nodes TrustFormaterS1::TrustFormaterS1(TrustManager* tm) { this->trustmanager = tm. #endif //TRUSTFORMATER_H #include "TrustFormater. //implementing class . const nsaddr_t src). //fields TrustManager* trustmanager. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 124 . virtual void initNewTrustValues(const nsaddr_t replyroute[].Source code class TrustFormater { public: //Constructor //TrustFormater(). const nsaddr_t src) {} //initializes trust for unknown nodes from known nodes (Call with Path) void TrustFormaterS1::initNewTrustValues(const Path& replyroute.
min).const nsaddr_t src) { //cout << "TrustFormater Called" << endl. for(it = unknown.i++)//1 { //cout << "loop 1" << endl. it != unknown. known.end(). 125 M. } //-----------.push_front(id).assign the average trust of the route*/ void TrustFormaterS2::initNewTrustValues(const Path& replyroute.length().end().begin(). double ghost = 1000. //if we dont know anybody it should be set to some standard val } //3 now create new Trustvalues //list<nsaddr_t>::iterator uit. //1 find known/unknown for(int i =0.i < replyroute. find minimum tval of know nodes list<nsaddr_t>::iterator it. min = S1_DEFAULTTRUSTVALUE. //cout << "loop 4" << endl. } else//we don't know it { unknown. const nsaddr_t src) {} //initializes trust for unknown nodes from known nodes (Call with Path) /* strategy 2 .Strategy 2 -----------------------TrustFormaterS2::TrustFormaterS2() {} TrustFormaterS2::TrustFormaterS2(TrustManager* tm) { this->trustmanager = tm. //cout << "DId 2 list" << endl.//A very high value double min = ghost.push_front(id). } //cout << "FINISHED DOING TrustFormation Part 3" << endl.const int route_len.0. } } //cout << "FINISHED DOING TrustFormation Part 2" << endl. for(it = known. it != known. } //initializes trust for unknown nodes from known nodes (Call with nsaddr_t[]) void TrustFormaterS2::initNewTrustValues(const nsaddr_t replyroute[].Source code //3 create new Trustvalues with the minimum value list<nsaddr_t> known.P . it++) { trustmanager->createTrustValue(*it.getNSAddr_t(). if(trustmanager->getTrustValue(nid)->getValue() < min) { min = trustmanager->getTrustValue(nid)->getValue(). //2. list<nsaddr_t> unknown. if(trustmanager->isKnown(id))//we know it { //cout << "loop 3" << endl. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .Sc. } } //cout << "FINISHED DOING TrustFormation Part 1" << endl. //cout << "loop 2" << endl.begin(). //tjeck if min was ever set if(min == ghost) { //cerr << "valie of: S1_DEFAULTTRUSTVALUE in trustformater" <<S1_DEFAULTTRUSTVALUE<<endl. nsaddr_t id = replyroute[i]. it++) { int nid = *it.
begin(). } else//we don't know it { unknown. for(it = unknown. //cout << "DId 2 list" << endl.i < replyroute. average). //1 find known/unknown for(int i =0. it != unknown. //cout << "loop 2" << endl.h" /* ** By Lennart Conrad 12-10-2003 ** The TrustUpdater class is an abstract class.6 TrustUpdater (. } //cout << "FINISHED DOING TrustFormation Part 2" << endl. it != known. double ghost = 1000.P . } //cout << "FINISHED DOING TrustFormation Part 3" << endl. find minimum tval of know nodes list<nsaddr_t>::iterator it.cpp ** */ class TrustUpdater { M. for(it = known. list<nsaddr_t> unknown.size(). } P.push_front(id). ** Subclasses implementing different strategies should impmement the calculate() methods ** implementation are found in TrustUpdater. //cout << "loop 4" << endl.h and .//A very high value double average = ghost.i++)//1 { //cout << "loop 1" << endl.Sc. //tjeck if min was ever set if( average == ghost) { //cerr << "valie of: S2_DEFAULTTRUSTVALUE in trustformater" <<S2_DEFAULTTRUSTVALUE<<endl. } } //cout << "FINISHED DOING TrustFormation Part 1" << endl. known. //if we dont know anybody it should be set to some standard val } else { average = average/known. it++) { int nid = *it. nsaddr_t id = replyroute[i].push_front(id).getNSAddr_t().cc) #ifndef TRUSTUPDATER_H #define TRUSTUPDATER_H #include "TrustValue. //2. average = average + trustmanager->getTrustValue(nid)->getValue(). it++) { trustmanager->createTrustValue(*it.length().Source code //This is how is done: //1 go through the nodes and indentify the known ones -> //put the unknown in one list and the known in anoter //2 find min value of known nodes trust values //3 create new Trustvalues with the minimum value list<nsaddr_t> known.end().end(). } //3 now create new Trustvalues //list<nsaddr_t>::iterator uit.0. if(trustmanager->isKnown(id))//we know it { //cout << "loop 3" << endl.begin(). Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 126 . average = S2_DEFAULTTRUSTVALUE.
i++) { if(tval->getId() == evilnodes[i]) { cerr<< "We are updating trust for a evil node!" <<endl. tval->addExperience(exp).5}.dpos)*exp).11. #endif //TRUSTUPDATER_H #include "TrustUpdater.7.20. for(int i = 0.18.16. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . tval->addExperience(exp).0 .dpos)*exp).9. //implementing class . /*LC debug/analysis to see if we are giving trust to evil nodes*/ //evil nodes id are in this array //for now they are hardcoded but they should be read from a file /*nsaddr_t evilnodes[] = {1. i<NROFEVILNODES. //methods double update(TrustValue*.5}. //assign the new value tval->setValue(ret). double)=0. //methods double update(TrustValue*.13.9. } } */ } else//NOACKRECEIVED 127 M. double exp) { //parameters double dpos = 0.13. }. } else if(exp == DATAPACKETRECEIVED)// { ret = (dpos*tval->getValue() + (1.h" TrustUpdaterS1::TrustUpdaterS1() {} TrustUpdaterS2::TrustUpdaterS2() {} double TrustUpdaterS1::update(TrustValue* tval. //cerr << "Trust increased: " << ret << endl.h" #include "TrustValue. //update trustvalue + nr of experiences if(exp == ACKRECEIVED )//positive experineces { ret = (dpos*tval->getValue() + (1. //implementing class . }.//abstract methods }.Source code public: //Constructor //TrustUpdater().3. //negative inflation double ret. //methods //first argument is the trustValue that needs updating and holds data. //assign the new value tval->setValue(ret).double).P .//max of 10 //rmnsaddr_t evilnodes[] = {14.12.10. //positive inflation double dneg = 0.23.19.strategy 2 class TrustUpdaterS2 : public TrustUpdater { public: //Constructor TrustUpdaterS2().Sc.19.double).strategy 1 class TrustUpdaterS1 : public TrustUpdater { public: //Constructor TrustUpdaterS1(). secodn is the experience value virtual double update(TrustValue*.24.22.2. //cerr << "Trust increased: " << ret << endl.0 .
tval->addExperience(exp).dpos)*exp). double retexp.dpos)*exp). ret = (ret + retexp)/2.//if somebody wants to see the updated value } P.Source code { //cout << "tval->getValue():"<< tval->getValue() << endl. //assign the new value tval->setValue(ret). ret = (ret + retexp)/2.0.h" using namespace std.0 . retexp = tval->getAverageOfExperiences().0.7 ACKMonitor (. //positive inflation double dneg = 0.cc) #ifndef ACKMONITOR_H #define ACKMONITOR_H #include <map> #include <list> #include "TrustManager.dneg)*exp).h" #include <scheduler. tval->addExperience(exp).0 . /* ** Created by Lennart Conrad 23-10-2003 ** These classes are used to handle acknowledgments ** in the trust extensions to DSR ** */ //class used to store data about a send ACK class ACKData { M. retexp = tval->getAverageOfExperiences().0. } else//NOACKRECEIVED { //cout << "tval->getValue():"<< tval->getValue() << endl. tval->setValue(ret). //assign the new value tval->setValue(ret). Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 128 . double exp) { //parameters double dpos = 0. retexp = tval->getAverageOfExperiences(). tval->addExperience(exp). //cerr << "Trust decreased: " << ret << endl. } return ret.9.9. ret = (ret + retexp)/2.//if somebody wants to see the updated value } double TrustUpdaterS2::update(TrustValue* tval.dneg)*exp).h and .0 . ret = (dneg*tval->getValue() + (1. } return ret. tval->setValue(ret). //cerr << "Trust decreased: " << ret << endl. //negative inflation double ret. tval->addExperience(exp).Sc. //update trustvalue + nr of experiences if(exp == ACKRECEIVED )//positive experineces { ret = (dpos*tval->getValue() + (1.0 . ret = (dneg*tval->getValue() + (1. //cerr << "Trust increased: " << ret << endl. //cerr << "Trust increased: " << ret << endl.P .h" //NS2 includes #include "path.h> #include "TrustConstants. } else if(exp == DATAPACKETRECEIVED)// { ret = (dpos*tval->getValue() + (1.
ACKData*> acks. int ack_to_late. ACKData(double ackid. Time send_at). int ack_rec_ok.int routel. class ACKMonitor { public: //Constructor ACKMonitor().h" using namespace std.nsaddr_t route[]. ACKMonitor(TrustManager*). void addACK(double ackid. } }.P .//time we send this ACK //methods inline double getACKId() { return ackid. void handleACKReceived(double ackid. void setTrustManager(TrustManager*). int ack_add. Time send_at).h" #include <scheduler. void testIt().h> #include "TrustConstants.Source code public: ACKData(). } inline Time getTime() { return sendat. //Do Not forget the trailing semi-colon #endif //ACKMONITOR_H #ifndef ACKMONITOR_H #define ACKMONITOR_H #include <map> #include <list> #include "TrustManager.nsaddr_t route[]. void scanForOldACKs().Sc. //Destructor ~ACKMonitor(). /* ** Created by Lennart Conrad 23-10-2003 ** These classes are used to handle acknowledgments ** in the trust extensions to DSR ** */ //class used to store data about a send ACK class ACKData { public: ACKData(). //testing //these are just for statistics on how many acks are recieved/send etc int ack_time_out.int routel. //fields private: map<double. //Returns True if we have the ACK reqisterred bool isACKRegistered(double ackid).nsaddr_t route[]. int dup_add_ack. Time send_at). ACKData(double ackid. nsaddr_t from).int routelen. list<nsaddr_t> route. //for testing void terminate().//all ids on the route Time sendat. //fields double ackid.size(). }.h" //NS2 includes #include "path.int rl. ACKData* getACK(double ackid).nsaddr_t returnroute[].//holds all ACKData TrustManager* trust_manager. //fields 129 M. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . void removeACK(double id). Time rec_at. } inline int getLength() {return route.
Sc. void setTrustManager(TrustManager*).h and . int ack_add. Time send_at). class ACKMonitor { public: //Constructor ACKMonitor().cc) #ifndef ROUTESELECTOR_H #define ROUTESELECTOR_H #include "TrustManager.h> using namespace std.//holds all ACKData TrustManager* trust_manager. }.ACKData*> acks.P . void virtual setTrustManager(TrustManager* tm)=0. } inline int getLength() {return route.nsaddr_t route[]. ACKMonitor(TrustManager*). /* ** Created by Lennart Conrad 30-10-2003 ** These classes are used to handle route selection ** in the trust extensions to DSR ** */ class RouteSelector { public: TrustManager* trust_manager. int ack_to_late. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 130 .h" //NS2 includes #include "path. void addACK(double ackid. void removeACK(double id). void testIt(). //testing //these are just for statistics on how many acks are recieved/send etc int ack_time_out. void scanForOldACKs(). } }. //Returns True if we have the ACK reqisterred bool isACKRegistered(double ackid). M. } inline Time getTime() { return sendat. nsaddr_t from). //fields private: map<double.//time we send this ACK //methods inline double getACKId() { return ackid. int dup_add_ack. ACKData* getACK(double ackid). Time rec_at. int ack_rec_ok.size(). //methods double virtual evaluateRoute(Path&. void virtual testIt()=0.h" //#include <scheduler. //Do Not forget the trailing semi-colon #endif //ACKMONITOR_H P.8 RouteSelector (. //Destructor ~ACKMonitor().nsaddr_t returnroute[]. void handleACKReceived(double ackid.int rl.int&) = 0. //for testing void terminate().//all ids on the route Time sendat.int routelen. list<nsaddr_t> route.Source code double ackid.
}. void testIt(). RouteSelectorS5(TrustManager*). void setTrustManager(TrustManager* tm). Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .int&).Source code }. void setTrustManager(TrustManager* tm).int&). void setTrustManager(TrustManager* tm). void setTrustManager(TrustManager* tm). //methods double evaluateRoute(Path&. class RouteSelectorS3 : public RouteSelector { public: //Constructor RouteSelectorS3(). }.P . RouteSelectorS2(TrustManager*). void testIt().h> 131 M. }. void testIt(). //methods double evaluateRoute(Path&. void testIt(). //Destructor ~RouteSelectorS1().int&). //Destructor ~RouteSelectorS3(). RouteSelectorS3(TrustManager*). //methods double evaluateRoute(Path&.Sc.int&). void testIt(). class RouteSelectorS4 : public RouteSelector { public: //Constructor RouteSelectorS4(). void setTrustManager(TrustManager* tm). RouteSelectorS4(TrustManager*).int&). //Destructor ~RouteSelectorS5(). //Destructor ~RouteSelectorS2(). //methods double evaluateRoute(Path&. //methods double evaluateRoute(Path&. class RouteSelectorS2 : public RouteSelector { public: //Constructor RouteSelectorS2(). class RouteSelectorS5 : public RouteSelector { public: //Constructor RouteSelectorS5(). }. //Destructor ~RouteSelectorS4(). class RouteSelectorS1 : public RouteSelector { public: //Constructor RouteSelectorS1(). }. //Do Not forget the trailing semi-colon #endif //ROUTESELECTOR_H #include <iostream. RouteSelectorS1(TrustManager*).
P . return -1.length()).0. M. } //LC this should NEVER happen if(route.0. } if(trust_manager->isKnown(route[i].setLength(stopat+1).h" using namespace std. //temp = ( (double)rand()/(double)RAND_MAX+1 ). route. double average_trust = 0. //the route might be A->B->C->D->E even though e only want to use //A->B->C.i++) { if(stopat == 1)//dest is next to us { //cerr << "destination is next hop"<<endl. //cerr << "The value of the temp variable is :" << temp << endl.Route selection strategy 1 -----------------/ //Constructor RouteSelectorS1::RouteSelectorS1(){} RouteSelectorS1::RouteSelectorS1(TrustManager* tm) { this->trust_manager = tm. //-----------. int total_nr_of_nodes=0. total_nr_of_nodes++.getNSAddr_t()))//we know it { //should maybe consult a policy before we add the value? //int h = route[i].h> <string> <map> <sstream>//for double to string "RouteSelector.Sc. } //returns the calculated trust of the route //Strategy 1: average of all trust/nr of nodes in path double RouteSelectorS1::evaluateRoute(Path& route. } //Destructor RouteSelectorS1::~RouteSelectorS1(){} //setter for Trustmanager void RouteSelectorS1::setTrustManager(TrustManager* tm) { this->trust_manager = tm. ofstream routefile("routestat.0. total_trust = total_trust + temp. double total_trust =0. double temp =0. the stopat arg tells us were the destination is-so we shorten the route to this point //route. double result = 0. return MAXTRUSTVAL.0. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 132 . //cerr << "DOING IT\n" <<endl. //the sender is always the first in the ID[] but we take it with anyway for(int i =0. cout<<"\n The biggest error in the hole world ever has ocurred\n "<<endl. //temp = trust_manager->getTrustValueForNode(route[i].//LC debugtrust_manager>getTrustValue(route[i].int& stopat) { //routefile << "Node :"<<trust_manager->getId() <<"wrote to file\n".getNSAddr_t())->getValue().h" "TrustConstants.getNSAddr_t().0. temp = trust_manager->getTrustValue(route[i].getNSAddr_t()).route.length() < stopat) { cerr<<"\n The biggest error in the hole world ever has ocurred\n "<<endl. i < stopat. //cerr << "DID IT\n" <<endl.txt").getNSAddr_t())->getValue().removeSection(stopat.Source code #include #include #include #include #include #include <stdio.
route. total_nr_of_nodes++. } //LC this should NEVER happen if(route.getNSAddr_t() <<" unknown in path in RouteSelectorS1::evaluateRoute" <<endl. return result.length() < stopat) { cerr<<"\n The biggest error in the hole world ever has ocurred\n "<<endl. //the sender is always the first in the ID[] but we take it with anyway for(int i =0. total_trust = total_trust + temp. 133 M. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . } //used for testing void RouteSelectorS1::testIt() { cout << "Testing RouteSelector S1" << endl.Sc. //the route might be A->B->C->D->E even though e only want to use //A->B->C. } //-----------.DEFAULTUNKNOWNVAL).removeSection(stopat. result = average_trust. the stopat arg tells us were the destination is-so we shorten the route to this point //route.0. int total_nr_of_nodes=0.0. double average_trust = 0.0. } //Destructor RouteSelectorS2::~RouteSelectorS2(){} //setter for Trustmanager void RouteSelectorS2::setTrustManager(TrustManager* tm) { this->trust_manager = tm.0. trust_manager->createTrustValue(route[i]. return MAXTRUSTVAL. i < stopat.i++) { if(stopat == 1)//dest is next to us { //cerr << "destination is next hop"<<endl. double temp =0.//maybe divide here if(RSVERBOSE) cerr << "route selector S1 calculated a route to the value: "<<result<<"and the lenght of the route was:"<<stopat<<endl. trust_manager->testIt(). cout << "Testing Call to Trust Manager testIO()" << endl. } //Strategy 2: average trust/nr_of_nodes -> shorter routes are favoured double RouteSelectorS2::evaluateRoute(Path& route. route.getNSAddr_t().int& stopat) { double result = 0. double total_trust =0.//total_nr_of_nodes.Route selection strategy 2 -----------------/ //Constructor RouteSelectorS2::RouteSelectorS2(){} RouteSelectorS2::RouteSelectorS2(TrustManager* tm) { this->trust_manager = tm.length()).Source code } else//should not happen but if it does we create it { cerr << "Node: "<< route[i]. temp = trust_manager->getTrustValue(route[i].setLength(stopat+1).getNSAddr_t())->getValue(). } } //now do the heuristic average_trust = total_trust/total_nr_of_nodes.P .
//maybe divide here if(RSVERBOSE) cerr << "route selector S2 calculated a route to the value: "<<result<<"and the lenght of the route was:"<<stopat<<endl.getNSAddr_t(). total_nr_of_nodes++.0.getNSAddr_t())->getValue(). double average_trust = 0. trust_manager->createTrustValue(route[i].Route selection strategy 3 -----------------/ //Constructor using the average of the experiences and Not trust values RouteSelectorS3::RouteSelectorS3(){} RouteSelectorS3::RouteSelectorS3(TrustManager* tm) { this->trust_manager = tm.getNSAddr_t(). } //-----------.getNSAddr_t() <<" unknown in path in RouteSelectorS2::evaluateRoute" <<endl.getNSAddr_t())>getValue(). } //used for testing void RouteSelectorS2::testIt() { cout << "Testing RouteSelector S2" << endl. } if(trust_manager->isKnown(route[i]. M. total_trust = total_trust + temp.Sc. trust_manager->testIt(). Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 134 .0. return result.//LC debugtrust_manager->getTrustValue(route[i].int& stopat) { double result = 0. } //Destructor RouteSelectorS3::~RouteSelectorS3(){} //setter for Trustmanager void RouteSelectorS3::setTrustManager(TrustManager* tm) { this->trust_manager = tm.getNSAddr_t()). total_trust = total_trust + temp. return -1. temp = trust_manager->getTrustValue(route[i].P . double total_trust =0. int total_nr_of_nodes=0.getNSAddr_t())->getValue(). //temp = trust_manager>getTrustValueForNode(route[i]. temp = trust_manager->getTrustValue(route[i]. //cerr << "DOING IT\n" <<endl. result = average_trust/total_nr_of_nodes. } } //now do the heuristic average_trust = total_trust/total_nr_of_nodes.0. //cerr << "The value of the temp variable is :" << temp << endl. } //Strategy 3: buidl on the number of experiences double RouteSelectorS3::evaluateRoute(Path& route. //cerr << "DID IT\n" <<endl. } else//should not happen but if it does we create it { cerr << "Node: "<< route[i].Source code cout<<"\n The biggest error in the hole world ever has ocurred\n "<<endl.getNSAddr_t()))//we know it { //should maybe consult a policy before we add the value? //int h = route[i]. //temp = ( (double)rand()/(double)RAND_MAX+1 ). total_nr_of_nodes++.0. cout << "Testing Call to Trust Manager testIO()" << endl.DEFAULTUNKNOWNVAL).
trust_manager->testIt().getNSAddr_t(). if(RSVERBOSE) cerr << "route selector S3 calculated a route to the value: "<<result<<"and the lenght of the route was:"<<stopat<<endl. return MAXTRUSTVAL. } } //now do the heuristic average_trust = total_trust/total_nr_of_nodes. total_trust = total_trust + temp. cout<<"\n The biggest error in the hole world ever has ocurred\n "<<endl. total_trust = total_trust + temp.getNSAddr_t())>getAverageOfExperiences().length() < stopat) { cerr<<"\n The biggest error in the hole world ever has ocurred\n "<<endl.setLength(stopat+1). //the sender is always the first in the ID[] but we take it with anyway for(int i =0.removeSection(stopat.getNSAddr_t() <<" unknown in path in RouteSelectorS3::evaluateRoute" <<endl. i < stopat+1. return -1. total_nr_of_nodes++. //the route might be A->B->C->D->E even though e only want to use //A->B->C. } if(trust_manager->isKnown(route[i]. //cerr << "The value of the temp variable is :" << temp << endl. trust_manager>createTrustValue(route[i].Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . total_nr_of_nodes++. } //-----------. temp = trust_manager->getTrustValue(route[i].getNSAddr_t())>getAverageOfExperiences(). //cerr << "DID IT\n" <<endl. } else//should not happen but if it does we create it { cerr << "Node: "<< route[i].getNSAddr_t()))//we know it { //should maybe consult a policy before we add the value? temp = trust_manager->getTrustValue(route[i].0. return result.i++) { //LC this should NEVER happen if(route. route.route. cout << "Testing Call to Trust Manager testIO()" << endl.length()).Source code double temp= 0. the stopat arg tells us were the destination is-so we shorten the route to this point //route.0. } if(stopat == 1) { //cerr << "destination is next hop"<<endl.P . } //used for testing void RouteSelectorS3::testIt() { cout << "Testing RouteSelector S3" << endl.Route selection strategy 4 -----------------/ //Constructor using the average of the experiences and Not trust values RouteSelectorS4::RouteSelectorS4(){} RouteSelectorS4::RouteSelectorS4(TrustManager* tm) { 135 M. result = average_trust.DEFAULTUNKNOWNVAL).
length() < stopat) { cerr<<"\n The biggest error in the hole world ever has ocurred\n "<<endl.setLength(stopat+1). double total_trust =0. temp = trust_manager->getTrustValue(route[i].getNSAddr_t() <<" unknown in path in RouteSelectorS4::evaluateRoute" <<endl. int total_nr_of_nodes=0.getNSAddr_t())>getAverageOfExperiences(). trust_manager>createTrustValue(route[i]. } //Destructor RouteSelectorS4::~RouteSelectorS4(){} //setter for Trustmanager void RouteSelectorS4::setTrustManager(TrustManager* tm) { this->trust_manager = tm.0. } if(trust_manager->isKnown(route[i]. //cerr << "DID IT\n" <<endl. //the sender is always the first in the ID[] but we take it with anyway for(int i =0.25) { return -1. route.DEFAULTUNKNOWNVAL).25) { return -1. } else//should not happen but if it does we create it { cerr << "Node: "<< route[i]. return -1. } M. //POLICY if trust < -0.0.route. double temp=0.0. } total_trust = total_trust + temp.i++) { if(stopat == 1)//dest is next to us { //cerr << "destination is next hop"<<endl.Source code this->trust_manager = tm.length()). return MAXTRUSTVAL.P .getNSAddr_t())>getAverageOfExperiences(). total_nr_of_nodes++.Sc. } //Strategy 4: buidl on the number of experiences using a policy double RouteSelectorS4::evaluateRoute(Path& route. //cerr << "The value of the temp variable is :" << temp << endl.removeSection(stopat.0.0. the stopat arg tells us were the destination is-so we shorten the route to this point //route. //POLICY if trust < -0.0.getNSAddr_t().getNSAddr_t()))//we know it { //should maybe consult a policy before we add the value? temp = trust_manager->getTrustValue(route[i]. double average_trust = 0.0.25 return -1 if(temp < -0. cout<<"\n The biggest error in the hole world ever has ocurred\n "<<endl.int& stopat) { double result = 0. i < stopat. } //LC this should NEVER happen if(route. //the route might be A->B->C->D->E even though e only want to use //A->B->C. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 136 .25 return -1 if(temp < -0.
int& stopat) { double result = 0. route.route. } //Strategy 5: Return the lowest trust value of the route double RouteSelectorS5::evaluateRoute(Path& route. } //used for testing void RouteSelectorS4::testIt() { cout << "Testing RouteSelector S4" << endl. double temp=0. double minimum.0.length() < stopat) { cerr<<"\n The biggest error in the hole world ever has ocurred\n "<<endl.0. cout<<"\n The biggest error in the hole world ever has ocurred\n "<<endl. int lowestid. for(int i =0.removeSection(stopat. cout << "Testing Call to Trust Manager testIO()" << endl.getNSAddr_t()<<"is evaluating"<< route. return -1. } */ if(stopat == 1) { 137 M. result = average_trust. trust_manager->testIt().i++) { //LC this should NEVER happen /*if(route.length()). //the route might be A->B->C->D->E even though e only want to use //A->B->C. } //-----------. if(RSVERBOSE) cerr << "route selector S4 calculated a route to the value: "<<result<<"and the lenght of the route was:"<<stopat<<endl. int firsttime = 1.P . //the sender is always the first in the ID[] but we take it with anyway //cerr<<"Node : "<< route[0].Source code total_trust = total_trust + temp. i < stopat.dump() <<"with stopat: "<<stopat<<endl. } //Destructor RouteSelectorS5::~RouteSelectorS5(){} //setter for Trustmanager void RouteSelectorS5::setTrustManager(TrustManager* tm) { this->trust_manager = tm.Sc. the stopat arg tells us were the destination is-so we shorten the route to this point //route. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 . return result.0.setLength(stopat+1). } } //now do the heuristic average_trust = total_trust/total_nr_of_nodes.Route selection strategy 5 return minimum of trust values ----------------/ //Constructor using the average of the experiences and Not trust values RouteSelectorS5::RouteSelectorS5(){} RouteSelectorS5::RouteSelectorS5(TrustManager* tm) { this->trust_manager = tm. total_nr_of_nodes++.
firsttime = 0.getNSAddr_t())->getValue(). trust_manager->testIt().c++ -*TrustConstants. } else { temp = trust_manager>getTrustValue(route[i].Source code //cerr << "destination is next hop"<<endl. .getNSAddr_t(). } P. cout << "Testing Call to Trust Manager testIO()" << endl. adjustment here makes it easier to change settings of simulation */ #ifndef TRUSTCONSTANTS_H #define TRUSTCONSTANTS_H M.getNSAddr_t().getNSAddr_t() <<" unknown in path in RouteSelectorS5::evaluateRoute" <<endl. if(temp < minimum) { minimum = temp.getNSAddr_t())->getValue().getNSAddr_t().h /* -*. if(temp < minimum) { minimum = temp. } } } } if(RSVERBOSE) cerr << "RS 5 returning:"<<minimum<<"from node with id"<<lowestid<<endl.getNSAddr_t())->getValue().getNSAddr_t())->getValue(). lowestid = route[i].DEFAULTUNKNOWNVAL). trust_manager>createTrustValue(route[i]. lowestid = route[i]. } if(trust_manager->isKnown(route[i]. if(firsttime) { minimum = trust_manager>getTrustValue(route[i].P . } //used for testing void RouteSelectorS5::testIt() { cout << "Testing RouteSelector S4" << endl. } } } else//should not happen but if it does we create it { cerr << "Node: "<< route[i]. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 138 .getNSAddr_t()))//we know it { //should maybe consult a policy before we add the value? if(firsttime) { minimum = trust_manager>getTrustValue(route[i]. return minimum. firsttime = 0. } else { temp = trust_manager>getTrustValue(route[i].9 TrustConstants.Sc. return MAXTRUSTVAL.h Constants used in trust.
0 //the max trust value /*used to give when no nodes in a route is known .Source code #include "path.Sc.P .4//the default trustval for s1 .4 //for strategy 2 /*used when node is unknown is routeselector*/ #define DEFAULTUNKNOWNVAL -0.0 //acktimed out #define DATAPACKETRECEIVED 0.7 //data from someboby else #define MAXTRUSTVAL 1.measured! //what is the max #endif // TRUSTCONSTANTS_H 139 M.0 //ack received #define NOACKRECEIVED -1.estimated #define S2_DEFAULTTRUSTVALUE -0.trustformater*/ #define S1_DEFAULTTRUSTVALUE -0.4 //if we ask for the average of experiences and there are no experinces (RS3) #define MAX_NR_OF_EXP 5 //the number of experinces we store #define USEROUTESELECTOR 4 //which routeselection to use //verbose flags for viewing diffent output #define #define #define #define RSVERBOSE 0 //1 debug routeselector ACKVERBOSE 0 TRUSTVALUEUPDATEVERBOSE 0 MALICIOUSDROPVERBOSE 0 //max 10 //ACK time out in seconds .h" //LC use these constants to define evil behaviuor #define NROFEVILNODES 10 /*Acknowledgements */ #define AVR_ACK_TIME_OUT_VAL 0. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 .01 wait we will add to the average /*events -meaning packets received */ #define ACKRECEIVED 1.07 #define MAXWAIT 0.4 //the value we give to nodes that are unknown during route selection (determined by experiments) #define NOEXPERIENCES -0.
P .Sc. Thesis Secure Routing in Mobile Ad Hoc Networks by Lennart Conrad 2003 140 .Source code M.
|
https://www.scribd.com/document/72801956/imm2971
|
CC-MAIN-2018-51
|
en
|
refinedweb
|
#include "petscis.h" PetscErrorCode ISGetInfo(IS is, ISInfo info, ISInfoType type, PetscBool compute, PetscBool *flg)Collective or logically collective on IS if the type is IS_GLOBAL (logically collective if the value of the property has been permanently set with ISSetInfo())
Note: ISGetInfo uses cached values when possible, which will be incorrect if ISSetInfo() has been called with incorrect information. To clear cached values, use ISClearInfoCache().
|
https://www.mcs.anl.gov/petsc/petsc-dev/docs/manualpages/IS/ISGetInfo.html
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
#include <deal.II/base/derivative_form.h>
This class represents the (tangential) derivatives of a function \( \mathbf \mathbf F(\mathbf x)\) with \(\mathbf x\in {\mathbb R}^{\text{dim}}\), in such a way that the directional derivative in direction \(\mathbf d\in {\mathbb R}^{\text{dim}}\) so that
\begin{align*} \nabla \mathbf F(\mathbf x) \mathbf d = \lim_{\varepsilon\rightarrow 0} \frac{\mathbf F(\mathbf x + \varepsilon \mathbf d) - \mathbf F(\mathbf x)}{\varepsilon}, \end{align*}
i.e., one needs to be able to multiply the matrix \(\nabla \mathbf 58 of file derivative_form.h.
Constructor. Initialize all entries to zero.
Constructor from a tensor.
Read-Write access operator.
Read-only access operator.
Assignment operator.
Assignment operator.
Converts a DerivativeForm <order, dim, dim, Number> to Tensor<order+1, dim, Number>. In particular, if order == 1 and the derivative is the Jacobian of \(\mathbf F(\mathbf x)\), then Tensor[i] = \(\nabla F_i(\mathbf x)\).
Converts a DerivativeForm<1, dim, 1, Number> to Tensor<1, dim, Number>.
Return the transpose of a rectangular DerivativeForm, viewed as a two dimensional matrix.
Compute the Frobenius norm of this form, i.e., the expression \(\sqrt{\sum_{ij} |DF_{ij}|^2} = \sqrt{\sum_{ij} |\frac{\partial F_i}{\partial x_j}|^2}\).
Compute the volume element associated with the jacobian of the transformation \(\mathbf F\). That is to say if \(DF\) is square, it computes \(\det(DF)\), in case DF is not square returns \(\sqrt{\det(DF^T \,DF)}\).
Assuming that the current object stores the Jacobian of a mapping \(\mathbf F\), then the current function computes the covariant form of the derivative, namely \((\nabla \mathbf F) {\mathbf G}^{-1}\), where \(\mathbf G = (\nabla \mathbf F)^{T}(\nabla \mathbf F)\). If \(\nabla \mathbf F\) is a square matrix (i.e., \(\mathbf F: {\mathbb R}^n \mapsto {\mathbb R}^n\)), then this function simplifies to computing \(\nabla {\mathbf F}^{-T}\).
Determine an estimate for the memory consumption (in bytes) of this object.
Auxiliary function that computes \(A T^{T}\) where A represents the current object. 396 of file derivative_form.h.
Similar to the previous apply_transformation(). Each row of the result corresponds to one of the rows of
D_X transformed by
grad_F, equivalent to \(\mathrm{D\_X} \, \mathrm{grad\_F}^T\) in matrix notation.
Definition at line 418 445 of file derivative_form.h.
Transpose of a rectangular DerivativeForm DF, mostly for compatibility reasons.
Definition at line 465 of file derivative_form.h.
Array of tensors holding the subelements.
Definition at line 166 of file derivative_form.h.
|
https://dealii.org/developer/doxygen/deal.II/classDerivativeForm.html
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
Firebase + Ember = Mind Blown
I don’t think there is a faster way to build a web app than firebase and ember.
The awesomeness of Firebase’s realtime database, no server, no backend, instant deployment, hosting and user authentication makes it an incredibly productive choice.
Ember’s conventions and best practices and incredibly productive CLI makes it an excellent choice for your front-end. Let’s see how fast we can get a working app together.
Create a Firebase App
Go to your firebase console and create a new app
Create a Firebase Database
Make sure you change the rules to enable read/write for testing purposes. Learn more about Firebase rules.
Create an Ember App
Install ember globally
npm install -g ember-cli
Create a new app
ember new my-demo-app
Install ember add-on into your app to enable firebase integration
cd my-demo-app
ember install emberfire
I ran into an issue (can’t remember what) but installing this add-on fixed it
ember install ember-cli-shims
Configure EmberFire
Get firebase credentials and add them to your ember app.
Enable Authentication in Firebase
I hate writing authentication code. This is the fastest I have ever added authentication to an application. We will add Google login but firebase supports several OAuth providers including github, twitter, etc…
Add Authentication to Emeber
ember install torii
Add this to
config/environment.js
torii: {
sessionServiceName: ‘session’
}
Create a file name
app/torii-adapters/application.js with the following code:
import ToriiFirebaseAdapter from ‘emberfire/torii-adapters/firebase’;
export default ToriiFirebaseAdapter.extend({
});
Add login and logout functions in the application route
app/routes/application.js :
import Ember from 'ember';
export default Ember.Route.extend({
session: Ember.inject.service(),
beforeModel: function() {
return this.get('session').fetch().catch(function() {});
},
actions: {
this.get('session').open('firebase', { provider: provider}).then(function(data) {
console.log(data.currentUser);
});
},
signOut: function() {
this.get('session').close();
}
}
});
Now add a login/logout button to your application template to test this out. In
app/templates/application.hbs
{{#if session.isAuthenticated}}
Logged in as {{session.currentUser.displayName}}
<button {{action "signOut"}}>Sign out</button>
{{outlet}}
{{else}}
<button {{action "signIn" "google"}}>Sign in with Google</button>
{{/if}}
THAT IS IT!!! You can login to your app with Google…
Create Data
Let’s create some data in our firebase database.
Create an ember model
ember g model article title:string
Then simply save the model as you usually do with any ember app and it magically appears in the database…
var article= this.store.createRecord('article',{
title : 'Hello this is my title'
});
article.save();
Go look in your firebase console and you will see your data in there.
Deploy
Firebase provides hosting as well and it is dead simple.
Install the firebase tools cli
npm install -g firebase-tools
Build your ember app
ember build
Init firebase and follow the prompts (more info here and here)
firebase init
Deploy
firebase deploy
Tip: you can open your app url from the terminal by running
firebase open .
Want to send emails with Firebase? See my article here.
|
https://medium.com/front-end-weekly/firebase-ember-mind-blown-8e0a2ae1c0ec?source=---------2-----------------------
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
QtMultimedia.CameraCapture
An interface for capturing camera images More...
Properties
- capturedImagePath : string
- errorString : string
- ready : bool
- resolution : size
Signals
- captureFailed(requestId, message)
- imageCaptured(requestId, preview)
- imageMetadataAvailable(requestId, key, value)
- imageSaved(requestId, path)
Methods
- cancelCapture()
- capture()
- captureToLocation(location)
- setMetadata(key, value)
Detailed Description
This type allows you to capture still images and be notified when they are available or saved to disk. You can adjust the resolution of the captured image and where the saved image should go.
CameraCapture is a child of a Camera (as the
imageCapture property) and cannot be created directly.
import QtQuick 2.0 import QtMultimedia 5.0 Item { width: 640 height: 360 Camera { id: camera imageCapture { onImageCaptured: { // Show the preview in an Image photoPreview.source = preview } } } VideoOutput { source: camera focus : visible // to receive focus and capture key events when visible anchors.fill: parent MouseArea { anchors.fill: parent; onClicked: camera.imageCapture.capture(); } } Image { id: photoPreview } }
Property Documentation
This property holds the location of the last captured image.
This property holds the error message related to the last capture.
This property holds resolution.
Signal Documentation
This signal is emitted when an error occurs during capture with requestId. A descriptive message is available in message.
The corresponding handler is
onCaptureFailed.
This signal is emitted when an image with requestId has been captured but not yet saved to the filesystem. The preview parameter can be used as the URL supplied to an Image.
The corresponding handler is
onImageCaptured.
See also imageSaved.
This signal is emitted when the image with requestId has new metadata available with the key key and value value.
The corresponding handler is
onImageMetadataAvailable.
See also imageCaptured.
This signal is emitted after the image with requestId has been written to the filesystem. The path is a local file path, not a URL.
The corresponding handler is
onImageSaved.
See also imageCaptured.
Method Documentation
Cancel pending image capture requests.
Start image capture. The imageCaptured and imageSaved signals will be emitted when the capture is complete.
The image will be captured to the default system location, typically QStandardPaths::writableLocation(QStandardPaths::PicturesLocation) for still imaged or QStandardPaths::writableLocation(QStandardPaths::MoviesLocation) for video.
Camera saves all the capture parameters like exposure settings or image processing parameters, so changes to camera paramaters after capture() is called do not affect previous capture requests.
CameraCapture::capture returns the capture requestId parameter, used with imageExposed(), imageCaptured(), imageMetadataAvailable() and imageSaved() signals.
Start image capture to specified location. The imageCaptured and imageSaved signals will be emitted when the capture is complete.
CameraCapture::captureToLocation returns the capture requestId parameter, used with imageExposed(), imageCaptured(), imageMetadataAvailable() and imageSaved() signals.
If the application is unable to write to the location specified by
location the CameraCapture will emit an error. The most likely reasons for the application to be unable to write to a location is that the path is wrong and the location does not exists, or the application does not have write permission for that location.
Sets a particular metadata key to value for the subsequent image captures.
See also QMediaMetaData.
|
https://phone.docs.ubuntu.com/en/apps/api-qml-current/QtMultimedia.CameraCapture
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
Telling – how hard would that be? Well, let’s find out as we take a look at a machine learning algorithm called Q-Learning.
Q-Table Learning
Q-Learning is a type of reinforcement machine learning. One (simple) way to implement the algorithm is to use something called a Q-Table. All that really means is that we will have a table which maps from (state, action) pairs, to a value of the expected potential reward for taking the action from that state. In other words, as we fill out the values in the table, a machine learning agent can look up the potential values of any action at a given state, pick the one with the highest reward, and execute it as a policy for solving a problem. We will continue to follow along with the original blog post here, as we analyze Arthur Juliani’s solution:
import gym import numpy as np env = gym.make('FrozenLake-v0') #Initialize table with all zeros Q = np.zeros([env.observation_space.n,env.action_space.n]) # Set learning parameters lr = .8 y = .95 num_episodes = 2000 #create lists to contain total rewards and steps per episode #jList = [] rList = [] for i in range(num_episodes): #Reset environment and get first new observation s = env.reset() rAll = 0 d = False j = 0 #The Q-Table learning algorithm while j < 99: j+=1 #Choose an action by greedily (with noise) picking from Q table a = np.argmax(Q[s,:] + np.random.randn(1,env.action_space.n)*(1./(i+1))) #Get new state and reward from environment s1,r,d,_ = env.step(a) #Update Q-Table with new knowledge Q[s,a] = Q[s,a] + lr*(r + y*np.max(Q[s1,:]) - Q[s,a]) rAll += r s = s1 if d == True: break #jList.append(j) rList.append(rAll) print "Score over time: " + str(sum(rList)/num_episodes) print "Final Q-Table Values" print Q
The code above came from here. Copy & paste the code and run it to make sure everything works. On one run (note that your results may vary), after printing the Q table I saw the following values:
[[ 1.18181511e-01, 1.05839621e-02, 5.93369485e-03, 5.28426147e-04], [ 0.00000000e+00, 5.08521011e-03, 2.31402787e-03, 5.81610901e-02], [ 3.58928767e-03, 2.29724031e-03, 2.30403831e-02, 0.00000000e+00], [ 1.25818424e-03, 2.06772726e-03, 2.04618843e-03, 1.28835672e-02], [ 1.45386252e-01, 0.00000000e+00, 2.60545654e-03, 8.42432295e-03], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [ 2.86682494e-04, 2.65293005e-07, 8.33202120e-04, 1.24716625e-05], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [ 3.38969412e-03, 2.58918580e-03, 1.52705296e-03, 1.51976034e-01], [ 0.00000000e+00, 2.83306822e-01, 8.81415294e-04, 3.89093922e-03], [ 8.20269416e-01, 1.14104585e-03, 4.87808190e-04, 0.00000000e+00], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, 2.43200000e-02, 5.62247331e-01, 0.00000000e+00], [ 0.00000000e+00, 4.77429893e-01, 0.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00]]
You might recognize this as a 2 dimensional array. If so, you’re right – we have 16 rows (for possible game states) by 4 columns (for possible actions). However, I don’t find it very intuitive to look at the Q-Table in this way. It would help for states to be positioned relative to each other like they are on the gameboard, and for actions to be positioned over their state toward the direction they provide. I have overlaid grid lines on top of the tile map I made earlier, with each tile split into four sub sections by an ‘X’. The space in each slice of the tile represents the value of taking an action to move in a direction of that side. I also rounded the values at two decimal places for easier readability. Take a look at another round of completed Q-Table data with this format:
To interpret this data the way our machine learning agent does, you must first look at whatever state the environment is in (what tile is the agent located at). Then you look at each of the values for each of the actions at that state (the 4 slices on the tile). The “best” action to take is the action with the highest value.
Let’s walk through the ideal solution according to this table. *Quick tip* remember that the tiles are indexed in the same order we read (from left to right, and top to bottom) with the values from 0 to 15 like so:
0, 1, 2, 3 4, 5, 6, 7 8, 9, 10, 11 12, 13, 14, 15
- [Tile 0] Beginning in the upper left corner, we see that the highest value (0.08) is on the left slice. The computer is relying on random wind to push it down a tile [to 4], because the path to the right is more risky.
- [Tile 4] Again we also have the highest value (0.13) on the left slice. Any other action has a chance of falling in the hole and thus ending the game without any reward, therefore the computer is again relying on random wind to push it down a tile [to 8].
- [Tile 8] Now the highest value (0.19) is on the top slice. The computer is hoping for random wind to push it toward the right [to 9] even though it may actually backtrack into a position that is still safe [at 4].
- [Tile 9] One of our first “obvious” answers, from this position, the computer tries to go down [to 13]. Any random wind pushing it to the right or left would still be a safe position, so there is nothing to worry about.
- [Tile 13] Another “obvious” answer, here we try to go to the right [to 14]. Any random wind up or down will still be a safe position.
- [Tile 14] We’ve almost won – it would be tempting for any human to just choose to go right, but the computer (not being in any rush) takes the safest approach and actually tries to go down (into the wall) hoping for random wind to push it onto the goal [at 15]. Going right is still “safe”, but in the event that random wind pushed the agent up, it would end up taking a circular route [Tile 10, 9, 13, 14] to get back to where it had been (to avoid any possibility of falling in holes). Whereas by going down it will either end up in the same tile, backtrack to Tile 13 then forward to 14 again, or get lucky and land on the goal.
Now that I’ve explained what the values mean, let’s observe how they are learned over time:
Hopefully you are able to gain some extra intuitions about what the code is doing. I observed things like:
- The values flood outward from the goal tile, because it is the only one that generates a reward (note that I played back frames more slowly at the very beginning to make sure you could see this).
- The values fluctuate – they can go up or down based on the outcome of each round of the game, but should generally learn a truth that favors certain actions over others.
- The agent has learned to favor the safest path, even when it is a potentially longer one.
- None of the slices on the holes or goal ever hold any value. This is because no actions were taken on the environment once those states were reached, therefore the Q-Table is never updated at those entries.
I’d like to focus a bit more on that first bullet point, because I think it is really important to understand what happened here. Initially, we started out with a blank slate – the values all over the table were zero. Reaching the goal, and earning a reward from the environment, was the ONLY way to introduce a new value to the table at that time. Therefore, when the agent first began learning, the ONLY way it could determine that ANY action was good, was to be lucky enough to take a series of actions leading all the way to the goal, all chosen at random, and only the very last action taken would be “learned” as a good choice.
After having reached the goal on at least one session, the table now had an action with a positive value. Any followup session would have an opportunity to learn both from reaching the goal, as well as from reaching a tile that has its own reward from having reached the goal in the past. With each new session, the chain of rewards can potentially grow another tile longer, and this is how the agent can ultimately learn to do things even when the reward for its actions is delayed until some point in the future.
Next, consider the second bullet point – that the values in the table can both increase and decrease. As each action is taken our agent attempts to “learn” based on the maximum potential reward of the tile it reached. When following the “correct” path, such as when moving from tile 14 to tile 15, we grow by some learning rate multiplied by a positive reward causing the tile’s own action (and therefore the tile position itself) to grow in value. This results in a sort of gradient where the value of each tile in the path should generally grow until it reaches the goal. This also helps indicate when the agent might be going the wrong direction, even when moving along the correct path, because the maximum value of the next tile would be less than the value of the tile it had been standing on. Such an action would then “decrease” the value of taking an action that led to backtracking.
NumPy
Before we do a deep dive of the code for the solution, I want to point out a few features of the numpy module. Feel free to open up a python console window and follow along:
import numpy as np
Start by importing the module. I used the same abbreviation, ‘np’, as the solution code so we dont get confused.
table = np.zeros([4,3]) table # prints to the console: # array([[ 0., 0., 0.], # [ 0., 0., 0.], # [ 0., 0., 0.], # [ 0., 0., 0.]])
Here I created an N-dimensional numpy array. The array I passed in defines the number of dimensions (the length of the array) as well as the capacity of each dimension (the values at each index in the array). Each entry in the table uses a default value of zero because of the “zeroes” method used to create it. Note that the documentation suggests we could have passed an int or a tuple of ints, but the array also worked, and matched the style of code in the solution.
table[0,1] = 3.14 table # prints to the console: # array([[ 0. , 3.14, 0. ], # [ 0. , 0. , 0. ], # [ 0. , 0. , 0. ], # [ 0. , 0. , 0. ]])
You can index into an N-dimensional numpy array just like you would with a normal array. Here I set one of the table’s values to pi.
table[0,:] # prints to the console: # array([ 0. , 3.14, 0. ])
Here I have read and printed the whole contents at the first row of the array.
list = np.random.randn(1,3) # array([[-1.45347796, 0.71221563, 0.54473448]])
Zeros isnt the only way to create an N-dimensional array- here we create a 1×3 array of random values and stored it in a variable named “list”.
list * 3 # array([[-4.36043389, 2.1366469 , 1.63420343]])
One interesting feature of an N-Dimensional array is that you can scale each of its elements simply by multiplying by a scalar as I did above. Note that I didn’t assign the result back to “list” (but I could have), I merely allowed it to print to the console.
table[0,:] + list # array([[-1.45347796, 3.85221563, 0.54473448]])
Here I have added values from a row in the first table, with the array of random values. Note that this is a component-wise operation, which means it adds the values of matched indices.
Again, I didn’t assign the result either to the original table or to the list of random numbers, I merely printed the result of the operation.
np.argmax(list) # 1
The argmax function returns the index of the largest element in an array. For the random value array that we created earlier, the middle element at index ‘1’ held the largest value, so that index was returned.
Solution Breakdown
Now, let’s dive a little deeper and look at each line of the solution code:
import gym import numpy as np
The first two lines import code from other modules. This is pretty standard practice in Python as well as many other languages. The gym module is what allows us to create and work with the Frozen Lake environment. The numpy module handles a lot of scientific computing and will be used in this code for its powerful N-dimensional array object. The last bit “as np” allows us to refer to the module with an abbreviated syntax, not that “numpy” was that long in my opinion. Oh well.
env = gym.make('FrozenLake-v0')
Here we are creating an environment based on the Frozen Lake game we’ve been using all along.
Q = np.zeros([env.observation_space.n,env.action_space.n])
Here we create our Q-Table, which is the lookup table we described above. We create it as a 2 dimensional array using the “numpy” module. The capacity of the table is 16 x 4 which is obtained by the values returned from “env.observation_space.n” (16) and “env.action_space.n” (4). Every entry in the table will be populated with a value of ‘0’ because we create the array using the call to “np.zeros”.
lr = .8
This represents a “learning rate”, which is a sort of magic number constant that can have a big impact on the performance of your algorithm. You can try with different values and observe the different ways it causes the A.I. to learn. Values closer to zero mean that the agent will “exploit” its previous knowledge while values closer to one mean that the agent will “explore” by more heavily considering recent knowledge. Essentially you want to find the right balance between learning speed (number closer to 1) and learning quality (number closer to 0).
y = .95
This represents a “discount factor” which is applied to the impact that future expected rewards have on our learning. Values closer to zero care more about current rewards while values closer to one favor long-term higher rewards. Like the “learning rate”, it is a sort of magic number that will need to be experimented with. It was likely represented with ‘y’ because that character looks kind of like the lower-case Greek letter gamma, which is normally seen in related math formulas.
num_episodes = 2000
The “num_episodes” is the number of attempts we want to take at solving the environment. We will want to try repeatedly because we need a lot of wins and losses to really develop an understanding of the (state, action) value pairs. If your learning rate was lower, you would probably need more episodes to learn from, but might end up with a better end result, so consider this yet another constant you can tweak to your liking.
for i in range(num_episodes):
The outer loop goes from 0 to the “num_episodes” (2000) constant declared previously. So the next lines of code will be repeated many times.
s = env.reset()
Each time we begin a new pass on solving the game, we need to reset the environment to its starting position. ‘s’ is the state which is implemented as an index of the possible board positions. Upon reset, the state will be ‘0’ which is the first state, and appears in the upper left hand corner designated with the letter ‘S’.
d = False
The ‘d’ will be a flag indicating whether or not the board has reached an end-game position. We initialize it to false so that it will continue playing.
j = 0 while j < 99: j+=1
The ‘j’ is the iterator for an inner loop. Each episode will be allowed 99 ‘turns’ with which to try and solve the environment. This is to prevent scenarios, particularly early in the learning process, where the computer might continually pick choices that never result in an end game state. In theory it could do so forever. The first line of the inner loop causes the iterator to increment so that the loop will eventually terminate even if the done flag never triggers.
The author probably would have used a simpler
for j in range(99): syntax, but appears to have wanted to use the value of the iterator even outside of the loop for diagnostic purposes.
a = np.argmax(Q[s,:] + np.random.randn(1,env.action_space.n)*(1./(i+1)))
This step chooses an action based in part on the learned values of the Q-Table, and in part by a random noise. ‘Q[s,:]’ means the array of values for the actions at state ‘s’. ‘np.random.randn(1,env.action_space.n)’ will create a list of random numbers that is the same length as our number of actions and we will add the two together. We use ‘(1./(i+1))’ to scale the random values over time. The higher ‘i’ becomes, the less influence the random number generator will have on our decision because (1/1) is much larger than (1/2000). In other words, when we first start learning, we use a lot of random decisions because we have no history of actions to rely on. As we play more and more rounds of the game, we rely more and more on the results of past actions so that what we have learned is more important than making random choices. ‘np.argmax’ picks the index of the largest value in the resulting array which means it is picking the action with the highest ‘expected’ reward.
s1,r,d,_ = env.step(a)
Using the value of ‘a’, which is the action index we chose on the previous line, we will apply an action to the environment using the “step” call. There are four return values from this method including: ‘s1’ which is the new state that has been entered. ‘r’ is the reward for reaching the new state. ‘d’ is the flag indicating whether or not the game is done such as by falling in a hole or reaching the goal. The final parameter ‘_’ is unused – it holds debug info about the environment but should not be used in any attempt to solve it.
Q[s,a] = Q[s,a] + lr*(r + y*np.max(Q[s1,:]) - Q[s,a])
Now that we have chosen an action and gotten a result, we can update our Q-Table with what we’ve found. This line is based on a formula called the Bellman equation. Note that it uses our magic number constants defined above. Let’s try to break the line down a bit more to make sure its dynamic parts are fully understood. Imagine that we are doing another pass on the table starting from where it left off, so the values in the table will match the chart I have above. For now, let’s create an example based on the following:
- ‘s’ is state ‘0’ (the upper left tile)
- ‘a’ is action ‘0’ (move left)
- Q[s,a] is Q[0,0] which currently holds the value of ‘0.08’
- ‘s1’ is ‘4’ (due to random wind)
- ‘r’ is ‘0’ (only the goal tile provides a reward)
- Q[s1:] refers to the entire array of action values at state ‘s1’
- np.max(Q[s1,:]) is ‘0.13’ (the highest possible reward at state ‘s1’)
Now we know enough to rewrite the equation by substituting real values like so:
Q[0,0] = 0.08 + 0.8 * (0.0 + 0.95 * 0.13 - 0.08) # This results in a value of (0.1148) which would continue to strengthen / increase the expected reward for moving left
Make sense so far? Let’s continue…
s = s1
Now that we have updated the Q-Table, we are free to update our local reference of what the current state is – which is the resulting state based on the action we took.
if d == True: break
If we reached the goal, or fell in a hole, we need to abort the loop, because the game has ended and there is no point to taking further actions upon the environment. We check for these conditions by the reference to ‘d’ which indicates when the environment is done, and we use the ‘break’ statement to break out of the inner loop whenever done is true.
Note that I didn’t bother to comment on a few lines of this code such as anything referring to “jList”, because it was commented out anyway. I also didn’t comment on the “rList” which merely held an array of reward values – one entry for each episode. This code is merely diagnostic and has nothing to do with training the machine learning agent.
Summary
In this lesson we discussed the implementation of a Q-Table for a mchine learning agent. The code “solved” the Frozen Lake environment, such that the solution resulted in a table that mapped from a state and action, to a potential reward. We also covered the bits of the numpy module that were important to complete the problem.
Overall, we actually succeeded at writing and (hopefully) understanding a reinforcement machine learning algorithm. Cool as it is, we can’t stop here. Any game I would be interested to make is going to require a lot more states as well as actions, and our Q-Table wont scale well for that purpose. Don’t worry, there are solutions that do scale well – one of which is a neural network. Keep following along and we will take a look at one of those next.
If you find value in my blog, you can support its continued development by becoming my patron. Visit my Patreon page here. Thanks!
|
http://theliquidfire.com/2018/10/05/q-learning-agents-part-2/
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
Talk:Yahoo! Answers
Contents
Examples[edit]
I don't think those examples posted at the top are particularly necessary or interesting. If examples are needed, I'm sure there are much more jaw-droppingly stupid &/or shocking ones out there. + Inciting readers to start recruiting drives or link farms on YA for RW or CP isn't a great idea. Ŵêâŝêîôîď
Methinks it is a Weasel 19:53, 7 October 2010 (UTC)
- This is the bit I'm referring to. Ŵêâŝêîôîď
Methinks it is a Weasel 19:55, 7 October 2010 (UTC)
- Understood. Welcome to RW 2.0 or is it 3.0--congradulations on the Foundation :-) . I might be doing a List of stupid Yahoo! Answers questions in a few days, or more likely, a few weeks or months. I might internalize links sooner. I also want to create articles on Answerbag, and it's terrible fall, and Fluther.Civic Cat (talk) 21:43, 7 October 2010 (UTC)
This page is crap[edit]
Yahoo! Answers is a cesspool of racists and homophobes and this is the best snark/information you can provide? YA! needs to be trashed and criticized in this article, not fucking encouraged to ccontinue existing. — Unsigned, by: 66.87.114.136 / talk / contribs (signed by bot) 13:25, 25 September 2014 (UTC)
Why do people keep removing the Wikipedia template?[edit]
Is this deliberate?Civic Cat (talk) 19:28, 12 October 2010 (UTC)
- See Template talk:Wikipedia article#I don't really like this template. Is there a reason why it's needed here? Ŵêâŝêîôîď
Methinks it is a Weasel 19:34, 12 October 2010 (UTC)
- Didn't realize that the use was restricted. I guess not, provided most RW'ians presume that there is an WP on YA. Maybe this article should be deleted as it too is "Off Mission," as
this and this apparantly were; and unlike these, Search engine optimization,YouTube.:-/21:16, 12 October 2010 (UTC)
- Get it over with and just move everything to the "Fun" namespace. Occasionaluse (talk) 21:24, 12 October 2010 (UTC)
- Are you sure Fun:Answerbag and Fun:Fluther would be acceptable?Civic Cat (talk) 21:38, 12 October 2010 (UTC)
- How about merging them into one huge "answers sites" article, like we did with the Myspace and Facebook articles? I see missionality lurking in the mists of this lot. Totnesmartin (talk) 22:10, 12 October 2010 (UTC)
- I'd be in favour of merging into an 'Answers websites' article. Dalek (talk) 22:14, 12 October 2010 (UTC)
- Sounds reasonable. I'll peruse Social networking websites and this earlier edit of Facebook, and see what I can do about an Answer sites article this week. I'd like to create a List of stupid Yahoo! Answers questions later on. Should it be in the Fun namespace? Also what about the WP, Unc, and EP templates. Both AB and YA have them.Civic Cat (talk) 23:30, 12 October 2010 (UTC)
Delete request[edit]
Why would anyone want to delete this? It may not be a great article as written, but the topic is good, because it is a major source of "discussion" for the - hum, immature? budding? teen? - atheists and creationists. it's so much fun to watch. I don't want to see us go overboard with CP like articles, but a basic "lols found here" page seems quite appropriate.
Godot What do cats dream about? 19:43, 5 April 2012 (UTC)
- I think it is the creator throwing a tantrum. Тycommunications wire 19:43, 5 April 2012 (UTC)
- Why doncha block me Ty, like ya did last night! Civic Cat Talk to Civic Cat 19:46, 5 April 2012 (UTC)
- Asshole! Civic Cat Talk to Civic Cat 19:48, 5 April 2012 (UTC)
C'mon P-Foster, Ty, and Weaseloid: delete this article. You know you three wanna!![edit]
Civic Cat Talk to Civic Cat 19:46, 5 April 2012 (UTC)
Why do I feel like I survived a suicide-by-cop?[edit]
Civic Cat Talk to Civic Cat 17:29, 22 March 2013 (UTC)
That latest "best of"[edit]
Just... wow. Ikanreed (talk) 20:53, 20 August 2014 (UTC)
- Wow nothing. Are you wowed by the satire (which isn't that impressive) or are you actually taking any of those comments seriously? Weaseloid
Methinks it is a Weasel 21:13, 20 August 2014 (UTC)
In recent years...[edit]
I think this article needs to start talking more about the recent development of Yahoo! Answers. Most of this seems to be about the site in 2014 and before, and doesn't talk much about what happened since then. It has gotten so much worse. Advicedoge (talk) 05:58, 12 March 2018 (UTC)
|
https://rationalwiki.org/wiki/Talk:Yahoo!_Answers
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
A friend of mine was banging his head against the wall because this Groovy code.
Let’s explain very quickly what this does.
First, we create an empty map and then we define a key that is the result of a string interpolation. The key will be
"job-4".
Then we verify if the key is already on the map. If the map does not have the key, we add it with the value
1, and then we do the same again, but just this time the key will be on the map and nothing will change. The value for key
"job-4", should remain the same, that is value
1.
Let me tell you something, we are all wrong. The line
println(cache[key]) will in fact, print
2.
This is madness!!! so we looked at other languages to see if one of them behaves in the same way Groovy does.
In Ruby we do:
it prints out the value
1 as expected!
In JavaScript we do:
it prints out the value
1 as expected!
In Elixir we do:
it prints out the value
1 as expected!
In Scala we do:
it prints out the value
1 as expected!
What is wrong with Groovy!!!!???
The problem comes from the way Groovy manages dynamic typing and string interpolation.
When Groovy does the string interpolation, the resulting type is
GStringImpl which means the comparison is not in the way you expected. We need to force
GStringImpl to be a
String be doing
.toString().
If we only do:
def key = "job-${4}".toString()
everything starts working as expected.
Stop using Groovy!!!
|
https://hackernoon.com/what-is-wrong-with-groovy-482b7064f591
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
Data types and variables in C# programming
Definition of Data Types
A variable holds data of a specific type. When you declare a variable to store data in an application, you need to choose an appropriate data type for that data. Visual C# is a type-safe language, which means that the compiler guarantees that values stored in variables are always of the appropriate type.
Commonly Used Data Types
The following table shows the commonly used data types in Visual C#, and their characteristics.
Declaring and Assigning Variables
Before you can use a variable, you must declare it so that you can specify its name and characteristics. The name of a variable is referred to as an identifier. Visual C# has specific rules concerning the identifiers that you can use:
- An identifier can only contain letters, digits, and underscore characters.
- An identifier must start with a letter or an underscore.
- An identifier for a variable should not be one of the keywords that Visual C# reserves for its own use.
Visual C# is case sensitive. If you use the name MyData as the identifier of a variable, this is not the same as myData . You can declare two variables at the same time called MyData and myData and Visual C# will not confuse them, although this is not good coding practice.
You can declare multiple variables in a single declaration by using the comma separator; all variables declared in this way have the same type.
Declaring a Variable:
// DataType variableName; int price; // OR // DataType variableName1, variableName2; int price, tax;
After you declare a variable, you can assign a value to it by using an assignment statement. You can change the value in a variable as many times as you want during the running of the application. The assignment operator = assigns a value to a variable.
Assigning a Variable, Declaring and Assigning:
//Declaring variableName = value; price = 10; //declaring and assigning variables int price = 10;
Implicitly Typed Variables
When you declare variables, you can also use the var keyword instead of specifying an explicit data type such as int or string. When the compiler sees the var keyword, it uses the value that is assigned to the variable to determine the type.
Declaring a Variable by Using the var Keyword:
var price = 20;
In this example, the price variable is an implicitly typed variable. However, the var keyword does not mean that you can later assign a value of a different type to price. The type of price is fixed, in much the same way as if you had explicitly declared it to be an integer variable.
Implicitly typed variables are useful when you do not know, or it is difficult to establish explicitly, the type of an expression that you want to assign to a variable.
Object Variables
When you declare an object variable, it is initially unassigned. To use an object variable, you must create an instance of the corresponding class, by using the new operator, and assign it to the object variable.
The new Operator:
ServiceConfiguration config = new ServiceConfiguration();
The new operator does two things:
- It causes the CLR to allocate memory for your object
- It then invokes a constructor to initialize the fields in that object.
The version of the constructor that runs depends on the parameters that you specify for the new operator.
Example of Variables
The program below show the use of int, var and string variables:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Variables { class Program { static void Main(string[] args) { //declaring and assigning using var var a = "C# Programming"; var b = " Tutorials"; //declaring and assigning string string myFirstName; string myLastName; myFirstName = "Info"; myLastName = "codify"; //declaring and assigning using int and string int x = 1; string y = "4"; //converting int to string string myFirstTry = x.ToString() + y; //converting string to int int mySecondTry = x + int.Parse(y); Console.WriteLine(a + b); Console.WriteLine(myFirstName + myLastName); Console.WriteLine(myFirstTry + " is Admin BM Date of Birth"); } } }
Output: C# Programming Tutorials infocodify 14 is Admin BM Date of Birth
Ads Right
|
https://www.infocodify.com/csharp/variables
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
Created on 2019-10-26 19:48 by Kevin Schlossser, last changed 2020-05-16 18:43 by P12 Pfx.
System
Windows 7 x64 SP2
Ram 16GB
6 Core AMD @ 3.2ghz
CPython 3.7.2
C Extension (pyd) import cap.
There seems to be a cap on the number of extensions that a package is able to contain. I am able to import 123 extension modules that my package has but when i go to import number 124 i get the following traceback
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.
these extension modules are part of my package, importing an extension module from another package does not change this behavior. it is only when I import the 124th extension that is in my package does it occur.
When I change the order of the imports the error does not follow the import. I end up getting the same error when the 124th extension gets loaded doesn't matter what extension it is.
I have tried to see if maybe it was a module limit and I spread the imports across multiple files and it still fails when the 124th gets loaded. I also tried imp.load_dynamic and importlib.import_module and the same error occurs.
If there is a way to work around this limitation it would be very helpful.
There is an implicit cap due to the C runtime (specifically vcruntime140.dll) allocating fibre local storage on load, which seems like the one you are hitting. However, we discovered this before the first 3.5 release and fixed it.
How are you compiling your packages? Or where are you getting them from?
It's possible that someone else is building and statically linking the C runtime, which will cause this, but distutils (and hence CPython) should not be doing it by default.
Looks like I have same problem for Windows 10 (version 1809, build - 17763.864).
I created repository with steps for reproducing -
Could you share just one of your .pyd files?
Without being able to see whether they are compiled incorrectly, it's hard to be sure whether this is the same cause as before. It certainly looks like distutils is still going to link correctly.
Done:
.pyd files are added in
folder with name "dist_example_with_error"
Thank you msg356892 for spear heading this for me. I family things to attend to so I apologize for opening this bug report and then walking away..
As far as recreating this issue. It simple to do. you can either use cython or you can put together a quick script that will make say 150 extensions. put one line of code in it and compile it.. The results always end up being the same 123 extensions can be loaded on the 124th a TB happens.. It does not matter where the files are inside the package. it is always the 124th one that gets loaded for any one package. importing a pyd from another package does not change the number. The extensions have to be a direct descendant of one single package.
I haven't looked into _why_ yet, but the first PYD I grabbed from the GitHub link above has had the CRT statically linked. This is not the default (or it should not be), because when we made it the default this exact issue occurred :)
If somehow the default linking mode in distutils has changed, we should fix that. If it is being overridden by Setuptools or Cython then we should get those projects fixed.
Stefan/Paul - do Cython or Setuptools override compiler/linker settings like this at all? Most likely it's the /MT vs /MD option
Cython doesn't interfere with the C compiler setup in any way, that's left
to distutils/setuptools (and the user).
I have a similar issue. Do we have an estimate how long it may take to fix this bug? Thanks. I can help but would need some mentoring.
Okay, looking at _find_vcvarsall in distutils, I'm guessing that something about how your machines are set up means that the vcredist search is failing.
First, could you specify which versions of Visual Studio you have installed, and if possible which one is being found and used by your builds.
Then, if you can search your install to find both vcvarsall.bat and vcruntime140.dll (there will be a few of these) and post the paths, that may indicate if the layout isn't consistent.
Distutils will try and dynamically link to the runtime if you have the redist, and statically link it if you don't (though I don't remember why it doesn't just rely on the copy included with Python... probably future-proofing or licencing).
Thanks Steve. Here is what you requested.
xinfa@LAPTOP-71TBJKSA MINGW64 /c/Program Files (x86)/Microsoft Visual Studio
$ ./Installer/vswhere.exe
Visual Studio Locator version 2.7.1+180c706d56 [query version 2.3.2200.14893]
xinfa@LAPTOP-71TBJKSA MINGW64 /c/Program Files (x86)/Microsoft Visual Studio
$ find . -name "vcvarsall.bat"
./2019/BuildTools/VC/Auxiliary/Build/vcvarsall.bat
xinfa@LAPTOP-71TBJKSA MINGW64 /c/Program Files (x86)/Microsoft Visual Studio
$ find . -name "vcruntime140.dll"
./2019/BuildTools/VC/Redist/MSVC/14.24.28127/onecore/x64/Microsoft.VC142.CRT/vcruntime140.dll
./2019/BuildTools/VC/Redist/MSVC/14.24.28127/onecore/x86/Microsoft.VC142.CRT/vcruntime140.dll
./2019/BuildTools/VC/Redist/MSVC/14.24.28127/x64/Microsoft.VC142.CRT/vcruntime140.dll
./2019/BuildTools/VC/Redist/MSVC/14.24.28127/x86/Microsoft.VC142.CRT/vcruntime140.dll
./2019/BuildTools/VC/Tools/MSVC/14.24.28314/bin/Hostx64/x64/vcruntime140.dll
./2019/BuildTools/VC/Tools/MSVC/14.24.28314/bin/Hostx64/x86/vcruntime140.dll
./2019/BuildTools/VC/Tools/MSVC/14.24.28314/bin/Hostx86/x64/vcruntime140.dll
./2019/BuildTools/VC/Tools/MSVC/14.24.28314/bin/Hostx86/x86/vcruntime140.dll
./Installer/resources/app/ServiceHub/Services/Microsoft.VisualStudio.Setup.Service/vcruntime140.dll
./Installer/vcruntime140.dll
xinfa@LAPTOP-71TBJKSA MINGW64 /c/Program Files (x86)/Microsoft Visual Studio
I want mention that I have 301 extension modules. I used setuptools in my setup.py
from setuptools import setup
from setuptools.extension import Extension
python setup.py build_ext
python setup.py bdist_wheel
I bring the whl file to another computer, pip install, then launch the app and I get this error
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.
I tried using distutils instead, but it says: error: invalid command 'bdist_wheel'
from distutils.core import setup
from distutils.extension import Extension
You should be able to install "wheel" without setuptools to get the bdist_wheel command.
Can you confirm that the build process is actually using that Visual Studio install? If it's going through the regular distutils detection process then it ought to be finding the right files.
I have had wheel installed. Following this SO answer (), I added "import setuptools" before distutils (my setup.py attached).
Following is the log, where we see the VS path it is using. BTW, I am trying to reduce my package to <120 modules and test it.
(base) C:\Users\xinfa\Documents\code\ezcad-dev\beta>C:\Users\xinfa\AppData\Local\Continuum\anaconda3\python.exe setup.py build_ext
Include directory: C:\Users\xinfa\Documents\code\ezcad-dev\beta
Number of ext modules = 225
running build_ext
building 'ezcad.__main__' extension
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.24.28314\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -IC:\Users\xinfa\Documents\code\ezcad-dev\beta -I. -IC:\Users\xinfa\AppData\Loca
l\Continuum\anaconda3\include -IC:\Users\xinfa\AppData\Local\Continuum\anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.24.28314\include" "36
2.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\cppwinrt" /Tcezcad\__main__.c /Fobuild\temp.win-amd64-3.7\Release\ezcad\__main__.obj
__main__.c
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.24.28314\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /nodefaultlib:libucrt.lib ucrt.lib /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPAT
H:C:\Users\xinfa\AppData\Local\Continuum\anaconda3\libs /LIBPATH:C:\Users\xinfa\AppData\Local\Continuum\anaconda3\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.24.28314\l
ib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\um\x64" build\temp.win-amd64-3.7\Release\ezcad\__main__.obj /OUT:build\lib.win
-amd64-3.7\ezcad\__main__.cp37-win_amd64.pyd
Creating library build\lib.win-amd64-3.7\ezcad\__main__.cp37-win_amd64.lib and object build\lib.win-amd64-3.7\ezcad\__main__.cp37-win_amd64.exp
Generating code
Finished generating code
version = 0.1.9
FYI when I reduced my package to 106 extension modules, I could run without the DLL error.
Thanks, it does seem like it's finding the correct MSVC, but is not finding the redistributable DLL:
> cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT ...
The "/MT" means to statically the CRT, and then we use link settings later to dynamically link the part installed in the OS (see for more details).
The problem seems to be that this glob in distutils can't find the path listed below it:
"2019\BuildTools\VC\redist\MSVC\**\x64\Microsoft.VC14*.CRT\vcruntime140.dll"
"2019\BuildTools\VC\Redist\MSVC\14.24.28127\x64\Microsoft.VC142.CRT\vcruntime140.dll"
We swallow a lot of errors while doing this glob, so I assume there's something about your install that's affecting it (maybe related to it being BuildTools rather than Community or higher?)
Could you try running this code and see what result/error you get:
import glob
glob.glob(r"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\redist\MSVC\**\x64\Microsoft.VC14*.CRT\vcruntime140.dll", recursive=True)
Hmm, just ran it on my own and it's finding the OneCore file first, which is not a problem (yet) but could become one.
So we at least need to replace the "**" with a "*" in Lib/distutils/_msvccompiler.py#L109. Not sure if that will help in this other case or not.
In thinking about this, I think the best way forward is to just remove the logic that might statically link the initialization code, and instead commit to CPython releases always including vcruntime140.dll even if we switch to a newer version one day.
Hopefully third party distributions will do the same, though it should only matter for ABI3 modules that are not recompiled for the newer versions.
Steve, don't know if you still need it but here is what you requested. Sorry for the slow move (I was working on something else). Seems mine is finding the x64 before the OneCore, though I don't know the significance.
Python 3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)] on win32
In[2]: import glob
In[3]: glob.glob(r"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\redist\MSVC\**\x64\Microsoft.VC14*.CRT\vcruntime140.dll", recursive=True)
Out[3]:
['C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\redist\\MSVC\\14.24.28127\\x64\\Microsoft.VC142.CRT\\vcruntime140.dll',
'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\redist\\MSVC\\14.24.28127\\onecore\\x64\\Microsoft.VC142.CRT\\vcruntime140.dll']
> don't know if you still need it but here is what you requested.
Thanks. That basically confirms that something is interfering with distutils. Skipping the check entirely should avoid it.
New changeset ce3a4984089b8e0ce5422ca32d75ad057b008074 by Steve Dower in branch 'master':
bpo-38597: Never statically link extension initialization code on Windows (GH-18724)
New changeset 8a5f7ad5e423b74ea612e25472e5bff3adf1ea87 by Steve Dower in branch '3.7':
[3.7] bpo-38597: Never statically link extension initialization code on Windows (GH-18724) (GH-18759)
New changeset 0d20364b132014eec609b900997c34779a4d548c by Miss Islington (bot) in branch '3.8':
bpo-38597: Never statically link extension initialization code on Windows (GH-18724)
|
https://bugs.python.org/issue38597
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
Yo: diff --git a/tests/test-poll.c b/tests/test-poll.c index e8beb55..b65b7b3 100644 --- a/tests/test-poll.c +++ b/tests/test-poll.c @@ -139,16 +139,12 @@ connect_to_socket (int blocking) #endif } - if (connect (s, (struct sockaddr *) &ia, sizeof (ia)) < 0) + if (connect (s, (struct sockaddr *) &ia, sizeof (ia)) < 0 + && (blocking || errno != EINPROGRESS)) { - if (errno != EINPROGRESS) - { - perror ("connect"); - exit (77); - } + perror ("connect"); + exit (77); } - else if (!blocking) - failed ("huh, connect succeeded?"); return s; } I suppose you don't have similar build bots for Windows, do you? Paolo
|
http://lists.gnu.org/archive/html/bug-gnulib/2008-09/msg00165.html
|
CC-MAIN-2019-04
|
en
|
refinedweb
|
Process images in React with react-imgpro
In this lesson, we will cover a popular image processing component in the react eco-system for image processing.
The Library is react-imgpro.
Installation:
npm install --save react-imgpro
Include it as a module :
import ProcessImage from 'react-imgpro'
The documentation and the source files can be found here:
|
https://egghead.io/lessons/react-process-images-in-react-with-react-imgpro
|
CC-MAIN-2019-04
|
en
|
refinedweb
|
I have created new java application on Netbeans by pressing create new project and it creates java package. This fully fine ! When I add new JFrame it creates and automatically MAIN METHOD , after I am done with Matisse I mean putting some gui components , I want to add JDialog to that , I go on package right click and create JDialog Form which also created MAIN METHOD as well so itself. So both MAINS mixes up. this is confusing me all the time. My Aim is to create JMenuItem called new , when I click on it I want my JDialog to be appear and something like project creation dialog. Help please ! How to combine to different components in these situations ?
Regards
"this so confusing always , do have some examples "
I'm not so sure what is so confusing. Your program should only have one launching class with a
main method. Netbeans will create a
main method for you in
JDialog forms, so just delete the
main method. The only
main method you need is your main
JFrame form.
You have your
JDialog form
public class MyDialog extends javax.swing.JDialog { public MyDialog(final Frame parent, boolean modal) { super(parent, model); initComponents(); } private void initiComponent() { ... } // delete the auto-generated main method }
You have your JFrame form with
JMenuItem. Add a listener to the
JmenuItem to open the
MyDialog
public class MyFrame extends javax.swing.JFrame { private javax.swing.JMenuItem jMenuItem1; public MyFrame() { initComponents(); } /* Auto-generated code */ private void initComponents() { jMenuItem1 = new JMenuItem(); jMenuItem1.addActionListener(new java.awt.event.ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); } /* Auto-generated method */ private jmenuItemActionPerformed(java.awt.event.ActionEvent evt) { /* Your hand written code */ MyDialog dialog = new MyDialog(MyFrame.this, true); } public static void main(String[] args) { } }
" How to combine to different components in these situations ? "
What does that even mean?
Side Note
|
http://m.dlxedu.com/m/askdetail/3/cc85c233f4ac6bb8524631b974b44677.html
|
CC-MAIN-2019-04
|
en
|
refinedweb
|
BGE: passing arguments to __init__() when subclassing a KX_GameObject
Extending the KX_GameObject is a powerful way to add extra functionality to game objects. Once built, custom classes can speed up development while maintaining a tidy syntax. However, difficulties arise when trying to pass additional arguments to a subclass of the KX_GameObject. This tutorial looks at the various ways this can be overcome.
The problem
Lets’s take a simple character class as an example:
import bge own = bge.logic.getCurrentController().owner class character(bge.types.KX_GameObject): def __init__(self, own): self.stamina = 10 self.strength = 12 self.defense = 8 self.agility = 11 def printStats(self): print(self.stamina) print(self.strength) print(self.defence) print(self.agility) player = character(own)
What happens what when don’t want to hard-code values into the class but want to pass them when we create the object? For example:
class character(bge.types.KX_GameObject): def __init__(self, own, stamina, strength, defence, agility): self.stamina = stamina self.strength = strength self.defence = defence self.agility = agility player = character(own, 14, 13, 15, 7)
We get the error: “TypeError: Base PyObjectPlus() takes exactly 1 argument (5 given)”.
So long as we’re only passing the owner to a class that extends KX_GameObject we’ve got a co-operative inheritance tree and everything works as expected. But once our custom class and KX_GameObject has different __init__() signatures errors start to get raised. So how do we get around this? I’ll start by looking at some simple methods then move to the more complex or hackier ways of doing things.
Using 2 initialisers
The most straight forward method is to not try and pass any arguments to __init__() other than the owner and use a separate function to initialise our values:
class character2(bge.types.KX_GameObject): def __init__(self, own): # nothing happens here pass def initialise(self, stamina, strength, defence, agility): self.stamina = stamina self.strength = strength self.defence = defence self.agility = agility player = character2(own) player.initialise(8, 9, 12, 14)
However, we must ensure that own initialise() function is called before any other member function. If not, there is the potential for a member function to try and use variables that do not exist. The same applies if we try and subclass our custom class. If you were writing a library for the BGE and expecting users to extend the custom game object classes you’ve provided you’d need to make this clear to them.
Using keyword arguments
Another option is to have all the values you plan to use initialise in you __init__() definition, then pass them by name:
class character3(bge.types.KX_GameObject): def __init__(self, own, stamina, strength, defence, agility): self.stamina = stamina self.strength = strength self.defence = defence self.agility = agility player = character3(own, stamina=12, strength=10, defence=14, agility=9)
Passing values to custom classes is starting to look a little cleaner than our previous attempt. This method will work well when you’ve just got a couple of values to pass, but once you’ve got lots of values it’ll start to get a little ugly.
The other draw back is that it requires the class user to know the names of the variables they’re passing.
To tidy things up a little we could put all our values in a dictionary and then unpack it as a keyword argument:
stats = {'stamina' : 12, 'strength' : 11, 'defence' : 14, 'agility' : 15} player = character3(own, **stats)
In this particular example, having a dictionary for character stats is a reasonably tidy way to store and pass them. Plus it would make the easier to save/load (think configparser here). But for many other custom classes it wouldn’t make much sense. For instance, having lots of dicts for a particle class’s starting values. So lets move on.
Using a custom constructor
__init__() is not a class constructor, it simply initialises values for us. When creating classes in python it provides us with a default class constructor so that we don’t have to worry about it. But we can define our own when we need to by overriding __new__(). This allows us to control how a class is created and is called before __init__(), so we can control what variables get passed to our custom class’s base class:
class character4(bge.types.KX_GameObject): def __new__(cls, *args, **kwargs): return super().__new__(cls, own) def __init__(self, own, stamina, strength, defence, agility): self.stamina = stamina self.strength = strength self.defence = defence self.agility = agility player = character4(own, 8, 7, 15, 16)
Here, __new__() passes the owner onto to our KX_GameObject base class and prevents the other variables from being passed to KX_GameObject. Personally, I like this solution the most. It’s clean, only adds 2 more lines, and allows you pass arguments as you sorta would expect.
However, we’re move into the hackier solutions now. Overriding __new__() sits in the realm of python magic and has a lot of powerful effects (such as being able to return an entirely different object to the one being created). When there are other solutions available it might be best to avoid.
Using an adapter class
This method introduces another class to bridge the __init__() signature between a custom class and the KX_GameObject:
class gameObProxy(): def __init__(self, own): self.ob = bge.types.KX_GameObject(own) class character5(gameObProxy): def __init__(self, own, stamina, strength, defence, agility): super(character5, self).__init__(own) self.stamina = stamina self.strength = strength self.defence = defence self.agility = agility player = character5(own, 8, 7, 15, 16)
The proxy class holds the reference to the game object owner and our custom class is does not inherit directly from the KX_GameObject. When we initialise our custom class we deliberately call the proxy class’s initialiser so that we can pass the owner to it. This results in some interesting features. Firstly, inside the class to access KX_GameObject methods we need to go through the variable holding it first:
def move(self): self.ob.applyMovement(self.vec) # note, self.ob from the proxy class
Which means outside of the class we can’t access the KX_GameObject methods, without going through the variable holding the owner either. Now, there aren’t any private attributes in python. But lets pretend for a second that there are (say we called our holding variable self._ob to indicate it’s meant to be private). What this means is the custom class interface can provide the user only the functions the class was intended for, while obscuring the other KX_GameObject methods. For instance, if creating a custom particle class it could hide things like changing the dynamics or re-instancing the mesh, or something that might break the particle system.
Using a factory pattern
Rather than introduce another class into our inheritance tree, like the previous example. We can create a class who’s job it is to create classes. This class can then create an extended game object class and initialise values accordingly:
class characterCreator: @classmethod def make(cls, toMake, own, *args, **kwargs): if toMake == wizard: obj = toMake(own) obj.stamina = args[0] obj.strength = args[1] obj.defence = args[2] obj.agility = args[3] obj.intelligence = args[4] return obj if toMake == warrior: obj = toMake(own) obj.stamina = args[0] obj.strength = args[1] obj.defence = args[2] obj.agility = args[3] obj.rage = args[4] obj.armour = args[5] return obj else: return None class wizard(bge.types.KX_GameObject): def __init__(self, own): # there's nothing to do here # our factor takes care of this pass class warrior(bge.types.KX_GameObject): def __init__(self, own): # there's nothing to do here # our factor takes care of this pass player = characterCreator.make(wizard, own, 7, 6, 8, 9, 16)
Each time we want to create a new object we go through the factory rather than creating the object directly. This has the advantage of separating the class interface from the implementation. For example, say you have a particle class that stores a movement vector. That vector might want to be randomly determined, or within a particular range or a fixed value. Rather than bog the particle class down with a lengthy initialiser and interface we can let the factory handle that while keeping the particle class light-weight.
The above example is just a simple demonstration, there’s a lot we could do on object creation. Let’s say you’re using a factory pattern to create enemies, after initialising their values you could also run their climb out of the ground animation to get them started.
The other thing we can do with a factory method is register the created object to a container, so we can keep track of objects in play.
class characterCreator2: characterCreator.enemies = [] @classmethod def make(cls, toMake, own, *args, **kwargs): if toMake == spider: obj = toMake(own) obj.stamina = args[0] obj.strength = args[1] obj.defence = args[2] obj.agility = args[3] obj.intelligence = args[4] # keep track of added enemies characterCreator.enemies.append(obj) return obj ## add various other enemy types else: return None
Of course, you’ll then need to add some way to keep the list of registered objects up-to-date. One way is to have a delete/unregister method, so when an object is deleted it is done through the factory.
Wrapping up
This tutorial has covered a number of methods you can use to extend the KX_GameObject and work around problems initialising values. Which method is best will largely depend on what you are trying to do. If you’ve got a simple class with a few parameters, probably use key words. If you’re creating lots of objects, you may wish to use a factory. If you want to provide a very particular interface, then go with an adapter class. If you’ve got a class with a number of parameters, then it may be tidier to override the constructor. And I can’t think of a reason to use 2 initialisers when there are better solutions.
If you’ve got any other ways to pass multiple parameters to __init__() when extending the KX_GameObject leave them in the comments below. And remember to like and follow!
|
https://whatjaysaid.wordpress.com/2015/02/01/bge-passing-arguments-to-__init__-when-subclassing-a-kx_gameobject/
|
CC-MAIN-2019-04
|
en
|
refinedweb
|
Process Process Process Process Class
Definition
Provides access to local and remote processes and enables you to start and stop local system processes.
public ref class Process : System::ComponentModel::Component
public class Process : System.ComponentModel.Component
type Process = class inherit Component
Public Class Process Inherits Component
- Inheritance
-
Examples
The following example uses an instance of the Process class to start a process.
#using <System.dll> using namespace System; using namespace System::Diagnostics; using namespace System::ComponentModel; int main() { Process^ myProcess = gcnew ); } }
using System; using System.Diagnostics; using System.ComponentModel; namespace MyProcessSample { class MyProcess { public static void Main() { try { using (Process myProcess = new Process()) {); } } } }
Imports System Imports System.Diagnostics Imports System.ComponentModel Namespace MyProcessSample Class MyProcess Public Shared Sub Main() Dim myProcess As e As Exception Console.WriteLine((e.Message)) End Try End Sub 'Main End Class End Namespace
The following example uses the Process class itself and a static Start method to start a process.
(); }(); } } }
Imports System.Diagnostics Imports System.ComponentModel Namespace MyProcessSample Class MyProcess ' Opens the Internet Explorer application. Public Sub OpenApplication(myFavoritesPath As String) ' Start Internet Explorer. Defaults to the home page. Process.Start("IExplore.exe") ' Display the contents of the favorites folder in the browser. Process.Start(myFavoritesPath) End Sub 'OpenApplication ' Opens urls and .html documents using Internet Explorer. ' Uses the ProcessStartInfo class to start new processes, ' both in a minimized mode. Sub OpenWithStartInfo() Dim startInfo As New ProcessStartInfo("IExplore.exe") startInfo.WindowStyle = ProcessWindowStyle.Minimized Process.Start(startInfo) startInfo.Arguments = "" Process.Start(startInfo) End Sub 'OpenWithStartInfo
The code for the
runProc function was written by ImaginaryDevelopment and is available under the Microsoft Public License.
Remarks/
finally block. To dispose of it indirectly, use a language construct such as
using (in C#) or
Using (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.
Note
32-bit processes cannot access the modules of a 64-bit process. If you try to get information about a 64-bit process from a 32-bit process, you will get a Win32Exception exception. A 64-bit process, on the other hand, can access the modules of a 32-bit process..
Note
This class contains a link demand and an inheritance demand at the class level that applies to all members. A SecurityException is thrown when either the immediate caller or the derived class does not have full-trust permission. For details about security demands, see Link Demands.
.NET Core Notes
In the .NET Framework,.
Constructors
Properties
Methods
Events
Security
LinkDemand
for full trust for the immediate caller. This class cannot be used by partially trusted code.
InheritanceDemand
for full trust for inheritors. This class cannot be inherited by partially trusted code.
|
https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process?redirectedfrom=MSDN&view=netframework-4.7.2
|
CC-MAIN-2019-04
|
en
|
refinedweb
|
Bootstrap and Closest Peak Direction Getters Example¶
This example shows how choices in direction-getter impact fiber tracking results by demonstrating the bootstrap direction getter (a type of probabilistic tracking, as described in [Berman2008]) and the closest peak direction getter (a type of deterministic tracking). (Amirbekian, PhD thesis, 2016)
Let’s load the necessary modules for executing this tutorial.
from dipy.data import read_stanford_labels from dipy.tracking import utils from dipy.tracking.local import (ThresholdTissueClassifier, LocalTracking) from dipy.io.streamline import save_trk from dipy.viz import window, actor, colormap as cmap renderer = window.Renderer()
Now we import the CSD model
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
First we load our images and establish seeds. See the Introduction to Basic Tracking tutorial for more background on these steps.)
Next, we fit the CSD model
csd_model = ConstrainedSphericalDeconvModel(gtab, None, sh_order=6) csd_fit = csd_model.fit(data, mask=white_matter)
we use the CSA fit to calculate GFA, which will serve as our)
Next, we need to set up our two direction getters
Example #1: Bootstrap direction getter with CSD Model
from dipy.direction import BootDirectionGetter from dipy.tracking.streamline import Streamlines from dipy.data import small_sphere boot_dg_csd = BootDirectionGetter.from_data(data, csd_model, max_angle=30., sphere=small_sphere) boot_streamline_generator = LocalTracking(boot_dg_csd, classifier, seeds, affine, step_size=.5) streamlines = Streamlines(boot_streamline_generator) renderer.clear() renderer.add(actor.line(streamlines, cmap.line_colors(streamlines))) window.record(renderer, out_path='bootstrap_dg_CSD.png', size=(600, 600))
Corpus Callosum Bootstrap Probabilistic Direction Getter
We have created a bootstrapped probabilistic set of streamlines. If you repeat the fiber tracking (keeping all inputs the same) you will NOT get exactly the same set of streamlines. We can save the streamlines as a Trackvis file so it can be loaded into other software for visualization or further analysis.
save_trk("bootstrap_dg_CSD.trk", streamlines, affine, labels.shape)
Example #2: Closest peak direction getter with CSD Model
from dipy.direction import ClosestPeakDirectionGetter pmf = csd_fit.odf(small_sphere).clip(min=0) peak_dg = ClosestPeakDirectionGetter.from_pmf(pmf, max_angle=30., sphere=small_sphere) peak_streamline_generator = LocalTracking(peak_dg, classifier, seeds, affine, step_size=.5) streamlines = Streamlines(peak_streamline_generator) renderer.clear() renderer.add(actor.line(streamlines, cmap.line_colors(streamlines))) window.record(renderer, out_path='closest_peak_dg_CSD.png', size=(600, 600))
Corpus Callosum Closest Peak Deterministic Direction Getter
We have created a set of streamlines using the closest peak direction getter, which is a type of deterministic tracking. If you repeat the fiber tracking (keeping all inputs the same) you will get exactly the same set of streamlines. We can save the streamlines as a Trackvis file so it can be loaded into other software for visualization or further analysis.
save_trk("closest_peak_dg_CSD.trk", streamlines, affine, labels.shape)
tractography using the residual bootstrap, NeuroImage, vol 39, no 1, 2008
Example source code
You can download
the full source code of this example. This same script is also included in the dipy source distribution under the
doc/examples/ directory.
|
http://nipy.org/dipy/examples_built/tracking_bootstrap_peaks.html
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Create a Business Service with Node.js using Visual Studio Code
04/25/2019
You will learn
- How to do develop a sample business service using the SAP Cloud Application Programming Model and
Node.js
- Define a simple data model and a service that exposes the entities you created in your data model
- Run your service locally
- Deploy the data model to an
SQLitedatabase
- Add custom handlers to serve requests that are not handled automatically
Before you start, make sure you have completed the prerequisites.
Configure the NPM registry by executing the following command:
npm set @sap:registry=
Install the CDS command-line tools by executing the following command:
npm i -g @sap/cds
This installs the
cdscommand, which we will use in the next steps.
To verify the installation was successful, run
cdswithout arguments:
cds
This lists the available
cdscommands. For example, use
cds versionto check the version you have installed.
Go to SAP Development Tools and download the CDS extension (
vsixfile) for Visual Studio Code.
Install the extension in Visual Studio Code:
And look for the
vsixfile you downloaded.
If you see a compatibility error, make sure you have the latest version of VS Code.
Open a command line window and run the following command in a folder of your choice:
cds init my-bookshop
This creates a folder
my-bookshopin the current directory.
Open VS Code, go to File | Open Folder and choose the
my-bookshopfolder.
You will create a simplistic all-in-one service definition.
In VS Code, choose the New File icon and type
srv/cat-service.cds.
This creates a folder called
srvand a file called
cat-service.cds.
Open the file and add the following code:
using { Country, managed } from '@sap/cds/common'; service CatalogService { entity Books { key ID : Integer; title : localized String; author : Association to Authors; stock : Integer; } entity Authors { key ID : Integer; name : String; books : Association to many Books on books.author = $self; } entity Orders : managed { key ID : UUID; book : Association to Books; country : Country; amount : Integer; } }
Save your file.
Run your service locally. In the
my-bookshopfolder, execute:
cds run
To test your service, go to.
You won’t see data, because you have not added a data model yet. However, click on the available links and confirm the service is running.
To stop the service and go back to your project directory, press
CTRL+C.
Add service provider logic to return mock data.
In the
srvfolder, create a new file called
cat-service.js.
Add the following code:
module.exports = (srv) => { // Reply mock data for Books... srv.on ('READ', 'Books', ()=>[ { ID:201, title:'Wuthering Heights', author_ID:101, stock:12 }, { ID:251, title:'The Raven', author_ID:150, stock:333 }, { ID:252, title:'Eleonora', author_ID:150, stock:555 }, { ID:271, title:'Catweazle', author_ID:170, stock:222 }, ]) // Reply mock data for Authors... srv.on ('READ', 'Authors', ()=>[ { ID:101, name:'Emily Brontë' }, { ID:150, name:'Edgar Allen Poe' }, { ID:170, name:'Richard Carpenter' }, ]) }
Save the file.
Run the
CatalogServiceagain:
cds run
To test your service, click on these links:
You should see the mock data you added for the Books and Authors entities.
To stop the service and go back to your project directory, press
CTRL+C.
To get started quickly, you have already added a simplistic all-in-one service definition. However, you would usually put normalized entity definitions into a separate data model and have your services expose potentially de-normalized views on those entities.
Choose New File and type
db/data-model.cds.
This creates a folder called db and a file called
data-model.cds. Your project structure should look like this:
Add the following code to the
data-model.cdsfile:
namespace my.bookshop; using { Country, managed } from '@sap/cds/common'; entity Books { key ID : Integer; title : localized String; author : Association to Authors; stock : Integer; } entity Authors { key ID : Integer; name : String; books : Association to many Books on books.author = $self; } entity Orders : managed { key ID : UUID; book : Association to Books; country : Country; amount : Integer; }
Open
cat-service.cdsand replace the code with:
using my.bookshop as my from '../db/data-model'; service CatalogService { entity Books @readonly as projection on my.Books; entity Authors @readonly as projection on my.Authors; entity Orders @insertonly as projection on my.Orders; }
Remember to save your files.
The
cds runtime includes built-in generic handlers that automatically serve all CRUD requests. After installing
SQLite3 packages, you can deploy your data model.
Install
SQLite3packages
npm i sqlite3 -D
Deploy the data model to an
SQLitedatabase:
cds deploy --to sqlite:db/my-bookshop.db
You have now created an
SQLitedatabase file under
db/my-bookshop.db.
This configuration is saved in your
package.jsonas your default data source. For subsequent deployments using the default configuration, you just need to run
cds deploy.
Open
SQLiteand view the newly created database:
sqlite3 db/my-bookshop.db -cmd .dump
If this does not work, check if you have SQLite installed. On Windows, you might need to enter the full path to SQLite, for example:
C:\sqlite\sqlite3 db\my-bookshop.db -cmd .dump.
To stop
SQLiteand go back to the your project directory, press
CTRL+C.
Add plain CSV files under
db/csv to fill your database tables with initial data.
In the
dbfolder, choose New File and enter
csv/my.bookshop-Authors.csv. Add the following to the file:
ID;name 101;Emily Brontë 107;Charlote Brontë 150;Edgar Allen Poe 170;Richard Carpenter
In the
dbfolder, choose New File and enter
csv/my.bookshop-Books.csv. Add the following to the file:
ID;title;author_ID;stock 201;Wuthering Heights;101;12 207;Jane Eyre;107;11 251;The Raven;150;333 252;Eleonora;150;555 271;Catweazle;170;22
Make sure you now have a folder hierarchy
db/csv/.... And remember that the
csvfiles must be named like the entities in your data model and must be located inside the
db/csvfolder.
Your service is now backed by a fully functional database. This means you can remove the mock data handlers from
cat-service.js and see the generic handlers shipped with the SAP Cloud Application Programming Model in action.
Remove the code with mock data in
cat-service.js, because we want to see the actual data coming from the database.
Deploy the data model again to add your initial data:
cds deploy
Run the service again:
cds run
To test your service, open a web browser and go to:
You should see a book titled Jane Eyre. If this is not the case, make sure you have removed the mock data from
cat-service.jsas indicated above.
Download the Postman application.
Note that you can use any other HTTP client than Postman.
Click on the following link and save the file to a folder of your choice:
postman.json.
In the Postman app, use the Import button in the toolbar:
Choose Import from File in the wizard. Click on Choose Files and select the file that you saved before.
In the imported collection, execute the various requests in the
metadataand
CRUDgroups. They should all return proper responses.
Note that with our current service implementation, we can get only POST orders. Any GET or DELETE to an order will fail, since we have specified the
Ordersentity to be
@insertonlyin
srv/cat-service.cds.
Add the following code in the
srv/cat-service.jsfile:
module.exports = (srv) => { const {Books} = cds.entities ('my.bookshop') // Reduce stock of ordered books srv.before ('CREATE', 'Orders', async (req) => { const order = req.data if (!order.amount || order.amount <= 0) return req.error (400, 'Order at least 1 book') const tx = cds.transaction(req) const affectedRows = await tx.run ( UPDATE (Books) .set ({ stock: {'-=': order.amount}}) .where ({ stock: {'>=': order.amount},/*and*/ ID: order.book_ID}) ) if (affectedRows === 0) req.error (409, "Sold out, sorry") }) // Add some discount for overstocked books srv.after ('READ', 'Books', each => { if (each.stock > 111) each.title += ' -- 11% discount!' }) }
Whenever orders are created, this code is triggered. It updates the book stock by the given amount, unless there are not enough books left.
Run your service:
cds run
In Postman, execute the
GET Booksrequest.
Take a look at the stock of book
201.
Execute one of the
POST Ordersrequests.
This will trigger the logic above and reduce the stock.
Execute the
GET Booksrequest again.
The stock of book
201is lower than before.
Prerequisites
- You have installed Node.js version 8.9 or higher.
- You have installed the latest version of Visual Studio Code.
- (For Windows users only) You have installed the
SQLitetools for Windows.
- Step 1: Set up your local development environment
- Step 2: Install Visual Studio Code Extension
- Step 3: Start a project
- Step 4: Define your first service
- Step 5: Provide mock data
- Step 6: Add a data model and adapt your service definition
- Step 7: Add a Database
- Step 8: Add initial data
- Step 9: Test generic handlers with Postman
- Step 10: Add custom logic
- Back to Top
|
https://developers.sap.com/korea/tutorials/cp-apm-nodejs-create-service.html
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Library: XML
Package: DOM
Header: Poco/DOM/NamedNodeMap.h
Description.
A NamedNodeMap returned from a method must be released with a call to release() when no longer needed.
Inheritance
Direct Base Classes: DOMObject
All Base Classes: DOMObject
Known Derived Classes: DTDMap, AttrMap
Member Summary
Member Functions: getNamedItem, getNamedItemNS, item, length, removeNamedItem, removeNamedItemNS, setNamedItem, setNamedItemNS
Inherited Functions: autoRelease, duplicate, release
Destructor
~NamedNodeMap
virtual ~NamedNodeMap();
Member Functions
getNamedItem
virtual Node * getNamedItem(
const XMLString & name
) const = 0;
Retrieves a node specified by name.
getNamedItemNS
virtual Node * getNamedItemNS(
const XMLString & namespaceURI,
const XMLString & localName
) const = 0;
Retrieves a node specified by name.
item
virtual Node * item(
unsigned long index
) const = 0;
Returns the index'th item in the map. If index is greater than or equal to the number of nodes in the map, this returns null.
length
virtual unsigned long length() const = 0;
Returns the number of nodes in the map. The range of valid child node indices is 0 to length - 1 inclusive.
removeNamedItem
virtual Node * removeNamedItem(
const XMLString & name
) = 0;
Removes a node specified by name. When this map contains the attributes attached to an element, if the removed attribute is known to have a default value, an attribute immediately appears containing the default value.
removeNamedItemNS
virtual Node * removeNamedItemNS(
const XMLString & namespaceURI,
const XMLString & localName
) = 0;
Removes a node specified by name.
setNamedItem
virtual Node * setNamedItem(
Node * arg
) = 0;
Adds a node using its nodeName attribute. If a node with that name is already present in this map, it is replaced by the new one..
setNamedItemNS
virtual Node * setNamedItemNS(
Node * arg
) = 0;
|
https://pocoproject.org/pro/docs/Poco.XML.NamedNodeMap.html
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
My rendering code is now ported to .Net Standard 2.0 assemblies for portability.
Next step is to consume said assemblies in a Xamarin Android app.
However I do not seem to be able to consume for example the System.Drawing.Graphics type in my Xamarin code, even though I have added a reference to the System.Drawing.Common package.
Am I attempting the impossible? Must anything System.Drawing.Common be completely encapsulated in my .NET Standard assemblies? Or is there a viable workaround?
Answers
Xamarin use Mono instead of
.Net, the difference between them should be clear.
Monocode and .Net are almost identical, they can even be compatible with each other (.net library can be mono-referenced and used), but
Monois a separate cross-platform library. You could refer to the document:. Not all the
.Netcode could be used in
Mono.
System.Drawing.Graphicsdoes not exist in Xamarin, as it conflict with
Android.Graphics. You could use
Android.Graphicsin
Xamarin.Androidinstead.
@YorkGo - thanks for the tip, but Xamarin.Android is not portable code. The whole point (for me) of going to .Net Standard and accompanying System.Drawing.Common package is to have portable rendering code, for all platforms supported by .Net Standard. Note - this is imaging, not UI.
Install the
System.Drawing.Commonnuget package for your portable library should be work.
@YorkGo once again appreciate the tip. That was my thinking too, but System.Drawing.Graphics is not resolved even with System.Drawing.Common package added.
My conclusion is that it seems to not be possible to reference any symbols in the System.Drawing.Common assembly from my Xamarin code. And that's really what my question is about - should it be possible? Is there a workaround? Is what I am seeing a .Net Standard problem, or a Xamarin problem? Or am I making a user error?
FYI: As far as I can tell the System.Drawing namespace also exists in the Mono.Android assembly. All System.Drawing classes I can reference (Color, Point, PointF, Rectangle, RectangleF, Size, SizeF) originate in the Mono.Android assembly.
For anyone attempting to reproduce... my projects:
.Net Standard 2.0 assembly, that references System.Drawing.Common package, and exposes System.Drawing.Graphics as a parameter in an abstract class. This assembly builds fine. Currently building for x86, not sure if it matters at this stage.
Xamarin Android class library that references the above assembly, and System.Drawing.Common package, and subclasses the abstract class above:
VS2017 class view for the Xamarin project shows no symbols in the System.Drawing.Common project reference. In the .Net Standard project, all System.Drawing symbols are visible in the class view.
Additionally I see a NuGet error:
NU1201 Project mochro.android is not compatible with netstandard2.0 (.NETStandard,Version=v2.0). Project mochro.android supports: monoandroid81 (MonoAndroid,Version=v8.1)
I guess that confirms lack of compatibility.
Found this doc page that sheds some light on the situation. Not sure yet to what degree it is relevant.
After some research I concluded that this is due to a problem in the net core. System.Drawing.Common.dll should be present in my deployed app folder on Android, but it's not. Manually adding it seemingly eliminates the symptom (but exposes another symptom).
The bug report is here:
Solution seems to be targeted for .Net Standard 3.0.
I finally got PlatformNotSupportedException from System.Drawing.Common.dll.
Pretty clear sign. I have to write my own rendering primitives if I want portable code.
|
https://forums.xamarin.com/discussion/comment/363099/
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Markowitz Portfolio Optimization in Python
Tutorial on the basic idea behind Markowitz portfolio optimization and how to do it with Python and plotly.
About the authors: Dr. Thomas Starke, David Edwards, Dr. Thomas Wiecki Today's blog post is written in collaboration with Dr. Thomas Starke. It is based on a longer whitepaper by Thomas Starke on the relationship between Markowitz portfolio optimization and Kelly optimization. The full whitepaper can be found here.
Introduction¶¶
import plotly import cufflinks plotly.__version__
'1.4.7'
# (*) To communicate with Plotly's server, sign in with credentials file import plotly.plotly as py # (*) Useful Python/Plotly tools import plotly.tools as tls # (*) Graph objects to piece together plots from plotly.graph_objs import *)
fig = plt.figure() plt.plot(return_vec.T, alpha=.4); plt.xlabel('time') plt.ylabel('returns') py.iplot_mpl(fig, filename='s6_damped_oscillation') some:$$ R = p^T w $$
where $R$ is the expected return, $p^T$ is the transpose of the vector for the mean
returns for each time series and w is the weight vector of the portfolio. $p$ is a Nx1
column vector, so $p^T$$$\sigma = \sqrt{w^T C w}$$
where $C$.
fig = plt.figure() plt.plot(stds, means, 'o', markersize=5) plt.xlabel('std') plt.ylabel('mean') plt.title('Mean and standard deviation of returns of randomly generated portfolios') py.iplot_mpl(fig, filename='mean_std', strip_style=True)
/home/wiecki/envs/zipline_p14/local/lib/python2.7/site-packages/plotly/matplotlylib/renderer.py:514: UserWarning: Looks like the annotation(s) you are trying to draw lies/lay outside the given figure size. Therefore, the resulting Plotly figure may not be large enough to view the full text. To adjust the size of the figure, use the 'width' and 'height' keys in the Layout object. Alternatively, use the Margin object to adjust the figure's margins.
Markowitz optimization and the Efficient Frontier¶
Once we have a good representation of our portfolios as the blue dots show we can calculate the efficient frontier Markowitz-style. This is done by minimising$$ w^T C w$$
for $w$ on the expected portfolio return $R^T w$ whilst keeping the sum of all the weights equal to 1:$$ \sum_{i}{w_i} = 1 $$
Here we parametrically run through $R^T w = \mu$ and find the minimum variance
for different $\mu $\mu$) fig = plt.figure() plt.plot(stds, means, 'o') plt.ylabel('mean') plt.xlabel('std') plt.plot(risks, returns, 'y-o') py.iplot_mpl(fig, filename='efficient_frontier', strip_style=True)'].iplot(filename='prices', yTitle='price in $', world_readable=True, asDates=True) (add_history, ''' # Register history container to keep a window of the last 100 prices. add_history(100, '1d', 'price') #.iplot(filename='algo_perf', yTitle='Cumulative capital in $', world_readable=True, asDates=True)
[2015-03-02 09:52] INFO: Performance: Simulated 2411 trading days out of 2411. [2015-03-02 09:52] INFO: Performance: first open: 2005-08-01 13:31:00+00:00 [2015-03-02 09:52] INFO: Performance: last close: 2015-02-27 21:00:00+00:00 post,!
|
https://plot.ly/ipython-notebooks/markowitz-portfolio-optimization/
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
1. ) What is structure in C#.
3. ) How does define structure in.
- Structure are created more quickly than heap -allocated.
- Structures are automatically deallocated ,when it go the out of the scope.
- Structures are value type so that we can easily copy value type variables on the stack memory.
Syntax:-
struct structure_name
{
data-member 1;
data-member 2;
data-member 3;
.
.
.
}
struct Employee
{
public string Name;
public int e-id;
public money salary;
}
Employee e1;
4. ) How does assign the values in structure's member in C#?
e1. Name = 'Ram';
e1. e-id = 101;
e1. salary = 2000;
5. ) How does copy values from one structure to another structure in C#?
When we create object of any structure class,the data member of that structure automatic comes in memory.So if we want to copy values from one structure to another structure then we have to assigned the one structure's object to another structure's object.Which is given below:
Ex.
Employee e1 ;
Employee e2 ;
e1 = e2; (structure second copied to first structure)
6. )Does Structure members private by default in C#?
Yes, Structure members are private by default in C#.We can not access private member from the outside using dot operator.
7. )How can we use constructor and method in C# program?
using System; namespace ConsoleApplication6 { class Program { struct rectangle { int x,y; public rectangle(int a, int b) //Constructor { x = a; y = b; } public void Area() // method { Console.WriteLine("area of rectangle is: "); Console.WriteLine(x*y); } } static void Main(string[] args) { rectangle rect = new rectangle(20,30); rect.Area(); Console.ReadLine(); } } }
Output:-
8. ) Can we use Nested Structures in C# ?
Yes.
9. )What is difference between Structure and Class in C# ?
More Details..
10. )Does C# support parameter less constructor by default ?
No, C# does not support parameter less constructor.
11. )What is Enumeration in C# ?
An Enumeration is an user-defined integer type,which is used for attaching names to Numbers .We use enum keyword for Enumeration in C#.
12. )What is the Syntax Enumeration in C# ?
Syntax:-
enum {value 1,value 2,value 3, ........value n}
Ex.
enum Days {mon,tue,wed,thu,fri,sat,sun}
Zero(0)
14. )How does assign values in enum member manually in C# ?
enum color
{
white =1;
red=2;
blue=3;
green=4;
}
15. )What is the type of an enum by default in C# ?
int
16. )How can we declare explicitly a base type for each enum in C# ?
The valid base types are:-
byte, sbyte, short, ushort, int ,uint , long , ulong
Ex.
enum shape : long
{
rectangle ;
square ;
triangle =100;
circle;
}
Note:-The value assigned to the members must be within the range of values that can be represented by the base type in C#,Means we can assign value in enum members within range of base type.
17. )What is type conversion in Enumeration in C# ?
enum type can be converted to their base type.we can use explicit conversion to convert back using Cast function.
Ex.
enum number
{
value 0,
value 1,
value 2,
}
number n = (number) 1;
int x = int (int)n;
.................................
Note:- Literal values can be converted to an enum type without any cast.
18. )Can i use Implicit and Explicit conversion in Enumerator ?
Yes.
19. )When do we prefer the use of structs over class?
We do not prefer structure if it satisfied the following statement which are given below:
- For represent a single value.
- size is smaller than 16 byte.
- immutable
- for boxing
Constructors are basically used for initialization of the data members in the structure .
|
http://www.msdotnet.co.in/2013/07/structures-and-enumerations-questions.html
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Hedge funds and mutual funds are both “pooled” vehicles, but there are more differences
than similarities. For instance, a mutual fund is registered with the SEC, and can be sold
to an unlimited number of investors.
Most hedge funds are not registered and can only be sold to carefully defined sophisticated
investors. Usually a hedge fund will have a maximum of either 100 or 500. If he changes
his strategy, he will be accused of “style drift”.
Paperwork – a mutual fund is offered via a prospectus; a hedge fund is offered via the
private placement memorandum.
Liquidity – the mutual fund often offers daily liquidity (you can withdraw at any time); the
hedge fund usually has some sort of “lockup” provision. You can only get your money
periodically.
Absolute vs. Relative – the hedge fund aims for absolute return (it wants to produce
positive returns regardless of what the market is doing); the mutual fund is usually
managed relative to an index benchmark and is judged on its variance from that
benchmark.
Self-Investment – the hedge fund manager is expected to put some of his own capital at
risk in the strategy. If he does not, it can be interpreted as a bad sign. The mutual fund
does not face this same expectation.
42.Is investment banking a good career for someone who is afraid of taking risks? Why
or why not?.”
43.Should financial institutions be regulated in order to reduce their risk? Offer at least
one argument for regulation and one argument against regulation.
Regulation maybe able to reduce failures of financial institutions, which may stabilize the
financial system. The flow of funds into financial institutions will be larger if the people
who provide the funds can trust that the financial institutions will not fail. However,
regulation can also restrict competition. In some cases, it results in subsidies to financial
institutions that are performing poorly. Thus, regulation can prevent firms from operating
efficiently
44.When a securities firm serves as an underwriter for an IPO, is the firm working for
the issuer or the institutional investors that may purchase shares? Explain the
dilemma.
a securities firm attempts to satisfy the issuer of stock by ensuring that the price is suffiently
high, but it must also ensure that it can place all the shares. It also wants to satisfy the
investors who invest in the IPO. If the investors incur losses because they paid too much
for the shares, they may not want to purchase any more stock from that underwriter in the
future.
TUTORIAL 5
45. Discuss alternative measures of financial leverage. Should the market value of
equity be used or the book value? Is it better to use the market value of debt or the
book value? How should you treat off-balance-sheet obligations such as pension
liabilities? How would you treat preferred stock?
CHƯA TÌM ĐƯỢC ĐÁP ÁN.
46. In general, the principles of cash cycle time management call for a firm to shorten
(minimise) the time it takes to collect receivables, and lengthen (maximise) the time it
takes to pay amounts it owes to suppliers. Explain what tradeoffs need to be managed if
the firm offers discounts to customers who pay early, and the firm also foregoes
discounts offered by its suppliers by extending the time until it pays invoices.
By offering the discount to customers for early payment, the firm is shortening its receivables
period, but also giving away some money in form of discount. By waiting to pay its suppliers,
the firm is extending its payables period, but the net effect is to spend more money than is
necessary to resolve open invoices. A question to be asked: Is the firm earning more by
holding its money over the period between when the discount is forgone and the total invoice
from the supplier come due, than it is incuring in the form of the implicit interest charge by
paying later? Or is there some cases which at a persent time calls for the retention of cash for
as long as possible.
|
https://pl.scribd.com/document/378256427/ACFrOgAhRu3-yERcQoDLYPHYK7EEol-R060siAYiiZPhoacWvW2ehxtFcVTUU05T-1sHkRSrROCayVLJHEfrJrI5CEsSGKQH2qPOWneLQ2fkycu54gCEJdMK7B91aWw
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Serving Static Files
It’s often useful to load static files like images and videos when creating components and stories.
Storybook provides two ways to do that.
1. Via Imports1. Via Imports
You can import any media assets by simply importing (or requiring) them as shown below.
import React from 'react'; import { storiesOf } from '@storybook/react'; import imageFile from './static/image.png'; const image = { src: imageFile, alt: 'my image', }; storiesOf('<img />', module) .add('with an image', () => ( <img src={image.src} alt={image.alt} /> ));
This is enabled with our default config. But, if you are using a custom Webpack config, you need to add the file-loader into your custom Webpack config.
2. Via a Directory2. Via a Directory
You can also configure a directory (or a list of directories) for searching static content when you are starting Storybook. You can do that with the -s flag.
See the following npm script on how to use it:
{ "scripts": { "start-storybook": "start-storybook -s ./public -p 9001" } }
Here
./public is our static directory. Now you can use static files in the public directory in your components or stories like this.
import React from 'react'; import { storiesOf } from '@storybook/react'; const imageAlt = 'my image'; // assume image.png is located in the "public" directory. storiesOf('<img />', module) .add('with a image', () => ( <img src="/image.png" alt={imageAlt} /> ));
You can also pass a list of directories separated by commas without spaces instead of a single directory.
{ "scripts": { "start-storybook": "start-storybook -s ./public,./static -p 9001" } }
3. Via a CDN3. Via a CDN
Upload your files to an online CDN and just reference them. In this example we’re using a placeholder image service.
import React from 'react'; import { storiesOf } from '@storybook/react'; storiesOf('<img />', module) .add('with a image', () => ( <img src="" alt="My CDN placeholder" /> ));
Absolute versus relative pathsAbsolute versus relative paths
Sometimes, you may want to deploy your storybook into a subpath, like.
In this case, you need to have all your images and media files with relative paths. Otherwise, Storybook cannot locate those files.
If you load static content via importing, this is automatic and you do not have to do anything.
If you are using a static directory, then you need to use relative paths to load images.
|
https://storybook.js.org/docs/configurations/serving-static-files/
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
My mother loves to cross-stitch and crochet. Her biggest problem is finding the right patterns for what she needs to do. I've seen her buy dozens of books with patterns as well as have my brother draw on grid paper a unique design. Many of the images are easy to find with a quick Google search, so I set out to take a jpeg from a Google Image search and turn it into a cross-stitch of crochet pattern for my mother!
The way I did this is with a JAVA program, however, besides reading/writing the image, I used all basic primitives so anyone could easily take what I've done and do it in their own language. The full source code is available here to download and use or translate.
Step 1: Take the Input Parameters
This is meant to take in a jpeg. This part has some fairly JAVA specific methods, but to port it to your language of choice should be trivial. Here we receive the input parameters, verify the input image exists and make sure we can create the output file.
Step 2: Example Image
For our testing, we will be making a cross-stitch ready pattern of the Instrucable mascot!
Step 3: Scaling the Image Down
The above code will take our rather large image of the mascot and resize it to the user specified dimensions. This results in a very tiny image. This very tiny image isn't very useful, but this is the resolution that we want. To make it useful, we now have to size it back up but make it seem as we're staying at this low resolution!
Step 4: Scale the Image Back Up
Now we take our very small image, and we're going to re-produce each pixel 10 times in the X and Y direction. Then in between each of these 10x10 scaled up versions of our pixel, we're going to put a black line. This will give us our cross-stitch template effect!
Once that is done, you can write your image out and use it!
Step 5: Example Cross-stitch Pattern!
And here are some example patterns that I've made!
Step 6: A Note on Aspect Ratio
To use this effectively, when inputting your output dimensions try to preserve the aspect ratio or width / height as close as possible. Sometimes to fit a specific template, you're forced to smush a bit, but try to stay close.
For example, the input Batman image is 200 pixels wide, and 120 pixels height. It's wider than taller. So, when re-scaling it, I chose 50 pixels wide, by 30 pixels height. I just divided both sides by the same amount, and the result looks great. However, above you can see when I choose 50x50, changing the aspect ratio, makes the symbol looked squish compared to the original!
13 Discussions
4 years ago
This would work great for making perler bead patterns too. Thanks for sharing!
Reply 4 years ago on Introduction
Yes! That would be a great use of it as well! Thank you!
4 years ago
I have actually used that exact batman pattern for crocheting.
4 years ago on Introduction
This is a great idea. Thanks for sharing!
Question 1 year ago on Introduction
Very nice coding style! Can you show an example of which variables get updated when you setup your java file for a new .jpg image? Please include a sample directory path. When I tried to use your code I got a message in the output flow:
Unable to process request. 0
CrossStitch.java requires three parameters:
[1]: Full path and file name for Input Image(Ex:C:/images/funImage.jpg
[2]: Full path and file name for Output Image(Ex:C:/images/funImage_crossStitch.jpg
[3]: Number of rows in output
[4]: Number of columns in output
Answer 1 year ago
Hi Sizzlewump,
It looks like you forgot to add the input parameters. You have to fill out those for it to work. So for example, these are input parameters I just tried to get a new picture:
"C:\temp\TestPic.jpg"
"C:\temp\TestPic_CS.jpg"
51
51
The top one is a picture that exists, the second one is what the code will create and the third and fourth are the image dimensions of the created picture. I hope that helps!
Answer 1 year ago
I think I'm missing some code or something. I have tried as you suggested but I get the same results using:
public class CrossStitch
{
public static void main(String[] p_args) throws IOException
{
String imageToStitch = "C:/temp/spaceGhost2.jpg";//"C:/....."
String outputImage = "C:/temp/spaceGhost2_CS.jpg";//"C:/....."
int sizeX = 51;
int sizeY = 51;
try
{
Answer 1 year ago
Oh, I see the problem. Don't modify the code and add your variables, they are input parameters. If you're running from Eclipse or another IDE, You have to put them under PROGRAM Arguments. Then, those will populate the String[] p_args variable.
If you DO want to just modify the code, then fill those out as you see fit, and comment out the try/catch that decipers p_args.
Answer 1 year ago
Awesome! Thanks for clearing that up. I'm using JGrasp (I like that it's not resource intensive). It works fine without the try/catch block. I didn't even consider that.
2 years ago
Very clever idea! Thanks for sharing!
4 years ago on Introduction
open in MSPaint, zoom in and printscreen?
Reply 4 years ago on Introduction
Zooming in with MsPaint will give the image a pixelated look, but it won't make it in to a specific number of pixels, which are needed for cross stitching, crocheting and perler beading.
Reply 4 years ago on Introduction
ok. i didnt realize that it had to be a specific style. I just thought it was as simple as adding a grid and making X's. thanks for the info!
|
https://www.instructables.com/id/Cross-Stitch-Pattern-Generator/
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
The QMultiPortMultiplexer class provides multiplexing across several serial ports More...
#include <QMultiPortMultiplexer>
Inherits QSerialIODeviceMultiplexer.
The QMultiPortMultiplexer class provides multiplexing across several serial ports
Use this class instead of QGsm0710Multiplexer if the operating system kernel has built-in support for multiplexing.
Instances of QMultiPortMultiplexer are created by multiplexer plug-ins. See the Tutorial: Writing a Multiplexer Plug-in for more information on how to write a multiplexer plug-in that uses QMultiPortMultiplexer.
See also QSerialIODeviceMultiplexer, QGsm0710Multiplexer, and QSerialIODeviceMultiplexerPlugin.
Construct a new multi-port multiplexer object and attach it to parent. The primary channel will be set to device. Further channels can be added by calling addChannel(). Ownership of device will pass to this object; it will be deleted when this object is deleted.
Destruct this multi-port multiplexer object.
Add a new channel to this multiplexer, with requests for name being redirected to device. Returns false if name already exists.
Ownership of device will pass to this object; it will be deleted when this object is deleted. A single device can be added for multiple channels (e.g. data and datasetup). This object will ensure that such devices will be deleted only once.
|
https://doc.qt.io/archives/qtopia4.3/qmultiportmultiplexer.html
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Leave:;>> wrote:
>
> > Hi all,
> >
> > Roman Shaposhnik suggested I open a discussion on the following topic:
> >
> > For Apache DataFu, all of the Java classes are declared in a datafu.*
> > namespace. This has been the naming convention since the DataFu project
> > started in 2010. Since DataFu became part of the Apache incubation
> > process, the topic has come up of moving all of the classes into a
> > org.apache.datafu.* namespace. This was first discussed in January 2014
> > (see DATAFU-7) and most recently again in the past couple weeks. The
> > consensus at the time last year was that it would be a huge pain for
> users
> > and not worth the cost. It would break any script out there currently
> > using DataFu. Also Jakob Homan and Russell Journey pointed out that this
> > is just a convention and not all Apache projects follow it. Since we
> would
> > like DataFu to graduate sometime soon it would be good to clarify what
> the
> > requirements are on package naming conventions before we do a release.
> >
> > Thoughts?
> >
> > Thanks,
> > Matt
> >
>
> Current statement on Incubator website
>
>
>
> But, if DataFu will do the repackaging, better sooner (before graduation)
> then later.
>
>
> --
> Luciano Resende
>
>
>
>
--
Russell Jurney twitter.com/rjurney russell.jurney@gmail.com datasyndrome.com
|
http://mail-archives.apache.org/mod_mbox/datafu-dev/201508.mbox/%3CCANSvDjowr2_hU=4Z7Sgk-oDmSpE0iQL2QswcK-UYiX1=6wDhJw@mail.gmail.com%3E
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
B01-02632560-294
The OpenCL Programming Book
The.
2
B01-02632560-294
The OpenCL Programming Book
Contents
Foreword 4 Foreword 6 Acknowledgment 7 Abou the Authors 8 Introduction to Parallelization 10 Why Parallel 10 Parallel Computing (Hardware) 10 Parallel Computing (Software) 15 Conclusion 30 OpenCL 31 What is OpenCL? 31 Historical Background 31 An Overview of OpenCL 34 Why OpenCL? 36 Applicable Platforms 37 OpenCL Setup 41 Available OpenCL Environments 41 Developing Environment Setup 44 First OpenCL Program 51 Basic OpenCL 59 Basic Program Flow 59 Online/Offline Compilation 67 Calling the Kernel 77 Advanced OpenCL 98 OpenCL C 98 OpenCL Programming Practice 131 Case Study 164 FFT (Fast Fourier Transform) 164 Mersenne Twister 200 Notes 245
3
B01-02632560-294
The OpenCL Programming Book
Foreword
“The free lunch is over.” The history of computing has entered a new era. Until a few years ago, the CPU clock speed determined how fast a program will run. I vividly recall having a discussion on the topic of software performance optimization with a System Engineer back in 2000, to which his stance was, “the passing of time will take care of it all,” due to the improving technology. However, with the CPU clock speed leveling off at around 2005, it is now solely up to the programmer to make the software run faster. The free lunch is over. The processor venders have given up on increasing CPU clock speed, and are now taking the approach of raising the number of cores per processor in order to gain performance capability. In recent years, many multi-core processors were born, and many developing methods were proposed. Programmers were forced to grudgingly learn a new language for every new type of processor architecture. Naturally, this caused a rise in demand for one language capable of handling any architecture types, and finally, an open standard was recently established. The standard is now known as “OpenCL”. With the khronos group leading the way (known for their management of the OpenGL standard), numerous vendors are now working together to create a standard framework for the multi-core era. Will this new specification become standardized? Will it truly be able to get the most out of multi-core systems? Will it help take some weight off the programmer’s shoulders? Will it allow for compatible programs to be written for various architectures? Whether the answers to these questions become “Yes” or “No” depends on the efforts of everyone involved. The framework must be designed to support various architectures. Many new tools and libraries must be developed. It must also be well-received by many programmers. This is no easy task, as evidenced by the fact that countless programming languages continually appear and disappear. However, one sure fact is that a new standard developing method is necessary for the new multi-core era. Another sure fact is that “OpenCL” is currently in the closest position to becoming that new standard. The Fixstars Corporation, who authors this book, has been developing softwares for the Cell 4
Fixstars Corporation Chief Executive Officer Satoshi Miki 5 . when its full power is unleashed by efficient usage of the hundreds of cores that exist within. We write this book in hopes that the readers of this book learns. uses. leading us to want an open framework. since 2004. We have also been amazed by the capability of the GPU. in order to see the performance capability of the processor in action.B01-02632560-294 The OpenCL Programming Book Broadband Engine co-developed by Sony. many of our clients had been expressing their distaste for the lack of standards between the different architectures. “OpenCL” is a framework that developed solely out of need. Therefore. enough to battle its infamously difficult hardware design. and thus become part of the ongoing evolution that is this multi-core era. Toshiba.E. and contribute to the development of OpenCL. and IBM. OpenCL is still in its infancy. Meanwhile. We have been awed by the innovative idea of the Cell B. and thus not every need can be fulfilled.
Fixstars is a skilled OpenCL practitioner and is ideally qualified to create state-of-the-art OpenCL educational materials.B01-02632560-294 The OpenCL Programming Book. Neil Trevett President. I wholeheartedly recommend to this book to anyone looking to understand and start using the amazing power of OpenCL. The Khronos Group 6 . A vital piece of any living standard is enabling the industry to truly understand and tap into the power full potential of the technology.
we do however assume that the reader has a good grasp of the C language. The official reference manual for OpenCL can be found online on Khronous' website at: 7 .B01-02632560-294 The OpenCL Programming Book Acknowledgment The book is intended for those interested in the new framework known as OpenCL.0/docs/man/xhtml/ Sample programs in this book can be downloaded at. While we do not assume any preexisting knowledge of parallel programming. since we introduce most of what you need to know in Chapter 1. Those who are already experts in parallel programming can start in Chapter 2 and dive straight into the new world of OpenCL.fixstars.org/opencl/sdk/1.
B01-02632560-294 The OpenCL Programming Book About the Authors Ryoji Tsuchiyama Aside from being the leader of the OpenCL team at Fixstars. My background. I worked on projects such as construction of a data collection system (Linux kernel 2. I get most of my vitamins and minerals from reading datasheets and manuals of chips from different vendors. as well as parallel processing using accelerators such as Cell/B. as well as memory-mapped registers. Recently. Between teaching numerous seminars and writing technical articles. for which my only memory concerning it is playing the Invader game for hours on end. that I/O and memory accesses must be conquered prior to tackling parallelization. and to a career where I orchestrate a bunch of CPUs and DSPs to work together in harmony with each other. I have been dealing with distributed computing on x86 clusters. but I have yet to come up with a good solution. I'm constantly thinking of ways to 8 . I am constantly trying to meet some sort of a deadline. and knew at first sight she was the one. my fascination with computers have gotten me through a Master's Degree with an emphasis on distributed computing. and I particularly enjoy glancing at the pages on latency/throughput. I joined Fixstars in hopes that it will help me in achieving my life goal of creating the ultimate compiler as it necessitates an in-depth understanding of parallel processing. and GPU. Since my first encounter with a computer (PC-8001) as a child. My first computer was the Macintosh Classic. I'm becoming more convinced by day. I still wish to write a book on how to make a GPU at some point. That being said. I take part in both the development and the marketing of middlewares and OS's for multi-core processors. Akihiro Asahara At Fixstars. I fell in love with the wickedly awesome capability of the GPU 2 years ago. is in Astrophysics. Back in my researching days. Takuro Iizuka I am one of the developers of the OpenCL Compiler at Fixstars. however. I am also involved in the development of a financial application for HPC.2 base!) for large telescopes.E. and developing a software for astronomical gamma-ray simulation (in FORTRAN!). Takashi Nakamura I am the main developer of the OpenCL Compiler at Fixstars. however. I often wonder how much geekier I could have been had I grew an appreciation for QuickDraw at that time instead.
I currently serve the CEO position here at Fixstars. as well as offer seminars. For more information. Since then. I have been working hard to help spread multi-core technology that is already becoming the standard. I was convinced that software developing process will have to change drastically for the multi-core era.com/en. Satoshi Miki As one of the founding member. In 2004. About Fixstars Corporation Fixstars Corporation is a software company that focuses on porting and optimization of programs for multi-core processors. 9 . manufacturing. and I am currently working on obtaining a PhD in information engineering.fixstars. and decided to change the direction of the company to focus on the research and development of multi-core programs.E. My debut as a programmer was at the age of 25. and the GPU. using multi-core processors such as the Cell/B. Fixstars offers a total solution to improve the performance of multi-core based operations for fields that requires high computing power such as finance.B01-02632560-294 The OpenCL Programming Book fit in some sort of astronomical work here at Fixstars. Fixstars also works on spreading the multi-core technology through publication of articles introducing new technologies. and digital media. please visit. medical.
which are then solved concurrently("in parallel"). Today. which effectively caused the CPU clock speed to level off. The processor vendors were forced to give up their efforts to increase the clock speed. and instead adopt a new method of increasing the number of cores within the processor. at around 2004 when Intel’s CPU clock speed reached 4GHz. SMP (Symmetric Multiprocessing) system .a network of general-purpose computers. Since the CPU clock speed has either remained the same or even slowed down in order to economize the power usage. old software designed to run on a single processor will not get any faster just by replacing the CPU with the newest model. operating on the principle that large problems can often be divided into smaller ones.identical processors (in powers of 2) connected 10 .[1] Many different hardware architectures exist today to perform a single task using multiple processors.known as the supercomputer architecture. However. which significantly increased each passing year. the increase in power consumption and heat dissipation formed what is now known as the “Power Wall”. which lead up to the introduction to OpenCL in the chapters to follow. but that it is becoming common in various applications. software speedup was achieved by using a CPU with a higher clock speed. Why Parallel In the good old days. dual-core CPUs are commonplace even for the basic consumer laptops.a combination of computer resources from multiple administrative domains applied to a common task. Some examples. To get the most out of the current processors. what exactly is "parallel computing"? Wikipedia defines it as "a form of computation in which many calculations are carried out simultaneously. Cluster server system . Parallel Computing (Hardware) First of all. the software must be designed to take full advantage of the multiple cores and perform processes in parallel. This shows that parallel processing is not just useful for performing advanced computations. MPP (Massively Parallel Processor) systems .B01-02632560-294 The OpenCL Programming Book Introduction to Parallelization This chapter introduces the basic concepts of parallel programming from both the hardware and the software perspectives. in order of decreasing scale is: Grid computing .
Multiple Data streams SIMD) One instruction is broadcasted across many compute units. each CPU that makes up the system uses a unique memory space. Single Data stream (MISD) Multiple instruction streams process a single data stream. Multiple Instruction. most parallel computing hardware architectures. 11 . where each unit processes the same instruction on different data. various micro-processors include SIMD processors. Single Data stream (SISD) SISD system is a sequential system where one instruction stream process one data stream. such as the SMP and cluster systems. Flynn's Taxonomy Flynn's Taxonomy is a classification of computer architectures proposed by Michael J. Very few systems fit within this category. the MIMD architecture is further categorized by memory types. In distributed memory type systems. In shared memory type systems. The pre-2004 PCs were this type of system. Single Instruction. 3. SSE instruction on Intel CPU. 4.B01-02632560-294 The OpenCL Programming Book together to act as one unit. The two main memory types used in parallel computing system are shared memory and distributed memory types. It is based on the concurrency of instruction and data streams available in the architecture. a type of a supercomputer. Multi-core processor . Recently. fall within the MIMD category. For this reason. The vector processor. Using this classification scheme. Multiple Instruction. An instruction stream is the set of instructions that makes up a process. 2. each CPU that makes up the system is allowed access to the same memory space.a single chip with numerous computing cores. is an example of this architecture type. Single Instruction. with the exception for fault tolerant systems. and a data stream is the set of data to be processed. For example. 1. Flynn [2]. Multiple Data streams (MIMD) Multiple processing units each process multiple data streams using multiple instruction streams. and SPE instruction on Cell Broadband Engines performs SIMD instructions.
Even with these external networks. If each CPU is running a process. while 82% are cluster systems. have been replaced by cluster systems.6% are MPP systems. the system with distributed memory types requires data transfers to be explicitly performed by the user. This is known as a cluster server system. 17. Infiniband. Due to this reason. giving it a much higher cost performance than the MPP systems. For the reason given above. The main difference between a cluster system and a MPP system lies in the fact that a cluster does not use specialized hardware. This is due to the fact that these transfers occur via an external network. which has significantly become faster compared to the traditional Gigabit Ethernet. NEC's Earth Simulator and IBM's blue Gene are some of the known MPP systems. many MPP systems. memory. which are made up of CPU. a system with shared memory type allows the two processes to communicate via Read/Write to the shared memory space. which performs tasks such as large-scale simulation. of the top 500 supercomputers as of June 2009. which is perhaps the most commonly-seen distributed memory type system. According to the TOP500 Supercomputer Sites[3]. Distributed Memory type Tasks that take too long using one computer can be broken up to be performed in parallel using a network of processors. and a network port.B01-02632560-294 The OpenCL Programming Book Different memory types result in different data access methods. since the two memory spaces are managed by two OS's. One problem with cluster systems is the slow data transfer rates between the processors. MPP (Massively Parallel Processor) system is also another commonly-seen distributed memory type system. the transfer rates are still at least an order of magnitude slower than the local memory access by each processor. On the other hand. via a specialized fast network. which used to be the leading supercomputer type. 10Gbit Ethernet. Some recent external networks include Myrinet. cluster systems are suited for parallel algorithms where the CPU's do 12 . This type of computing has been done for years in the HPC (High Performance Computing) field. The next sections explore the two parallel systems in detail. This connects numerous nodes.
An example is the risk simulation program used in Derivative product development in the finance field. The Intel Multiprocessor Specification Version 1. However. which makes the bandwidth between the processors and the shared memory a bottleneck. increasing the number of processors naturally increases the number of accesses to the memory. The main difference from a SMP system is that the physical distance between the processor and the memory changes the access speeds. By prioritizing the usage of physically closer memory (local memory) rather than for more distant memory (remote memory). this results in a much simpler system from the software perspective. To reduce the access cost to the remote memory. and only effective up to a certain number of processors. Since data transfers/collections are unnecessary.B01-02632560-294 The OpenCL Programming Book not have to communicate with each other too often.0 released back in 1994 describes the method for using x86 processors in a multi-processor configuration. which can become expensive. Although 2-way servers are inexpensive and common.1: SMP and NUMA Another example of a shared memory type system is the Non-Uniform Memory Access (NUMA) system. a 13 ." These algorithms are used often in simulations where many trials are required. the bottleneck in SMP systems can be minimized. An example of a shared memory type system is the Symmetric Multiprocessing (SMP) system (Figure 1. 32-Way or 64-Way SMP servers require specialized hardware. all processors share the same address space. SMP systems are thus not scalable. and 2-Way work stations (workstations where up to 2 CPU's can be installed) are commonly seen today [4]. These types of algorithms are said to be "Course-grained Parallel.1. allowing these processors to communicate with each other through Read/Writes to shared memory. but these trials have no dependency. Figure 1. left). Shared Memory Type In shared memory type systems.
looking at typical x86 server products bring about an interesting fact. Since these cores are relatively simple and thus do not take much area on the 14 . Networking these multi-core processors actually end up creating a NUMA system. Figure 1.B01-02632560-294 The OpenCL Programming Book processor cache and a specialized hardware to make sure the cache data is coherent has been added.E. The Dual Core and Quad Core processors are SMP systems. In addition. The non-CPU hardware in this configuration is known as an Accelerator.2: Typical 2Way x86 Server Accelerator The parallel processing systems discussed in the previous sections are all made by connecting generic CPUs. Now that the basic concepts of SMP and NUMA are covered. the NUMA gets rid of this to use a interconnect port that uses a Point-to-Point Protocol. In other words. another approach is to use a different hardware more suited for performing certain tasks as a co-processor. and Hyper Transport by AMD. and this system is known as a Cash Coherent NUMA (cc-NUMA). when these are used in multi-processor configuration. These ports are called Quick Path Interconnect (QPI) by Intel. the mainstream 2+way x86 server products are "NUMA systems made by connecting SMP systems" (Figure 1.2) [5]. Although this is an intuitive solution. since the processor cores all access the same memory space. it becomes a NUMA system.) and GPUs. Some popular accelerators include Cell Broadband Engine (Cell/B. Server CPUs such as AMD Opteron and Intel Xeon 5500 Series contains a memory controller within the chip. which is a bus that connects multiple CPU as well as other chipsets. Accelerators typically contain cores optimized for performing floating point arithmetic (fixed point arithmetic for some DSPs). Thus. Front Side Bus (FSB). The hardware to verify cache coherency is embedded into the CPU.
as well as high power usage. Another example is NVIDIA's GPU chip known as Tesla T10.E. the circuit board and semiconductor fields use automatic visual checks. since many factories and research labs are trying to cut back on the power usage. The medical imaging devices such as ultrasonic diagnosing devices and CT Scans are taking in higher and higher quality 2D images as an input every year. as well as what type of a hybrid system. and the generic CPUs are not capable of processing the images in a practical amount of time. For example. the accelerators provide a portable and energy-efficient alternative to the cluster. OpenCL. These accelerators are typically used in conjunction with generic CPUs. For example. This is mainly due to the fact that the generic CPU's floating point arithmetic capability has leveled off at around 10 GFLOPS. these accelerators are attracting a lot of attention. These 9 cores are connected using a high-speed bus called the Element Interconnect Bus (EIB). Thus. The number of checks gets more complex every year. making it unfit for applications requiring frequent I/O operations. the transfer speed between the host CPU and the accelerator can become a bottle neck. In summary. which contains 30 sets of 8-cored Streaming Processors (SM). and GPUs can perform between 100 GFLOPS and 1 TFLOPS for a relatively inexpensive price. needs to be made wisely. Cell/B.E. is a development framework to write applications that runs on these "hybrid systems". for a total of 240 cores on one chip. requiring faster image processing so that the rate of production is not compromised. contains 1 PowerPC Processor Element (PPE) which is suited for processes requiring frequent thread switching. creating what's known as a "Hybrid System". Thus. a decision to use a hybrid system. numerous cores are typically placed. and placed on a single chip. in brief. an accelerator allows for a low-cost. It is also more "Green". In recent years.B01-02632560-294 The OpenCL Programming Book chip. and 8 Synergistic Processor Elements (SPE) which are cores optimized for floating point arithmetic. Parallel Computing (Software) 15 . high-performance system. which makes it a better option than cluster server systems. low-powered. while Cell/B. Using a cluster server for these tasks requires a vast amount of space. However.
Figure 1. and run each subtasks on each core. This type of method is called Sequential processing. single-CPU processor (SISD system). hardware architectures that involve performing one task using numerous processors had been the main focus. = task_b(i). If this code is compiled without adding any options for optimization on a Dual Core system. As shown on Figure 1. and then performs addition at the end.i<N. List1. and the returned values are then summed up. task_c. the task is split up into 2 such that each subtask runs the loop N/2 times. This section will focus on the method for parallel programming for the discussed hardware architectures. This is clearly inefficient. the other core has nothing to do. so the intuitive thing to do here is to split the task into 2 subtasks. task_b.i++){ 002: 003: 004: 005: 006: 007: } resultA resultB resultC = task_a(i). = task_c(i).3: Parallel processing example 16 . Sequential vs Parallel Processing Take a look at the pseudocode below. This is then repeated N times. This is the basis of parallel programming.3. the program would run sequentially on one core.1: Pseudocode for parallel processing 001: for(i=0. so it becomes idle. This type of code can benefit from parallelization. In this scenario.3. resultD = task_d(i). resultAll += resultA + resultB + resultC + resultD. task_d. Running the code with N=4 is shown on the left hand side of Figure 1. Executing the above code on a single-core. incrementing i after each iteration.B01-02632560-294 The OpenCL Programming Book Up until this point. the 4 tasks would be run sequentially in the order task_a.
Decide on the best algorithm to execute the code over multiple processors 3. but since multi-core processors are becoming more common. it is necessary to follow the following steps. the use of these distributed processing techniques are becoming more necessary. The following sections will introduce basic concepts required to implement parallel processes. etc. in order to decide which sections can be executed in parallel. 2. In the past. 1. or OpenCL. Analyze the dependency within the data structures or within the processes. OpenMP. 17 . these skills were required only by a handful of engineers. Rewrite code using frameworks such as Message Passing Interface (MPI).B01-02632560-294 The OpenCL Programming Book For actual implementation of parallel programs.
The law can be proven as follows.4: Amdahl's Law Example 18 . For a more concrete example. Assume Ts to represent the time required to run the portion of the code that cannot be parallelized. Even without taking overhead into account. the speedup is limited by the portion of the code that must be run sequentially. the speedup S achieved is: S = T(1)/T(N) = T(1)/(Ts + Tp/N) = 1/(y+(1-y)/N) Taking the limit as N goes to infinity.3x speedup depending on y.B01-02632560-294 The OpenCL Programming Book Where to Parallelize? During the planning phase of parallel programs. Running the program with 1 processor. a 4-time speedup is achieved. Figure 1. and Tp to represent the time required to run the portion of the code that can benefit from parallelization. and 50%.4 shows the 2 cases where the proportion of the code that cannot be run in parallel (y) is 10%. certain existing laws must be taken into account. The first law states that if a program spends y% of the time running code that cannot be executed in parallel. Figure 1. the expected speed up from parallelizing is at best a 1/y fold improvement. the most speedup that can be achieved is S=1/y. This law is known as Amdahl's Law [6]. the processing time is: T(1) = Ts + Tp The processing time when using N processors is: T(N) = Ts + Tp/N Using y to represent the proportion of the time spent running code that cannot be parallelized. Ideally. However. as the law states. assume that a sequential code is being rewritten to run on a Quad Core CPU. the figure shows a difference of 3x and 1.
The graph clearly shows the importance of reducing the amount of sequentially processed portions.B01-02632560-294 The OpenCL Programming Book This problem becomes striking as the number of processors is increased. This also implies that the effort used for parallelizing a portion of the code that does not take up a good portion of the whole process may be in vain. In summary. especially as the number of cores is increased.5: Result of scaling for different percentage of tasks that cannot be parallelized 19 . GPUs such as NVIDIA's Tesla can have more 200 cores.5 shows the speedup achieved as a function of the sequentially processed percentage y and the number of cores. For a common 2-way server that uses Intel's Xeon 5500 Series CPUs which supports hyper-threading. the OS sees 16 cores. Figure 1. it is more important to reduce serially processed portions rather than parallelizing a small chunk of the code. Figure 1.
assume a program where a portion that must be run sequentially is limited to initialization and closing processes. Development of parallel programming requires close attention to these 2 laws. the fraction of the program that can be run in parallel also increases. a large-scale processing must take place. For example. This law states that as the program size increases. Parallel processing requires the splitting up of the data to be handled. and all other processes can be performed in parallel. and that Tp grows faster than Ts. the next step is to decide on the type of parallelism to use. In other words. Gustafson's law shows that in order to efficiently execute code over multiple processors. Types of Parallelism After scrutinizing the algorithm and deciding where to parallelize. Recall the previously stated equation: T(N) = Ts + Tp/N Gustafson states that of the changes in Ts.1. it is apparent that Gustafson's law holds true. Refer back to the code on List 1. This time. the Gustafson Law provides a more optimistic view. assume the usage of a Quad-core CPU to run 4 20 . Tp is directly proportional to the program size.B01-02632560-294 The OpenCL Programming Book While Amdahl's law gives a rather pessimistic impression of parallel processing. and/or the process itself. By increasing the amount of data to process by the program. thereby decreasing the portion that must be performed sequentially.
it also makes just as much sense to run each of these tasks in each processor.7. The pixels can be split up into blocks. As illustrated in Figure 1. more concrete example where this method can be applied is in image processing. the addition at each index can be performed completely independently of each other. For this operation. An intuitive approach is to let each processor perform N/4 iteration of the loop.7: Vector Addition 21 . and that all processors finish their task at around the same time. but since there are 4 tasks within the loop. This method is efficient when the dependency between the data being processed by each processor is minimal. The former method is called "Data Parallel". Figure 1. Figure 1. and the latter method is called "Task Parallel" (Figure 1. the number of processors is directly proportional to the speedup that may be achieved if overhead from parallelization can be ignored.B01-02632560-294 The OpenCL Programming Book processes at once. vector addition can benefit greatly from this method. Another. For example.6). and each of these blocks can be filtered in parallel by each processor.6: Data Parallel vs Task Parallel Data Parallel Main characteristics of data parallel method is that the programming is relatively simple since multiple processors are all running the same program.
One way is to implement a load balancing function on one of the processors. since task_a and task_c are doing nothing until task_b and task_d finishes. Also.6. the load balancer maintains a task queue. Task parallel method requires a way of balancing the tasks to take full advantage of all the cores. Since the processing time may vary depending on how the task is split up.B01-02632560-294 The OpenCL Programming Book Task Parallel The main characteristic of the task parallel method is that each processor executes different commands. This increases the programming difficulty when compared to the data parallel method. it is actually not suited for the example shown in Figure 1. Figure 1. and assigns a task to a processor that has finished its previous task. In the example in Figure 1.8.8: Load Balancing 22 . the processor utilization is decreased.
task_b. such that task_b. where processing frames are taken as inputs one after another. such as instruction decoding. but can be effective when processing. and register fetch. for example. arithmetic operation. In this example. Figure 1. This method is not suited for the case where only one set of tasks is performed. This concept can be used in parallel programming as well.9: Pipelining 23 .9 shows a case where each processor is given its own task type that it specializes in. task_c. the start of each task set is shifted in the time domain. videos.B01-02632560-294 The OpenCL Programming Book Another method for task parallelism is known as pipelining. Pipelining is usually in reference to the "instruction pipeline" where multiple instructions. task_c as an input. task_d takes in the output of task_a. are executed in an overlapped fashion over multiple stages. The data moves as a stream across the processors. Figure 1.
However. For example. the Cell/B. and the hardware is usually suited for one or the other. is more suited for performing task parallel algorithms. Programs usually have sections suited for data parallelism as well as for task parallelism. OpenCL allows the same code to be executed on either platforms. the hardware must be decided wisely.E. since the GPU (at present) is not capable of performing different tasks in parallel. due to the existence of many cores.B01-02632560-294 The OpenCL Programming Book Hardware Dependencies When porting sequential code to parallel code. but since it cannot change the nature of the hardware. 24 . the hardware and the parallelization method must be chosen wisely. since its 8 cores are capable of working independently of each other. the GPU is suited for data parallel algorithms.
For performing parallel instructions performed within the processor itself. but this is commonly done using a framework instead. the operating system performs execution. This section will explore the different methods. the operating system provides an API to create and manage these threads. the overhead from starting and switching is much smaller than when compared to processes. since these threads execute in the same memory space. which is a POSIX-approved thread protocol. UNIX provides a system call shmget() that allocates shared memory that can be accessed by different processes. UNIX provides a library called Pthreads. making sure each of these processes' distinct resources do not interfere with each other. Write parallel code using the operating system's functions. The code can be further broken down into "parallel processes" and "parallel threads" to be run on the processor. In general. Data transfer between programs may be performed by a system call to the operating system. POSIX is a standard for API specified by IEEE. and interruption within these process units. however. closing. at minimum. the OS system call may be used instead of the framework. In decreasing order of user involvement: 1. A thread is a subset of a process that is executed multiple times within the program. For example. the data transfer between programs is performed using network transfer APIs such as the socket system call. and some way of transferring data between the executed programs. 25 . Parallelism using the OS System Calls Implementing parallel programs using the OS system call requires. a call to execute and close a program. the next step is the implementation. 2. Use a parallelization framework for program porting. 3. If this is done on a cluster system. A process is an executing program given its own address space by the operating system. Use an automatic-parallelization compiler.B01-02632560-294 The OpenCL Programming Book Implementing a Parallel Program After deciding on the parallelization method. In general. In general. These threads share the same address space as the processes. The difference between processes and threads are as follows. For example.
i++) iptr[i] += 1. 014: for(i=0.h> 004: 005: #define TH_NUM 4 006: #define N 100 007: 008: static void *thread_increment(void *array) 009: { 010: int i. due to the light overhead.i++){ 028: array[i] = i.i<N. 025: 026: /* initialize array*/ 027: for(i=0.B01-02632560-294 The OpenCL Programming Book Whether to use parallel processes or parallel threads within a processor depends on the case. 011: int *iptr. 022: pthread_t thread[TH_NUM].i< N / TH_NUM. parallel threads are used if the goal is speed optimization. 029: } 26 .h> 003: #include <pthread.2 shows an example where each member of an array is incremented using multithreading.2: pthread example 001: #include <stdio. 015: 016: return NULL. 023: 024: int array[N]. but in general. List 1. List 1. 012: 013: iptr = (int *)array. 017: } 018: 019: int main(void) 020: { 021: int i.h> 002: #include <stdlib.
and the parallelization APIs in Boost C++. OpenMP for shared memory systems (SMP. array + i * N / TH_NUM) != 0) 034: { 035: return 1. NULL) != 0) 042: { 043: return 1.i<TH_NUM. NULL.B01-02632560-294 The OpenCL Programming Book 030: 031: /* Start parallel process */ 032: for(i=0. The start index is passed in as an argument. and the fourth argument is the argument passed to the thread. are limited.i<TH_NUM. It increments each array elements by one. These frameworks require the user to 27 . NUMA). 048: } The code is explained below. but the ones used in practical applications.i++){ 033: if (pthread_create(&thread[i]. 032-037: Creation and execution of threads. thread_increment. In line 033. the third argument is the name of the function to be executed by the thread. 003: Include file required to use the pthread API 008-017: The code ran by each thread. 022: Declaration of pthread_t variable for each thread. 044: } 045: } 046: 047: return 0. 039-045: Waits until all threads finish executing Parallelism using a Framework Many frameworks exist to aid in parallelization.i++){ 041: if (pthread_join(thread[i]. such as in research labs and retail products. 036: } 037: } 038: 039: /* Synchronize threads*/ 040: for(i=0. This is used in line 033. The most widely used frameworks are Message Passing Interface (MPI) for cluster servers.
List 1. i < N. From the original sequential code.3 shows an example usage of OpenMP.h> 002: #include<stdlib.i<N. such as GCC.h> 003: #include<omp. allowing the user to focus on the main core of the program. 026: } 28 . which is supported by most mainstream compilers. 017: } 018: 019: /* Parallel process */ 020: #pragma omp parallel for 021: for (i = 0. List 1. but take care of tasks such as data transfer and execution of the threads. 010: int rootBuf[N].B01-02632560-294 The OpenCL Programming Book specify the section as well as the method used for parallelization. 011: 012: omp_set_num_threads(TH_NUM). The compiler then takes care of the thread creation and the commands for thread execution. Microsoft C. which explicitly tells the compiler which sections to run in parallel. Intel C. the programmer inserts a "#pragma" directive.i++){ 016: rootBuf[i] = i. 023: } 024: 025: return(0).h> 004: #define N 100 005: #define TH_NUM 4 006: 007: int main () 008: { 009: int i. 013: 014: /* Initialize array*/ 015: for(i=0.3: OpenMP Example 001: #include<stdio. i++) { 022: rootBuf[i] = rootBuf[i] + 1.
and the number of times to run the loop. GCC (Linux) requires "-fopenmp". 003: Include file required to use OpenMP 004: Size of the array. The argument must be an integer. 012: Specify the number of threads to be used. The 29 . • -parallel: Enables automatic parallelization • -par-report3: Reports which section of the code was parallelized. The code is explained below. into the number of threads specified in 012. For example. which can be specified in the form -par-report[n] • -par-threshold0: Sets the threshold to decide whether some loops are parallelized. Automatic parallelization compiler Compilers exist that examines for-loops to automatically decide sections that can be run in parallel. There are 3 report levels. 020: Breaks up the for loops that follows this directive.c The explanations for the options are discussed below. enough computations must be performed within each loop to hide the overhead from process/thread creation. intel C (Linux) requires "-openmp". Compare with List 2 that uses pthreads. this number should be somewhat large to benefit from parallelism. This example shows how much simpler the programming becomes if we use the OpenMP framework. and Microsoft Visual C++ requires /OpenMP. This is specified in the form -par-threshold[n]. Intel C/C++ compiler does this when the option is sent. In general.c (Windows) > Icc /Qparallel /Qpar-report3 /Q-par-threshold0 -03 o parallel_test parallel_test. In order to benefit from parallelization.B01-02632560-294 The OpenCL Programming Book When compiling the above code. (On Linux) > icc -parallel -par-report3 -par-threshold0 -03 o parallel_test parallel_test. the OpenMP options must be specified. as well as how many threads to use.
the automatic parallelization compiler seems to be the best solution since it does not require the user to do anything. with higher number implying higher number of computations. Conclusion This section discussed the basics of parallel processing from both the hardware and the software perspectives. When this value is 0. 30 . all sections that can be parallelized become parallelized.B01-02632560-294 The OpenCL Programming Book value for n must be between 0 ~ 100. The default value is 75. The content here is not limited to OpenCL. making the performance suffer. as the code becomes more complex. Next chapter will introduce the basic concepts of OpenCL. no existing compiler (at least no commercial) can auto-generate parallel code for hybrid systems such as the accelerator. but in reality. so those interested in parallel processing in general should have some familiarity with the discussed content. the compiler has difficulty finding what can be parallelized. At a glance. As of August 2009.
The company authoring this book. it is no longer uncommon for laptops to be equipped with relatively high-end GPUs. by using one core for control and the other cores for computations. IBM. NVIDIA. such as CPU. using one language. Texas Instruments. OpenCL provides an effective way to program these CPU + GPU type heterogeneous systems. and it can be used on homogeneous. The heterogeneous system such as the 31 . Apple. GPU. Historical Background Multi-core + Heterogeneous Systems In recent years. multi-core processors such as the Intel Core i7. OpenCL. This chapter will introduce the main concepts of OpenCL.. who is known for their management of the OpenGL specification. and involved in the specification process. This chapter will give a glimpse into the history of how OpenCL came about. The physical limitation has caused the processor capability to level off. OpenCL (Open Computing Language) is "a framework suited for parallel programming of heterogeneous systems". so the effort is naturally being placed to use multiple processors in parallel. What is OpenCL? To put it simply.E. DSP. For desktops. more and more sequential solutions are being replaced with multi-core solutions. the Fixstars Corporation. Intel. Toshiba. The group consists of members from companies like AMD. is also a part of the standardization group. The goal of the standardization is ultimately to be able to program any combination of processors. however. OpenCL is standardized by the Khronos Group. Cell/B. is not limited to heterogeneous systems.B01-02632560-294 The OpenCL Programming Book OpenCL The previous chapter discussed the basics of parallel processing. it is possible to have multiple GPUs due to PCIe slots becoming more common. as well as an overview of what OpenCL is. etc. In recent years. which are all well-known processor vendors and/or multi-core software vendors. The framework includes the OpenCL C language as well as the compiler and the runtime environment required to run the code written in OpenCL C. Sony.
the CPU must perform tasks such as code execution. known for its use on the PLAYSTATION3. First. as well as GPUs specialized for GPGPU called "Tesla". the hardware can be chosen as follows: • Data Parallel → GPU • Task Parallel → Cell/B. we will take a look at CUDA. Another example of accelerator is Cell/B.E.E. In CUDA. which is a way to write generic code to be run on the GPU. The GPU is a processor designed for graphics processing.1.1: Example Kernel Code 001: __global__ void vecAdd(float *A. and the GPU side program is called the kernel. which uses the GPU for tasks other than graphics processing.. • General Purpose → CPU Vendor-dependent Development Environment We will now take a look at software development in a heterogeneous environment. 006: */ 32 . float *C) /* Code to be executed on the GPU (kernel) 002: { 003: int tid = threadIdx. and the user interface. which is an extension of the C language. Since no OS is running on the GPU. has been attracting attention as a result [7]. but its parallel architecture containing up to hundreds of cores makes it suited for data parallel processes. The GPGPU (General Purpose GPU). NVIDIA's CUDA has made the programming much simpler.B01-02632560-294 The OpenCL Programming Book CPU+GPU system is becoming more common as well. /* Get thread ID */ 004: 005: C[tid] = A[tid] + B[tid]. as it allows the CPU for performing general tasks and the GPU for data parallel tasks [8]. float *B. List 2. so that the data parallel computations can be performed on the GPU. Since this is suited for task parallel processing. The main difference between CUDA and the normal development process is that the kernel must be written in the CUDA language. The CPU side program is called the host program. NVIDIA makes GPUs for graphics processing.x. An example kernel code is shown in List 2. and the data parallel side (GPU) is called the "device". file system management. the control management side (CPU) is called the "host".
using specific library functions provided by the Cell SDK. List 2.1: Example Cell/B. /* kernel call(256 threads) */ 005: … 006: } The Cell/B. and a SPE-embedded instruction. 008: } The kernel is called from the CPU-side.1) Table 2. is programmed using the "Cell SDK" released by IBM [10]. Although it does not extend a language like the CUDA.E.2: Calling the kernel in CUDA 001: int main(void) /* Code to be ran on the CPU */ 002: { 003: … 004: vecAdd<<<1. the programmer is required to learn processor-specific instructions. Similarly.E.E. You may have noticed that the structures of the two heterogeneous systems are same. each requiring specific compilers. dB.2 [9]. (Table 2. SPE must call a SSE instruction. As an example. SIMD instructions on the SPE. dC). The Cell/B. comprises of a PPE for control. the programmers must learn two distinct sets of APIs. x86. However. as shown in List 2. specific library functions are required in order to run.2) 33 . and 8 SPEs for computations.B01-02632560-294 The OpenCL Programming Book 007: return. (Table 2. a VMX instruction. in order to perform a SIMD instruction. the SPE must be controlled by the PPE. and the computation being performed on GPU/SPE. respectively. for example. with the control being done on the CPU/PPE. 256>>>(dA. API commands Function Open SPE program Create SPE context Load SPE program Execute SPE program Delete SPE context Close SPE program API spe_image_open() spe_context_create() spe_context_load() spe_context_run() spe_context_destroy() spe_image_close() In order to run the same instruction on different processors. PPE.
all of these combinations have the following characteristics in common: • Perform vector-ized operation using the SIMD hardware • Use multiple compute processors in conjunction with a processor for control • The systems can multi-task However. which may prevent the platform to be chosen solely on its hardware capabilities. there may be varying difficulty in the software development process. each combination requires its own unique method for software development.B01-02632560-294 The OpenCL Programming Book Table 2. since software development and related services must be rebuilt ground up every time a new platform hits the market. the same sort of procedure is performed. The heterogeneous model. software developers will be able to write parallel code that is independent of the hardware platform. To summarize. where the CPU manages the DSPs suited for signal processing. made up of a control processor and multiple compute processors. OpenCL Runtime API Specification API used by the control node to send tasks to the compute cores By using the OpenCL framework. Also. An Overview of OpenCL OpenCL is a framework that allows a standardized coding method independent of processor types or vendors. Often times.2: SIMD ADD instructions on different processors X86 (SSE3) _mm_add_ps() PowerPC (PPE) vec_add() SPE spu_add() Additionally. as programming methods can be quite distinct from each other. This is especially more common in heterogeneous platforms. a similar model is used. Even here. and thus prove to be useless. The answer to this problem is "OpenCL". in the embedded electronics field. OpenCL C Language Specification Extended version of C to allow parallel programming 2. The software developers must learn a new set of APIs and languages. the following two specifications are standardized: 1. using a completely different set of APIs. is 34 . This can prove to be inconvenient. In particular. the acquired skills might quickly become outdated.
Performance OpenCL is a framework that allows for common programming in any heterogeneous environment. so the execution process can be written in normal C/C++. as well as all the GPU to perform computations in parallel [11]. If the performance suffers significantly as a result of using OpenCL. In order to actually execute the code. As an example." which is designed to be used for that particular environment [13]. a CPU core can use the other cores that include SSE units. its purpose becomes questionable. it must first be compiled to a binary using the OpenCL Compiler designed for that particular environment. This process must be coded by the programmer [12]. everything can be written using OpenCL. which includes the loading of the binary and memory allocation. including HPC. The OpenCL Runtime Library Specification also requires a function to compile the code to be run on the device. This brings up the question of whether performance is compromised. Therefore. The set of commands that can be used for this task is what is contained in the "OpenCL Runtime Library. Furthermore. Once the code is compiled. if an OpenCL implementation includes support for both multi-core CPU and GPU. This execution. all tasks ranging from compiling to executing can be written within the control code. Desktops and embedded systems. Therefore. requiring only this code to be compiled and run manually. OpenCL Software Framework So what exactly is meant by "using OpenCL"? When developing software using OpenCL. it must then be executed on the device. OpenCL will allow all of these areas to be taken care of. can be managed by the controlling processor. The control processer is assumed to have a C/C++ compiler installed. The execution process is common to all heterogeneous combinations. OpenCL code is capable of being executed on any computer.B01-02632560-294 The OpenCL Programming Book currently being employed in almost all areas. as it is often the case for this type of common language and middleware. the following two tools are required: • OpenCL Compiler • OpenCL Runtime Library The programmer writes the source code that can be executed on the device using the OpenCL C language. 35 .
it should be executed on a device suited for data parallel processes. The performance can vary greatly just by the existence of SIMD units on the device. Unix POSIX threads. asynchronous memory copy using DMA. coding in OpenCL does not imply that it will run fast on any device. Standardized Parallelization API As mentioned previously. It is. Thus. To be specific. as it should be able to run on any device. The aforementioned CUDA and Cell SDK are such examples. One of the functions that the OpenCL runtime library must support is the ability to determine the device type. it is independent of processors.B01-02632560-294 The OpenCL Programming Book OpenCL provides standardized APIs that perform tasks such as vectorized SIMD operations. That being said. By learning OpenCL. task parallel processing. Optimization OpenCL provides standard APIs at a level close to the hardware. and memory types. necessary for these processors to support OpenCL. but contrary to the other tools. operating systems. In case lower-level programming is desired. the abstraction layer is relatively close to the hardware. OpenCL does allow the kernel to be written in its native language using its own API. However. As far as standardized tools. and memory transfer between 36 . OpenCL prioritizes maximizing performance of a device rather than its portability. however. While the kernel written in OpenCL is portable. However. these include SIMD vector operations. This seems to somewhat destroy the purpose of OpenCL. data parallel processing. requiring the OpenCL compiler and the runtime library to be implemented. the hardware selection must be kept in mind. and memory transfers. and MPI for distributed memory type systems exist. OpenCL is another standardized tool. The hardware should be chosen wisely to maximize performance. as it would make the code non-portable. software developers will be able to code in any parallel environment. which can be used to select the device to be used in order to run the OpenCL binary. each heterogeneous system requires its own unique API/programming method. If a data parallel algorithm is written. Why OpenCL? This section will discuss the advantage of developing software using OpenCL. minimizing the overhead from the usage of OpenCL. making the switch over likely to be just a matter of time. OpenMP for shared memory systems. there are many reputable groups working on the standardization of OpenCL.
uses almost the exact same syntax as the C language. Therefore. it is necessary to learn the hardware-dependent methods.g. The control program using the OpenCL runtime API can be written in C or C++. The developer is required to learn how to use the OpenCL runtime API. such as printf(). the use of OpenCL would never result in limiting the performance. Also. Anyone who has developed code in these types of environment should see the benefit in this.B01-02632560-294 The OpenCL Programming Book the processors. the main steps taken is coding. the code will not have to be changed in order to control another device. As mentioned earlier. OpenCL Devices → Devices). once this is written to control one device type. Applicable Platforms This section will introduce the main concepts and key terms necessary to gain familiarity with OpenCL. and does not require a special compiler. and some features not required for computations. OpenCL allows for the use of the processor-specific API to be used in case some specific functions are not supported in OpenCL. This may seem counter-intuitive. since this would reduce the chance of wasting time on bugs that may arise from not having a full understanding of the hardware. but this is not very difficult. since in order to maximize performance. Some terms may be shortened for the ease of reading (e. It is extended to support SIMD vector operations and multiple memory hierarchies. 37 . debugging. it is possible to tune the performance to get the most out of the compute processors of choice using OpenCL. the developer can start directly from the tuning step. If the code is already debugged and ready in OpenCL. it should be kept in mind that if some code is written in OpenCL. it should work in any environment. and then tuning. Using the hardware-dependent coding method. especially to those who have experience with developing in heterogeneous environment such as CUDA. However. the processors in heterogeneous systems (OpenCL platforms) were called control processors and compute processors. Host + Device Up until this point. as the name suggests. Since high abstraction is not used. were taken out. Learning Curve OpenCL C language. but OpenCL defines these as follows.
This code is compiled using compilers such as GCC and Visual Studio. DSP. which is unique to each platform combination. which is made up of multiple Processing Elements. For CPU servers.Streaming Multiprocessor (SM) • Processing Element . There are no rules regarding how the host and the OpenCL device are connected. CPU are some of the typically used devices. which is linked to an OpenCL runtime library implemented for the host-device combination. GPU. Application Structure This section will discuss a typical application that runs on the host and device. Host Environment where the software to control the devices is executed. The memory associated with the processors is also included in the definition of a device. and use TCP/IP for data transfer. Since the OpenCL runtime implementation takes care of these tasks. Cell/B. 2. When creating an OpenCL application. the host controls the device using the OpenCL runtime API. The program run on the device is called a kernel. this kernel is written in OpenCL C. the CPUs can be connected over Ethernet.B01-02632560-294 The OpenCL Programming Book 1.GPU • Compute Unit .. the programmer will not have to know the exact details of how to perform these tasks. This is typically the CPU as well as the memory associated with it. and compiled using the OpenCL compiler for that device. • OpenCL Device . The host is programmed using C/C++ using the OpenCL runtime API. which contain numerous compute units.E. OpenCL device is expected to contain multiple Compute Units. As an example. As stated earlier.Scalar Processor (SP) OpenCL device will be called a device from this point forward. Since OpenCL expects the device to not be running an operating system. 38 . the GPU described in OpenCL terms is as follows. PCI Express is used most often. OpenCL Devices Environment where the software to perform computation is executed. the compiled kernel needs help from the host in order to be executed on the device. OpenCL explicitly separates the program run on the host side and the device side. In the case of CPU + GPU.
and another ID for each kernel within each compute unit. 39 . which is run on each processing element. each kernel requires a unique index so the processing is performed on different data sets.B01-02632560-294 The OpenCL Programming Book Parallel Programming Models OpenCL provides API for the following programming models. Memory Model OpenCL allows the kernel to access the following 4 types of memory. and the ID for the processing element is called the Work Item ID. The ID can have up to 3 dimensions to correspond to the data to process. Global Memory Memory that can be read from all work items. in which both the number of work groups and the work items are 1. • Data parallel programming model • Task parallel programming model In the data parallel programming model. The index space is defined and accessed by this ID set. OpenCL provides this functionality via the concept of index space. OpenCL gives an ID to a group of kernels to be run on each compute unit. For the task parallel programming model. The index space is defined for task parallel processing as well. For data parallel programming models. 1. so that each kernel processes different sets of data. and the number of work items to be ran on each compute unit (local item). The retrieval of this ID is necessary when programming the kernel. different kernels are passed through the command queue to be executed on different compute units or processing elements. the IDs are given for each item by the OpenCL runtime API. The number of workgroups can be computed by dividing the number of global items by the number of local items. The ID for the compute unit is called the Workgroup ID. It is physically the device's main memory. When the user specifies the total number of work items (global item). the same kernel is passed through the command queue to be executed simultaneously across the compute units or processing elements.
However. The cost memory is set and written by the host. but can be used more efficiently than global memory if the compute units contain hardware to support constant memory cache.B01-02632560-294 The OpenCL Programming Book 2. The 4 memory types mentioned above all exist on the device. all 4 memory types will be physically located on the main memory on the host. 3. However. is capable of reading and writing to the global. The host side has its own memory as well. Private Memory Memory that can only be used within each work item. 40 . The physical location of each memory types may differ depending on the platform. Constant Memory Also memory that can be read from all work items. It is physically the device's main memory. 4. Local Memory Memory that can be read from work items within a work group. Note that the physical location of each memory types specified above assumes NVIDIA's GPUs. The host. constant. only the kernel can only access memory on the device itself. OpenCL requires the explicit specification of memory types regardless of the platform. if the devices are x86 multi-core CPUs. It is physically the registers used by each processing element. and the host memory. It is physically the shared memory on each compute units. For example. on the other hand.
fixstars. giving the user a chance to verify the generated code. 2010. 64-bit). visit the FOXC website ( (32-bit. along with FOXC runtime. 2010). Also. multiple devices can be running in parallel on a multi-core system. Available OpenCL Environments This section will introduce the available OpenCL environment as of March. since multi-threading using POSIX threads are supported. but their OpenCL implementation allows the user to choose either environment. 64-bit) Further testing will be performed in the future. 41 . FOXC is a source-to-source compiler that generates readable C code that uses embedded SSE functions from an OpenCL C code. an OpenCL compiler. Hardware Tested Environment Multi-core x86 CPU. Therefore. an additional accelerator is unnecessary.com/en/foxc) NVIDIA OpenCL NVIDIA has released their OpenCL implementation for their GPU. to run program compiled using FOXC. which is the OpenCL runtime implementation. OpenCL users can use the FOXC and FOXC runtime to compile and execute a multi-core x86 program. Cent OS 5. and run a simple OpenCL program. NVIDIA also has a GPGPU development environment known as CUDA.B01-02632560-294 The OpenCL Programming Book OpenCL Setup This chapter will setup the OpenCL development environment. It is still a beta-release as of this writing (March. are softwares currently being developed by the Fixstars Corporation. x86 server Yellow Dog Enterprise Linux (x86. For the latest information. Although OpenCL is a framework that allows for parallel programming of heterogeneous systems. it can also be used for homogeneous systems. FOXC (Fixstars OpenCL Cross Compiler) FOXC.
B01-02632560-294 The OpenCL Programming Book Hardware CUDA-enabled graphics board. 64-bit) Red Had Enterprise Linux 5.com/object/cuda_learn_products. as well as their graphics boards. AMD's OpenCL environment supports both multi-core x86 CPU. AMD has a GPGPU development environment called "ATI Stream SDK". NVIDIA GeForce 8.9. 64-bit) Windows 7 (32-bit.3 (32-bit. 64-bit) Tested Environment The latest CUDA-enabled graphics boards are listed on NVIDIA's website () AMD (ATI) OpenCL ATI used to be a reputable graphic-chip vendor like NVIDIA.nvidia. 64-bit) Ubuntu 8.html). Some graphics products from AMD still have the ATI brand name.nvidia. (March 2010). 64-bit) Windows Vista (32-bit. Hardware Graphics boards by AMD. 64-bit) Yellow Dog Enterprise Linux 6.01 release. The latest supported environments are listed at (. which started to officially support OpenCL with their v2. 64-bit) Fedora 8 (32-bit.10 (32-bit. but was bought out by AMD in 2006.200 Series NVIDIA Tesla NVIDIA Quadro series Windows XP (32-bit. ATI Radeon HD 58xx/57xx/48xx ATI FirePro V8750/8700/7750/5700/3750 AMD FireStream 9270/9250 ATI Mobility Radeon HD 48xx ATI Mobility FirePro M7740 ATI Radeon Embedded E4690 Discrete GPU 42 .3 (32-bit.
offering five times the double precision performance of the previous Cell/B.com/tech/opencl/). which have yet to pass the OpenCL Spec test.6 (Snow Leopard) was the Apple OpenCL.E. Hardware Tested Environment Any Mac with an Intel CPU Mac OS X 10. made up of two POWER6+ processors. 64-bit) OpenSUSE 11. which can be downloaded from IBM Alpha Works ( (32-bit. 43 .aspx).B01-02632560-294 The OpenCL Programming Book Tested Environment Windows XP SP3 (32-bit)/SP2(64-bit) Windows Vista SP1 (32-bit. which is Apple's development environment. may help spread the use of OpenCL as a means to accelerate programs via GPGPU.E. QS22 is a blade server featuring two IBM PowerXCell 8i processors. The default support of OpenCL in the operating system. Xcode.com/gpu/ATIStreamSDKBetaProgram/Pages/default. The latest supported environments are listed on (. IBM's OpenCL includes compilers for both POWER processors.alphaworks.com/gpu/ATIStreamSDKBetaProgram/Pages/default. which was the first world-wide OpenCL release.ibm. 64-bit) Ubuntu 9.aspx) Apple OpenCL One of the main features included in MacOS X 10. which allows developers the access to OpenCL at their fingertips. which is IBM's traditional RISC processor. they are still alpha releases.6 (Snow Leopard) Apple's OpenCL compiler supports both GPUs and x86 CPUs.04 (32-bit. 64-bit) The latest list of supported hardware is listed on AMD's website (. as well as for Cell/B. processor. must be installed prior to the use of OpenCL. JS23 is another blade server.amd. IBM OpenCL IBM has released the alpha version of OpenCL Development Kit for their BladeCenter QS22 and JS23. As of this writing (March 2010).amd. 64-bit) Windows 7 (32-bit.
GCC) at default.gz -C /usr/local The following environmental variables must be set.6 (Snow Leopard) is required to use the Apple OpenCL.fixstars.com/mac/ (Figure 3. FOXC can be downloaded for free from the Fixstars website (. List 3.2: Bourne Shell export PATH=/usr/local/foxc-install/bin:${PATH} export LD_LIBRARY_PATH=/usr/local/foxc-install/lib:${LD_LIBRARY_PATH} This completes the installation of FOXC.1).1: CShell setenv PATH /usr/local/foxc-install/bin:${PATH} setenv LD_LIBRARY_PATH /usr/local/foxc-install/lib List 3. since OS X does not have the necessary development toolkits (e. Also.tar. OS IBM BladeCenter QS22 running Fedora 9 IBM BladeCenter JS23 running Red Had Enterprise Linus 5.com/en/foxc). Download the latest version of "Xcode" from. FOXC Setup This setup procedure assumes the installation of FOXC in a 64-bit Linux environment. Apple OpenCL Setup Mac OS X 10.B01-02632560-294 The OpenCL Programming Book Hardware.apple. > tar -zxf foxc-install-linux64. 44 . these kits must first be downloaded from Apple's developer site.3 Developing Environment Setup This section will walk through the setup process of FOXC. and NVIDIA OpenCL. Apple. The install package can be uncompressed as follows.g. under the directory "/usr/local".
Figure 3. You will need an ADC (Apple Developer Connection) account to download this file. You should see a file called "Xcode.1.1: Apple Developer Connection (. Figure 3. As of this writing (March 2010). The ADC Online account can be created for free. which automatically mounts the archive under /Volumes.2: Xcode Archive Content 45 .mpkg" (the name can vary depending on the Xcode version. however) (Figure 3. and this includes every tools required to start developing an OpenCL application.B01-02632560-294 The OpenCL Programming Book Xcode is a free IDE distributed by Apple.dmg file.com/mac/) Double click the downloaded .2). the latest Xcode version is 3.apple. The archive can be viewed from the Finder.2.
but there is one important step.3.4: Successful Xcode installation 46 . make sure that the box for "UNIX Dev Support" is checked.4. You may now use OpenCL on Mac OS X. Figure 3. On the screen shown in Figure 3. When you reach the screen shown in Figure 3.B01-02632560-294 The OpenCL Programming Book This file is the installation package for Xcode. Double click this file to start the installer.3: Custom Installation Screen Continue onward after making sure that the above box is checked. Most of the installation procedure is self-explanatory. Figure 3. the installation has finished successfully.
The installation procedure will be split up into that for Linux. Next.html). an upgrade or a downgrade is required. and that its version is 3.3_linux_64_190. Make sure GCC is installed. First. and for Windows. but will prove to be useful.5).gz Figure 3. • OpenCL Visual Profiler v1. Install NVIDIA OpenCL on Linux This section will walk through the installation procedure for 64-bit CentOs 5. Type the following on the command line. Type the following on the command line to get the GPU type (# means run as root).5: NVIDIA OpenCL download page 47 .nvidia. NVIDIA OpenCL uses GCC as the compiler.x prior to 4.nvidia. Downloading from this site requires user registration.tar.4 or 4. then GCC is not installed.B01-02632560-294 The OpenCL Programming Book NVIDIA OpenCL Setup NVIDIA OpenCL is supported in multiple platforms.com/object/get-opencl.run • GPU Computing SDK code samples and more: gpucomputingsdk_2.2. > gcc --version If you get an error message such as "command not found: gcc".html) (Figure 3. If the version is not supported for CUDA.run The following is optional. Download the following 2 files. you should make sure that your GPU is CUDA-enabled.0-beta_linux_64. • NVIDIA Drivers for Linux (64-bit): nvdrivers_2. # lspci | grep -i nVidia The list of CUDA-Enabled GPUs can be found online at the NVIDIA CUDA Zone ( Beta (64-bit): openclprof_1.3.com/object/cuda_gpus.3b_linux. go to the NVIDIA OpenCL download page (.
run You will get numerous prompts. Restart the X Window System after a successful installation. This requires the X Window System to be stopped. this must be stopped. which you can answer "OK" unless you are running in a special environment. # init 3 Execute the downloaded file using shell. # sh nvdrivers_2. If you are using a display manager. since it automatically restarts the X Window System. # service gdm stop Type the following to run Linux in command-line mode.29.B01-02632560-294 The OpenCL Programming Book First install the driver.3_linux_64_190. 48 . Type the following command as root if using gdb.
run You will be prompted for an install directory. • NVIDIA Drivers for WinVista and Win7 (190.nvidia.89_general. but will prove to be useful.com/object/get-opencl.exe • GPU Computing SDK code samples and more: gpucomputingsdk_2. under "Display Adapter".html) (Figure 3. Building of the SDK samples requires either Microsoft Visual Studio 8 (2005) or Visual Studio 9 (2008) (Express Edition and above). as this is required to install the "GPU Computing SDK code samples and more" package. Go to the CUDA-Enabled GPU list (link given in the Linux section) to make sure your GPU is supported. The GPU type can be verified on the "Device Manager".exe The following is optional.0 Beta (64-bit): openclprof_1. go to the NVIDIA OpenCL download page (. • OpenCL Visual Profiler v1. Next.3b_linux. This completes the installation procedure for Linux.zip Double click the download executable for the NVIDIA driver in order to start the installation procedure.89): nvdrivers_2. Install NVIDIA OpenCL on Windows This section will walk through the installation on 32-bit Windows Vista. Installation of the SDK requires user registration. Type the following on the command line. after the NVIDIA driver is installed.3_winvista_32_190. Download the following 2 files. After installation is completed successfully.0-beta_windows.5). log off as root. install the GPU Computing SDK. the SDK will be installed in the following directories: 49 . Downloading from this site requires user registration.3b_win_32.B01-02632560-294 The OpenCL Programming Book # startx At this point. Restart your PC when prompted. Next. and log back in as a user. Make sure this is installed. > sh gpucomputingsdk_2. which is $HOME by default.
dat. 1. On the right panel. Copy usertype.” Copy this file to the following directory.dat” already exists in the directory. On the left panel.B01-02632560-294 The OpenCL Programming Book • Windows XP C:¥Documents and Settings¥All Users¥Application Data¥NVIDIA Corporation¥NVIDIA GPU Computing SDK¥OpenCL • Windows Vista / Windows 7 C:¥ProgramData¥NVIDIA Corporation¥NVIDIA GPU Computing SDK¥OpenCL Restart your system after the SDK installation. double click on the “NVIDIA GPU Computing SDK Browser” icon which should have been created on your desktop. Some samples include a “Whitepaper”. The sample code is listed in increasing level of difficulty. To do so. you should see a file called “usertype. use an editor to append the content of NVIDIA SDK’s “usertype.dat” to the existing file. which is a detailed technical reference for that sample. If running on 32-bit Windows C:¥Program Files¥Microsoft Visual Studio 8¥Common7¥IDE (VC8) C:¥Program Files¥Microsoft Visual Studio 9¥Common7¥IDE (VC9) If running on 64-bit Windows C:¥Program Files (x86)¥Microsoft Visual Studio 8¥Common7¥IDE (VC8) C:¥Program Files (x86)¥Microsoft Visual Studio 9¥Common7¥IDE (VC9) If “usertype. type ". and then click on "Option". Visual Studio Setup Start Visual Studio. 2.cl" to the box labeled 50 . The following procedure will enable syntax highlighting. You will see a list of all the sample programs in the SDK. then "File Extension". Open the “OpenCL Samples” tab to see all the sample code written in OpenCL. go to the "Tool" Menu Bar. You should now be able to run the OpenCL sample program inside the SDK.dat Under the “doc” folder found inside the SDK installation directory. Syntax highlighting of OpenCL code on Visual Studio is not supported by default. select "Text Editor".
(The code can be downloaded from. Visual Studio will now perform syntax highlighting on . clext.dll If an application explicitly specifies the link to OpenCL. Hello World List 3. cl_gl. Since we have not yet gone over the OpenCL grammar.com/books/opencl) List 3. the string set on the kernel will be copied over to the host side.kernel (hello.4 shows the familiar "Hello.h.3 and 3.h.3: Hello World . When developing an OpenCL program. Since standard in/out cannot be used within the kernel. 51 .lib (32-bit version and 64-bit versions exist) • Dynamic Link Library (Default: "¥Windows¥system32") OpenCL. which can then be outputted. OpenCL. we will use the kernel only to set the char array.cl files.fixstars. World!" program.h • Library (Default: "NVIDIA GPU Computing SDK¥OpenCL¥common¥lib¥[Win32|x64]" OpenCL. we will start learning the OpenCL programming basics by building and running actual code.B01-02632560-294 The OpenCL Programming Book "Extension". First OpenCL Program From this section onward. the required files for building are located as follows. cl_platform.h.lib is not required at runtime.cl) 001: __kernel void hello(__global char* string) 002: { 003: string[0] = 'H'. Select "Microsoft Visual C++" on the drop-down menu. • Header File (Default: "NVIDIA GPU Computing SDK¥OpenCL¥common¥inc¥CL") cl. written in OpenCL. you should concentrate on the general flow of OpenCL programming. 005: string[2] = 'l'. In this program. 004: string[1] = 'e'.dll. 006: string[3] = 'l'. and then click the "Add" button.
015: string[12] = '!'. 016: string[13] = '¥0'. 013: string[10] = 'l'. 012: string[9] = 'r'. 021: cl_platform_id platform_id = NULL.h> 003: 004: #ifdef __APPLE__ 005: #include <OpenCL/opencl.c) 001: #include <stdio. 016: cl_context context = NULL. 022: cl_uint ret_num_devices.4: Hello World . 018: cl_mem memobj = NULL. 009: string[6] = ' '.h> 008: #endif 009: 010: #define MEM_SIZE (128) 011: #define MAX_SOURCE_SIZE (0x100000) 012: 013: int main() 014: { 015: cl_device_id device_id = NULL. 008: string[5] = '. 017: } List 3. 010: string[7] = 'W'. 014: string[11] = 'd'. 020: cl_kernel kernel = NULL. 011: string[8] = 'o'. 52 . 023: cl_uint ret_num_platforms. 017: cl_command_queue command_queue = NULL. 019: cl_program program = NULL.host (hello.h> 006: #else 007: #include <CL/cl.'.B01-02632560-294 The OpenCL Programming Book 007: string[4] = 'o'.h> 002: #include <stdlib.
040: source_size = fread(source_str. NULL. &ret). &device_id.B01-02632560-294 The OpenCL Programming Book 024: cl_int ret. fp). device_id. "r"). 027: 028: FILE *fp. &ret). 046: 047: /* Create OpenCL context */ 048: context = clCreateContext(NULL.¥n").cl". NULL. 038: } 039: source_str = (char*)malloc(MAX_SOURCE_SIZE). 1. &ret_num_platforms). &ret_num_devices). &platform_id. 037: exit(1). MAX_SOURCE_SIZE. 025: 026: char string[MEM_SIZE]. 055: 056: /* Create Kernel Program from the source */ 057: program = clCreateProgramWithSource(context. 042: 043: /* Get Platform and Device Info */ 044: ret = clGetPlatformIDs(1. NULL. 045: ret = clGetDeviceIDs(platform_id./hello. &device_id. &ret). 1. CL_DEVICE_TYPE_DEFAULT. 041: fclose(fp). 030: char *source_str. "Failed to load kernel. (const char **)&source_str. 53 . 1. 035: if (!fp) { 036: fprintf(stderr. 1. 031: size_t source_size. 052: 053: /* Create Memory Buffer */ 054: memobj = clCreateBuffer(context. CL_MEM_READ_WRITE.MEM_SIZE * sizeof(char). 0. 029: char fileName[] = ". 032: 033: /* Load the source code containing the kernel*/ 034: fp = fopen(fileName. 049: 050: /* Create Command Queue */ 051: command_queue = clCreateCommandQueue(context.
083: ret = clReleaseProgram(program).string. 0. 0. 086: ret = clReleaseContext(context). 082: ret = clReleaseKernel(kernel). 068: 069: /* Execute OpenCL Kernel */ 070: ret = clEnqueueTask(command_queue. 084: ret = clReleaseMemObject(memobj). 062: 063: /* Create OpenCL Kernel */ 064: kernel = clCreateKernel(program. NULL. 065: 066: /* Set OpenCL Kernel Parameters */ 067: ret = clSetKernelArg(kernel.1). 0. 075: 076: /* Display Result */ 077: puts(string). NULL. 085: ret = clReleaseCommandQueue(command_queue). NULL. NULL). 074: MEM_SIZE * sizeof(char). kernel. 087: 088: free(source_str). 54 . 081: ret = clFinish(command_queue). sizeof(cl_mem). 089: 090: return 0. "hello". NULL).B01-02632560-294 The OpenCL Programming Book 058: (const size_t *)&source_size. &ret).NULL). 0. CL_TRUE. &ret). NULL. 078: 079: /* Finalization */ 080: ret = clFlush(command_queue). &device_id. 059: 060: /* Build Kernel Program */ 061: ret = clBuildProgram(program. (void *)&memobj). 1. 071: 072: /* Copy results from the memory buffer */ 073: ret = clEnqueueReadBuffer(command_queue. 091: } The include header is located in a different directory depending on the environment (Table 3. memobj.
B01-02632560-294 The OpenCL Programming Book Make sure to specify the correct location.h CL/cl. The kernel and host code are assumed to exist within the same directory.0-beta4-lnx32 (32-bit Linux) Path-to-AMD/ati-stream-sdk-v2.1: Include Header Location (As of March.." should be replaced with the corresponding OpenCL SDK path.1: Include header location (as of March 2010) OpenCL implementation AMD Apple FOXC NVIDIA Include Header CL/cl..2.h OpenCL/opencl. Table 3. Table 3. The default SDK path is as shown in Figure 3.h CL/cl.h The sample code defines the following macro so that the header is correctly included in any environment. This section will describe the procedure under Linux/Mac OS X. The procedures for building vary depending on the OpenCL implementation.h> #endif Building in Linux/Mac OS X Once the program is written.2: Path to SDK SDK AMD Stream SDK 2.0 beta4 Path Path-to-AMD/ati-stream-sdk-v2. we are now ready to build and run the program. List 3. "path-to-. 2010) #ifdef __APPLE__ #include <OpenCL/opencl.h> #else #include <cl.0-beta4-lnx64 (64-bit Linux) Path-to-foxc/foxc-install FOXC 55 .
> make amd (Linux) > make apple (Mac OS X) > make foxc (Linux) > make nvidia (Linux) This should create an executable with the name "hello" in working directory.-rpath.-rpath./path-to-AMD/lib/x86_64 -lOpenCL (64-bit Linux) FOXC > gcc -I /path-to-foxc/include -L /path-to-foxc/lib -o hello hello.-rpath.c -Wl.c -Wl. > . you should get "Hello World!" on the screen.c -lOpenCL (64-bit Linux) Alternatively. If successful./path-to-AMD/lib/x86 -lOpenCL (32-bit Linux) > gcc -I /path-to-AMD/include -L/path-to-AMD/lib/x86_64 -o hello hello.c -Wl.B01-02632560-294 The OpenCL Programming Book NVIDIA GPU Computing SDK $(HOME)/NVIDIA_GPU_Computing_SDK (Linux) The build command on Linux/Max OS X are as follows: AMD OpenCL > gcc -I /path-to-AMD/include -L/path-to-AMD/lib/x86 -o hello hello./hello 56 . Run the executable as follows.c -lOpenCL (32-bit Linux) > gcc -I /path-to-NVIDIA/OpenCL/common/inc -L /path-to-NVIDIA/OpenCL/common/lib/Linux64 -o hello hello. you can use the Makefile included with the sample code to run the OpenCL code in various platforms as written below.c -framework opencl NVIDIA > gcc -I /path-to-NVIDIA/OpenCL/common/inc -L /path-to-NVIDIA/OpenCL/common/lib/Linux32 -o hello hello./path-to-foxc/lib -lOpenCL Apple > gcc -o hello hello.
go to “Linker” -> “Input”. Build and run the 57 . and in the box for “Additional library path”. and in the box for "Additional Dependencies". go to "Linker" -> "Input".B01-02632560-294 The OpenCL Programming Book Hello World! Building on Visual Studio This section will walk through the building and execution process using Visual C++ 2008 Express under 32-bit Windows Vista environment. type the following. then add the following in the box for “Additional include directories”: NVIDIA C:¥ProgramData¥NVIDIA Corporation¥NVIDIA GPU Computing SDK¥OpenCL¥common¥inc AMD C:¥Program Files¥ATI Stream¥include 2. NVIDIA C:¥ProgramData¥NVIDIA Corporation¥NVIDIA GPU Computing SDK¥OpenCL¥common¥lib¥Win32 AMD C:¥Program Files¥ATI Stream¥lib¥x86 3. Both NVIDIA and AMD OpenCL. From the project page. go to “C/C++” -> “General”. type the following.lib These should apply to All Configurations. which can be selected on the pull-down menu located on the top left corner. From the project page. From the project page. 1. The environment should now be setup to allow an OpenCL code to be built on. The OpenCL header file and library can be included to be used on a project using the following steps.
58 . and make sure you get the correct output.B01-02632560-294 The OpenCL Programming Book sample code.
4 hello. The OpenCL grammar will be explained in detail in Chapter 5. The sections to follow will walk through each code.c.3 hello. but for the time being. • The function specifier "__kernel" is used when declaring the "hello" function • The address specifier "__global" is used to define the function's string argument 59 . you can think of it as being the same as the standard C language. The device is programmed in OpenCL C. you should have the tools necessary for implementing a simple OpenCL program. The host is programmed in C/C++ using an OpenCL runtime API. You should also know the difference between a host memory and a device memory. as well as for the device side. By now. Basic Program Flow The previous chapter introduced the procedure for building and running an existing sample code. OpenCL Program Creating an OpenCL program requires writing codes for the host side. Kernel Code The function to be executed on the device is defined as shown in List 4. you should have an idea of the basic role of a host program and a kernel program. as well as when to use them. This section will walk through the actual code of the "Hello. List 4. as shown in List 3. World!" program introduced in the last chapter.cl.1: Declaring a function to be executed on the kernel 001: __kernel void hello(__global char * string) The only differences with standard C are the following.B01-02632560-294 The OpenCL Programming Book Basic OpenCL This chapter will delve further into writing codes for the host and the device.1. After reading this chapter. as shown in List 3.
execution. it will assume the address space to be __private.B01-02632560-294 The OpenCL Programming Book The "__kernel" specifies the function to be executed on the device. and private memory. Create program object 8. Host Code The host program tells the device to execute the kernel using the OpenCL runtime API. the clEnqueueTask() is called from the host to process the kernel. which is the device-side main memory. Create kernel object 10. • Task call: clEnqueueTask() • Data-parallel call: clEnqueueNDRangeKernel() Since the kernel is not of a data-parallel nature. 1. It must be called by the host. Select device 3. Create memory objects 6. Create Context 4. Read kernel file 7. constant. __constant. Read memory object 60 . Compile kernel 9. which includes initialization. Get a list of available platforms 2. If this is not specified. which is the device-side register. The procedure. which is done by using one of the following OpenCL runtime API commands. Execute kernel (Enqueue task) ← hello() kernel function is called here 12. local. but other setup procedures must be performed in order to actually run the code. is listed below. which is specified by __global. Set kernel arguments 11. The __global address specifier for the variable "string" tells the kernel that the address space to be used is part of the OpenCL global memory. The kernel is only allowed read/write access to global. and finalization. __private. Create command queue 5. respectively. Telling the device to execute the hello() kernel only requires the clEnqueueTask() command in the OpenCL runtime API. __local.
. which specifies whatever set as default in the platform to be used as the device.. CL_DEVICE_TYPE_DEFAULT. cl_uint ret_num_platforms.. If the desired device is the GPU.4. cl_uint ret_num_devices. The 2nd argument specifies the device type. The 3rd argument returns the number of OpenCL platforms that can be used. 021: .4. 044: ret = clGetPlatformIDs(1. &ret_num_platforms). cl_platform_id platform_id = NULL The platform model in OpenCL consists of a host connected to one or more OpenCL devices.. The 1st argument specifies how many OpenCL platforms to find which most of the time is one. &platform_id. which is returned as a list to the pointer platform_id of type cl_platform_id. 015: .. CL_DEVICE_TYPE_DEFAULT is passed. 022: . &device_id. This is done in the following code segment from hello.. 045: ret = clGetDeviceIDs(platform_id.. The 1st argument is the platform that contains the desired device. Free objects We will go through each step of the procedure using hello.B01-02632560-294 The OpenCL Programming Book 13. &ret_num_devices). then this should be CL_DEVICE_TYPE_GPU. In this case. 61 . Select Device The next step is to select a GPU device within the platform. Get a List of Available Platform The first thing that must be done on the host-side is to get a list of available OpenCL platforms. 1. This is done in the following code segment from hello.c as an example. cl_device_id device_id = NULL. The clGetDeviceIDs() function in line 45 selects the device to be used. 023: .c in List 3. and if it is CPU.c in List 3. The clGetPlatformIDs() function in line 44 allows the host program to discover OpenCL devices.. then this should be CL_DEVICE_TYPE_CPU.
which will be discussed later. &device_id.c in List 3. device_id. The 4th argument returns the handle to the selected device. In OpenCL. Create Memory Object 62 . For each device. This is done in the following code segment from hello. 051: command_queue = clCreateCommandQueue(context.. Create Command Queue The command queue is used to control the device.4. The 3rd argument specifies the list of device handlers. which will be used for memory copy and kernel execution.. The 5th argument returns the number of devices that corresponds to the device type specified in the 2nd argument. Create Context After getting the device handle.4. cl_context context = NULL. the next step is to create an OpenCL Context.B01-02632560-294 The OpenCL Programming Book The 3rd argument specifies the number of devices to use. The context is used by the OpenCL runtime for managing objects. This is done in the following code segment from hello. The function returns a handle to the command queue. If the specified device does not exist. The clCreateCommandQueue() function in line 51 creates the command queue. &ret). is performed through this command queue. An OpenCL context is created with one or more devices. The 2nd argument specifies the device which will execute the command in the queue. 016: . using the clCreateContext() function in line 48.. &ret). NULL. The 1st argument specifies the context in which the command queue will become part of.c in List 3. one or more command queue objects must be created. any command from the host to the device. then ret_num_devices will be set to 0. cl_command_queue command_queue = NULL. The 2nd argument specifies the number of devices to use. 1. such as kernel execution or memory copy. 048: context = clCreateContext(NULL.. 017: . NULL. 0.
030: char *source_str.cl kernel in list 3.c in List 3. This may be in a form of an executable binary. MEM_SIZE * sizeof(char). "Failed to load kernel. the kernel can only be executed via the host-side program. The clCreateBuffer() function in line 54 allocates space on the device memory [14]./hello.B01-02632560-294 The OpenCL Programming Book To execute a kernel. World!". this action must be performed on the host-side. "r"). 037: exit(1). 035: if (!fp) { 036: fprintf(stderr. or a source code which must be compiled using an OpenCL compiler. cl_mem memobj = NULL.cl". this allocated storage space gets the character string "Hello. In this example. CL_MEM_READ_WRITE.4. which is done in the hello. The CL_MEM_READ_WRITE flag allows the kernel to both read and write to the allocated device memory. This is done in the following code segment from hello. 029: char fileName[] = ".¥n"). The 3rd argument specifies the number of bytes to allocate. The allocated memory can be accessed from the host side using the returned memobj pointer. However. &ret). which allows the host to access the device memory. the host program must first read the kernel program. 031: size_t source_size. Therefore. a memory object must be created. To do this. the host reads the kernel source code. 028: FILE *fp. NULL. This is done using the standard fread() function. 054: memobj = clCreateBuffer(context. In this example. all data to be processed must be on the device memory. The 1st argument specifies the context in which the memory object will become part of.3. The 2nd argument specifies a flag describing how it will be used. 038: } 63 . the kernel does not have the capability to access memory outside of the device. 032: 033: /* Load kernel code */ 034: fp = fopen(fileName. Read Kernel File As mentioned earlier. To do this... 018: .
since the kernel program can contain multiple kernel functions [15].B01-02632560-294 The OpenCL Programming Book 039: source_str = (char*)malloc(MAX_SOURCE_SIZE). The 2nd argument is the number of target devices. 041: fclose(fp)..4. &device_id. the next step is to create a kernel object. The 3rd argument specifies the read-in source code. (const size_t *)&source_size. 040: source_size = fread(source_str. it is necessary to specify the kernel function's name when creating the kernel object. and the 4th argument specifies the size of the source code in bytes. 1. 061: ret = clBuildProgram(program. The clBuildProgram in line 61 builds the program object to create a binary. 057: 058: program = clCreateProgramWithSource(context. (const char **)&source_str. 019: .c in List 3. &ret). If the program object is to be created from a binary. Create Kernel Object Once the program object is compiled. Each kernel object corresponds to each kernel function. This is done by creating a program object. fp). Create Program Object Once the source code is read. The program object is created using the clCreateProgramWithSource() function. NULL. 1. cl_program program = NULL. The 1st argument is the program object to be compiled. The 3rd argument is the target device for which the binary is created. NULL). Therefore. MAX_SOURCE_SIZE. as shown in the following code segment from hello. The 4th argument specifies the compiler option string. This step is required.. Note that this step is unnecessary if the program is created from binary using clCreateProgramWithBinary(). clCreateProgramWithBinary() is used instead. NULL. Compile The next step is to compile the program object using an OpenCL C compiler. 1. this code must be made into a kernel program. 64 .
but it is possible to have multiple kernel functions for one program object. 067: ret = clSetKernelArg(kernel.4 65 .c in List 3. This is done by the code segment from hello. 0. meaning the 0th argument to the kernel is being set.cl in List 3. clSetKernelArg(kernel. (void *)&a). "hello". (void *) &memobj). Execute Kernel (Enqueue task) The kernel can now finally be executed. In this way. and the 2nd argument sets the kernel function name. the pointer to the allocated memory object is passed in. the arguments to the kernel must be set. with the 3rd argument specifying this argument size in bytes. sizeof(int). the clSetKernelArg() must be called for each kernel arguments. 0. In this example. the clCreateKernel() function must be called multiple times. This example only has one kernel function for one program object. 064: kernel = clCreateKernel(program.. This pointer must be specified on the host-side. sizeof(cl_mem). In this example. In this way. int a =10. The 4th argument is the pointer to the argument to be past in.. The 2nd argument selects which argument of the kernel is being passed in. since each kernel object corresponds to one kernel function.3 expects a pointer to a string array to be built on the device side. The 1st argument is the kernel object.B01-02632560-294 The OpenCL Programming Book 020: cl_kernel kernel = NULL. the memory management can be performed on the host-side. hello. Passing of the host-side data as a kernel argument can be done as follows. Set Kernel Arguments Once the kernel object is created. The 1st argument specifies the program object. However. which is 0 in this example. &ret). The clSetKernelArg() function in line 67 sets the arguments to be passed into the kernel. . The clCreateKernel() function in line 64 creates the kernel object from the program.
073: 074: ret = clEnqueueReadBuffer(command_queue. In order to wait for the kernel to finish executing. to be executed on the compute unit on the device. which keeps the host from executing the next command until the data copy finishes. The code that follows the clEnqueueTask() function should account for this. The "CL_TRUE" that is passed in makes the function synchronous. The 6th argument is the pointer to the host-side memory where the data is copied over to. CL_TRUE. meaning it just throws the kernel into the queue to be executed on the device. MEM_SIZE * sizeof(char). Also. that the "hello" kernel was queued asynchronously. the data copy instruction is placed in the command queue before it is processed.c in List 3. the clEnqueueTask() function is used for task-parallel instructions. 0. This is done in the following code segment from hello. string. This throws the kernel into the command queue. Read from the memory object After processing the data on the kernel. memobj. To copy the data from the host-side memory to the device-side memory.4. As the term "Enqueue" in the function indicates. the result must now be transferred back to the host-side... The 3rd argument specifies whether the command is synchronous or asynchronous. NULL. however.B01-02632560-294 The OpenCL Programming Book 070: ret = clEnqueueTask(command_queue. which queues the task and immediately executes the next instruction on the host-side. NULL). 026: . the 5th argument of the above function must be set as an event object. the clEnqueueWriteBuffer() function is used instead. 0. If "CL_FALSE" is passed in instead. NULL. This should make you question whether the memory copy from the device is reading valid data. NULL). Note that this function is asynchronous. while the 5th argument specifies the size of the data in bytes. the copy becomes asynchronous. This will be explained in "4-3-3 Task Parallelism and Event Object". 0. char string[MEM_SIZE]. The 2nd argument is the pointer to the memory on the device to be copied over to the host side. 66 . Recall. kernel. Data-parallel instructions should use the clEnqueueNDRangeKernel() function instead. The clEnqueueReadBuffer() function in lines 73~74 copies the data on the device-side memory to the host-side memory.
This is done in the code segment shown below from hello. However. the data copy may start before the kernel finishes its processing of the data. and a way to do this is explained in "4-3 Kernel Call". If the command queue was set to allow asynchronous execution. a kernel can be compiled either online or offline (Figure 4. in this case it is OK. ret = clReleaseMemObject(memobj). 082: 083: 084: 085: 086: ret = clReleaseKernel(kernel). all the objects need to be freed. since the same object can be used repeatedly. ret = clReleaseProgram(program). the 3rd argument passed in was a 0. it might make you think that this is a mistake. Figure 4.c in List 3. ret = clReleaseContext(context). the host-side's object management memory space may run out. the data copy command waits until the previous command in the queue. Therefore. is finished. Asynchronous kernel execution may be required in some cases. In real-life applications. the "hello" kernel.4. in which case the OpenCL runtime will throw an error. If too many objects are created without freeing. ret = clReleaseCommandQueue(command_queue). however.1). which will achieve incorrect results. Free Objects Lastly. This is because when the command queue was created.1: Offline and Online Compilation 67 . so object creation/deletion cycle do not usually have to be repeated. Online/Offline Compilation In OpenCL. which makes the queued commands execute in order.B01-02632560-294 The OpenCL Programming Book Looking just at the host-side code. the main course of action is usually a repetition of setting kernel arguments or the host-to-device copy -> kernel execution -> device-to-host copy cycle.
68 . However. multiple kernel binaries must be included. and the generated binary is what gets loaded using the OpenCL API. and that adaptive compiling of the kernel is possible. It also makes the testing of the kernel easier during development. This method is commonly known as JIT (Just in time) compilation. thus increasing the size of the executable file. this method may not be suited for commercial applications. this is not suited for embedded systems that require real-time processing. In a way. AMD. The problem with this method is that in order to execute the program on various platforms. the kernel is pre-built using an OpenCL compiler. FOXC on the other hand includes a stand-alone OpenCL kernel compiler. In "online-compilation". Since the kernel binary is already built. Hence. the kernel is built from source during runtime using the OpenCL runtime library. since OpenCL is a programming framework for heterogeneous environments. In fact. the time lag between starting the host code and the kernel getting executed is negligible. The OpenCL runtime library contains the set of APIs that performs the above operations.B01-02632560-294 The OpenCL Programming Book The basic difference between the 2 methods is as follows: • Offline: Kernel binary is read in by the host code • Online: Kernel source file is read in by the host code In "offline-compilation". The advantage of this method is that the host-side binary can be distributed in a form that's not device-dependent. since it gets rid of the need to compile the kernel each time. since the kernel code is in readable form. and Apple. the online compilation support should not come as a shock. Also. which makes the process of making a kernel binary intuitive. a stand-alone OpenCL compiler is not available for the OpenCL environment by NVIDIA. the built kernels has to be written to a file during runtime by the host program. in order to create a kernel binary in these environments.
cl_program program = NULL.B01-02632560-294 The OpenCL Programming Book We will now look at sample programs that show the two compilation methods. cl_uint ret_num_platforms./kernel. cl_int ret.h> 006: #else 007: #include <CL/cl.h> 003: 004: #ifdef __APPLE__ 005: #include <OpenCL/opencl. 69 . The first code shows the online compilation version.h> 002: #include <stdlib. char *source_str. float mem[MEM_SIZE]. List 4. cl_uint ret_num_devices. cl_platform_id platform_id = NULL. cl_kernel kernel = NULL. const char fileName[] = ". cl_device_id device_id = NULL. size_t source_size.h> 008: #endif 009: 010: #define MEM_SIZE (128) 011: #define MAX_SOURCE_SIZE (0x100000) 012: 013: int main() 014: { 015: 016: 017: 018: 019: 020: 021: 022: 023: 024: 025: 026: 027: 028: 029: 030: 031: FILE *fp. cl_mem memobj = NULL.cl". cl_context context = NULL.2: Online Compilation version 001: #include <stdio. cl_command_queue command_queue = NULL.
memobj. 0. NULL. /* Transfer data to memory buffer */ ret = clEnqueueWriteBuffer(command_queue. i++) { mem[i] = i. /*Initialize Data */ for (i = 0. i < MEM_SIZE. &ret). 0. fp). 1. &device_id. exit(1). &ret). /* Create memory buffer*/ memobj = clCreateBuffer(context. 70 . NULL. MEM_SIZE * sizeof(float). MEM_SIZE * sizeof(float). CL_TRUE. fclose(fp). "Failed to load kernel. &device_id. &ret_num_devices). mem. /* Create Command Queue */ command_queue = clCreateCommandQueue(context. } source_str = (char *)malloc(MAX_SOURCE_SIZE). if (!fp) { fprintf(stderr. /* Create OpenCL Context */ context = clCreateContext(NULL. &ret). CL_DEVICE_TYPE_DEFAULT. 1. MAX_SOURCE_SIZE. &ret_num_platforms). CL_MEM_READ_WRITE. ret = clGetDeviceIDs(platform_id. device_id. /* Load kernel source code */ fp = fopen(fileName. NULL. &platform_id. } /* Get platform/device information */ ret = clGetPlatformIDs(1. 1.B01-02632560-294 The OpenCL Programming Book: cl_int i. source_size = fread(source_str.¥n"). 0. "r"). NULL). NULL.
MEM_SIZE * sizeof(float).B01-02632560-294 The OpenCL Programming Book: /* Create Kernel program from the read in source */ program = clCreateProgramWithSource(context. 0. ret = clFinish(command_queue). (const size_t *)&source_size. 0. /* Display result */ for (i=0. /* Execute OpenCL kernel */ ret = clEnqueueNDRangeKernel(command_queue. NULL. /* Set OpenCL kernel argument */ ret = clSetKernelArg(kernel. i. NULL. ret = clReleaseProgram(program). 1. &ret). CL_TRUE. /* Create OpenCL Kernel */ kernel = clCreateKernel(program. size_t local_work_size[3] = {MEM_SIZE. 0}. 1. (void *)&memobj). 0. kernel. &device_id. i < MEM_SIZE. mem. 1. &ret). 0. ret = clReleaseKernel(kernel). global_work_size. } /* Finalization */ ret = clFlush(command_queue). i++) { printf("mem[%d] : %f¥n". 0. /* Transfer result from the memory buffer */ ret = clEnqueueReadBuffer(command_queue. (const char **)&source_str. NULL. 71 . memobj. local_work_size. ret = clReleaseCommandQueue(command_queue). NULL). /* Build Kernel Program */ ret = clBuildProgram(program. ret = clReleaseMemObject(memobj). NULL. NULL). NULL. 0. sizeof(cl_mem). mem[i]). 0}. NULL). "vecAdd". size_t global_work_size[3] = {MEM_SIZE.
cl_command_queue command_queue = NULL. cl_mem memobj = NULL. cl_device_id device_id = NULL. cl_platform_id platform_id = NULL.B01-02632560-294 The OpenCL Programming Book 098: 099: 100: 101: 102: 103: ret = clReleaseContext(context). free(source_str).h> 003: 004: #ifdef __APPLE__ 005: #include <OpenCL/opencl. cl_uint ret_num_platforms.h> 006: #else 007: #include <CL/cl. cl_int ret.3).h> 002: #include <stdlib. cl_uint ret_num_devices. List 4. cl_context context = NULL. 72 .h> 008: #endif 009: 010: #define MEM_SIZE (128) 011: #define MAX_BINARY_SIZE (0x100000) 012: 013: int main() 014: { 015: 016: 017: 018: 019: 020: 021: 022: 023: 024: 025: 026: float mem[MEM_SIZE]. cl_program program = NULL. return 0.3 Offline compilation version 001: #include <stdio. cl_kernel kernel = NULL. } The following code shows the offline compilation version (List 4.
} binary_buf = (char *)malloc(MAX_BINARY_SIZE). char fileName[] = ". NULL. /* Create OpenCL context*/ context = clCreateContext(NULL. &device_id. 1. cl_int binary_status. NULL. fclose(fp). CL_MEM_READ_WRITE. FILE *fp./kernel. if (!fp) { fprintf(stderr. &ret_num_devices). i++) { mem[i] = i. &ret). 1. /* Load kernel binary */ fp = fopen(fileName. "Failed to load kernel. fp). exit(1). &device_id. size_t binary_size. MAX_BINARY_SIZE. MEM_SIZE * sizeof(float).¥n"). char *binary_buf. 73 . device_id. &platform_id. &ret_num_platforms).B01-02632560-294 The OpenCL Programming Book: /* Create memory buffer */ memobj = clCreateBuffer(context. /* Create command queue */ command_queue = clCreateCommandQueue(context. binary_size = fread(binary_buf. cl_int i. "r"). /* Get platform/device information */ ret = clGetPlatformIDs(1. &ret). } /* Initialize input data */ for (i = 0. 0. 1. CL_DEVICE_TYPE_DEFAULT.clbin". i < MEM_SIZE. ret = clGetDeviceIDs(platform_id.
0. mem[i]). mem. NULL). /* Create kernel program from the kernel binary */ program = clCreateProgramWithBinary(context. 0.B01-02632560-294 The OpenCL Programming Book NULL.: /* Finalization */ ret = clFlush(command_queue). i++) { printf("mem[%d] :%f¥n". CL_TRUE. /* Copy result from the memory buffer */ ret = clEnqueueReadBuffer(command_queue. 1. sizeof(cl_mem). 0}. 0. 0. } /* Display results */ for (i=0. memobj. local_work_size. &ret). 0}. NULL). ret). 0. (void *)&memobj). NULL. CL_TRUE. /* Transfer data over to the memory buffer */ ret = clEnqueueWriteBuffer(command_queue. NULL). &binary_status. i < MEM_SIZE. NULL. NULL. memobj. sizeof(float). 74 . i. &ret). size_t local_work_size[3] = {MEM_SIZE. MEM_SIZE * /* Execute OpenCL kernel */ ret = clEnqueueNDRangeKernel(command_queue. MEM_SIZE * sizeof(float). 1. size_t global_work_size[3] = {MEM_SIZE. 0. &ret). &device_id. /* Set OpenCL kernel arguments */ ret = clSetKernelArg(kernel. 0. "vecAdd". mem. 0. NULL. *)&binary_size. global_work_size. (const size_t (const unsigned char **)&binary_buf. printf("err:%d¥n". /* Create OpenCL kernel */ kernel = clCreateKernel(program. kernel.
List 4. ret = clReleaseProgram(program). free(binary_buf).B01-02632560-294 The OpenCL Programming Book 093: 094: 095: 096: 097: 098: 099: 100: 101: 102: 103: } ret = clFinish(command_queue).5: Online compilation version . ret = clReleaseKernel(kernel). fp = fopen(fileName. "Failed to load kernel.4: Kernel program 001: __kernel void vecAdd(__global float* a) 002: { 003: 004: 005: 006: } a[gid] += a[gid]. "r"). if (!fp) { fprintf(stderr. The kernel program performs vector addition.5).4. fp). source_size = fread(source_str. 75 . ret = clReleaseContext(context). MAX_SOURCE_SIZE. The first major difference is the fact that the kernel source code is read in the online compile version (List 4.2 and List 4. so we will focus on their differences. ret = clReleaseCommandQueue(command_queue). return 0. 1. We will take a look at the host programs shown in List 4.¥n").3. List 4. exit(1). fclose(fp). int gid = get_global_id(0).Reading the kernel source code 035: 036: 037: 038: 039: 040: 041: 042: } source_str = (char *)malloc(MAX_SOURCE_SIZE). The two programs are almost identical. It is shown below in list 4. ret = clReleaseMemObject(memobj).
B01-02632560-294 The OpenCL Programming Book The source_str variable is a character array that merely contains the content of the source file. exit(1).¥n"). "Failed to load kernel. &device_id.7: Offline compilation . List 4. and then built. "r").clbin kernel. (const char **)&source_str. since the data is being read into a buffer of type char.Create kernel program 065: 066: 067: 068: 069: /* Build kernel program */ ret = clBuildProgram(program. fp). With offline compilation.7). NULL. /* Create kernel program from the source */ program = clCreateProgramWithSource(context. 1. In order to execute this code on the kernel. if (!fp) { fprintf(stderr. &ret). 1. > /path-to-foxc/bin/foxc -o kernel. this can be done as follows. 1. we will look at the source code for the offline compilation version (List 4. NULL. This means that the kernel source code must be compiled beforehand using an OpenCL compiler. binary_size = fread(binary_buf. 76 .Reading the kernel binary 036: 037: 038: 039: 040: 041: 042: 043: } binary_buf = (char *)malloc(MAX_BINARY_SIZE). fp = fopen(fileName. The code looks very similar to the online version. it must be built using the runtime compiler. NULL).cl The online compilation version required 2 steps to build the kernel program. MAX_BINARY_SIZE. The program is first created from source. In FOXC.6: Online compilation version . fclose(fp). (const size_t *)&source_size. Next.6. The difference is that the data on the buffer can be directly executed. the clCreateProgramWithSource() is replaced with clCreateProgramWithBinary. This is done by the code segment shown below in List 4. List 4.
To summarize. the GPUs are incapable of running different tasks in parallel. the difference between the two is whether the same kernel or different kernels are executed in parallel. &ret). Change clCreateProgramWithSource() to clCreateProgramWithBinary() 3. parallelizable code is either "Data Parallel" or "Task Parallel". At present. &device_id.2. &binary_status. 1. there is no reason for another build step as in the online compilation version. but hardware such as instruction fetch and program counters are shared across the processors. Calling the Kernel Data Parallelism and Task Parallelism As stated in the "1-3-3 Types of Parallelism" section. Since the kernel is already built. As shown in Figure 4. Since the processors can only process the same set of instructions across the cores. In OpenCL. most GPUs contain multiple processors. the processors scheduled to process Task B must be in idle mode until Task A is finished. in order to change the method of compilation from online to offline. the number of tasks equal to the number of processors can be performed at once. 77 .3 shows the case when multiple tasks are scheduled to be performed in parallel on the GPU.B01-02632560-294 The OpenCL Programming Book 067: 068: program = clCreateProgramWithBinary(context. *)&binary_size. For this reason. the following steps are followed: 1. Figure 4. (const size_t (const unsigned char **)&binary_buf. The difference becomes obvious in terms of execution time when executed on the GPU. Get rid of clBuildProgram() This concludes the differences between the two methods. when multiple processors perform the same task. Read the kernel as a binary 2. See chapter 7 for the details on the APIs used inside the sample codes.
This section will use vector-ized arithmetic operation to explain the basic method of implementations for data parallel and task parallel commands.B01-02632560-294 The OpenCL Programming Book Figure 4. 78 .2: Efficient use of the GPU Figure 4. When developing an application. called clEnqueueNDRangeKernel().3: Inefficient use of the GPU For data parallel tasks suited for a device like the GPU. subtraction. OpenCL provides an API to run the same kernel across multiple processors. The sample code performs the basic arithmetic operations. multiplication and division. The provided sample code is meant to illustrate the parallelization concepts. The overview is shown in Figure 4. the task type and the hardware need to be considered wisely. and use the appropriate API function. between float values. which are addition.4.
the input data consists of 2 sets of 4x4 matrices A and B.B01-02632560-294 The OpenCL Programming Book Figure 4. C[base+3] = A[base+3] / B[base+3]. 79 . int base = 4*get_global_id(0). __global float* C) 002: { 003: 004: 005: 006: 007: 008: 009: } C[base+0] = A[base+0] + B[base+0]. The output data is a 4x4 matrix C.8.kernel dataParallel.4: Basic arithmetic operations between floats As the figure shows. C[base+1] = A[base+1] .B[base+1].9). We will first show the data-parallel implementation (List 4. C[base+2] = A[base+2] * B[base+2]. List 4. List 4.8: Data parallel model .cl 001: __kernel void dataParallel(__global float* A. __global float* B. This program treats each row of data as one group in order to perform the computation.
cl_device_id device_id = NULL.9: Data parallel model .h> 002: #include <stdlib. cl_platform_id platform_id = NULL. float *A: 034: 035: A = (float *)malloc(4*4*sizeof(float)). cl_context context = NULL. cl_int ret. int i. cl_mem Amobj = NULL.h> 006: #else 007: #include <CL/cl.B01-02632560-294 The OpenCL Programming Book List 4. C = (float *)malloc(4*4*sizeof(float)).c 001: #include <stdio.h> 003: 004: #ifdef __APPLE__ 005: #include <OpenCL/opencl. cl_uint ret_num_devices.host dataParallel. B = (float *)malloc(4*4*sizeof(float)). cl_mem Cmobj = NULL. cl_mem Bmobj = NULL. cl_command_queue command_queue = NULL. cl_uint ret_num_platforms. float *B. cl_program program = NULL. j. cl_kernel kernel = NULL. float *C. 80 .
1. j++) { A[i*4+j] = i*4+j+1: FILE *fp. * Create command queue */ command_queue = clCreateCommandQueue(context. 1. &platform_id. 81 . i++) { for (j=0. i < 4.¥n"). &ret_num_devices). 1. const char fileName[] = ". NULL. &ret). char *source_str. NULL. CL_MEM_READ_WRITE. /* Load kernel source file */ fp = fopen(fileName. &ret). } source_str = (char *)malloc(MAX_SOURCE_SIZE). fp). source_size = fread(source_str. exit(1)./dataParallel. MAX_SOURCE_SIZE. ret = clGetDeviceIDs(platform_id. j < 4. /* Initialize input data */ for (i=0. B[i*4+j] = j*4+i+1. 4*4*sizeof(float). /* Create OpenCL Context */ context = clCreateContext(NULL. 0. size_t source_size. "Failed to load kernel. &ret_num_platforms). &device_id. * Create Buffer Object */ Amobj = clCreateBuffer(context. fclose(fp). &device_id. "r"). } } /* Get Platform/Device Information ret = clGetPlatformIDs(1. device_id.cl". if (!fp) { fprintf(stderr. CL_DEVICE_TYPE_DEFAULT. NULL.
NULL. sizeof(cl_mem). CL_MEM_READ_WRITE. NULL). &device_id. &ret). (void *)&Bmobj). 1. (const char **)&source_str. ret = clSetKernelArg(kernel. 0. 4*4*sizeof(float). NULL). Bmobj = clCreateBuffer(context. 0. size_t global_item_size = 4. size_t local_item_size = 1. 0. "dataParallel". ret = clEnqueueWriteBuffer(command_queue. B. 0. /* Execute OpenCL kernel as data parallel */ ret = clEnqueueNDRangeKernel(command_queue. NULL). &local_item_size. 82 . Amobj. &ret). (void *)&Amobj). NULL. /* Create kernel program from source file*/ program = clCreateProgramWithSource(context. CL_TRUE. 071: &ret). CL_TRUE. CL_MEM_READ_WRITE. &global_item_size. 4*4*sizeof(float). Cmobj. size_t *)&source_size. sizeof(cl_mem). NULL. C. NULL). /* Set OpenCL kernel arguments */ ret = clSetKernelArg(kernel. 1. 1. NULL. 4*4*sizeof(float). NULL. CL_TRUE. Bmobj. 4*4*sizeof(float). (const ret = clBuildProgram(program. 0. NULL). /* Copy input data to the memory buffer */ ret = clEnqueueWriteBuffer(command_queue. /* Create data parallel OpenCL kernel */ kernel = clCreateKernel(program. A. NULL. NULL. (void *)&Cmobj).: /* Transfer result to host */ ret = clEnqueueReadBuffer(command_queue. 0. 0. sizeof(cl_mem). 072: &ret). ret = clSetKernelArg(kernel. 1. NULL. NULL. kernel. 0. Cmobj = clCreateBuffer(context.B01-02632560-294 The OpenCL Programming Book &ret). 2. 4*4*sizeof(float).
} printf("¥n").B01-02632560-294 The OpenCL Programming Book 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: } /* Display Results */ for (i=0. free(C). j < 4. the tasks are grouped according to the type of arithmetic operation being performed.10: Task parallel model . ret = clReleaseProgram(program). ret = clReleaseContext(context). 83 .10. i++) { for (j=0. ret = clReleaseMemObject(Amobj). __global float* B. i < 4. Next.kernel taskParallel. } /* Finalization */ ret = clFlush(command_queue). List 4.2f ". free(A). we will show the task parallel version of the same thing (List 4. ret = clReleaseMemObject(Cmobj). List 4. free(source_str). In this sample. __global float* C) 002: { 003: int base = 0. free(B). j++) { printf("%7. ret = clReleaseMemObject(Bmobj). C[i*4+j]). ret = clReleaseKernel(kernel). ret = clReleaseCommandQueue(command_queue).11). ret = clFinish(command_queue). return 0.cl 001: __kernel void taskParallelAdd(__global float* A.
B[base+8].B[base+4]. C[base+4] = A[base+4] * B[base+4]. __global float* C) 012: { 013: 014: 015: 016: 017: 018: 019: } 020: 021: __kernel void taskParallelMul(__global float* A. C[base+12] = A[base+12] . __global float* B. C[base+4] = A[base+4] . C[base+0] = A[base+0] . C[base+12] = A[base+12] * B[base+12]. C[base+8] = A[base+8] * B[base+8]. __global float* C) 032: { 033: 034: 035: 036: 037: 038: 039: } C[base+0] = A[base+0] / B[base+0]. __global float* C) 022: { 023: 024: 025: 026: 027: 028: 029: } 030: 031: __kernel void taskParallelDiv(__global float* A.B[base+12]. C[base+8] = A[base+8] . C[base+0] = A[base+0] * B[base+0]. C[base+8] = A[base+8] + B[base+8].B[base+0].B01-02632560-294 The OpenCL Programming Book 004: 005: 006: 007: 008: 009: } 010: 011: __kernel void taskParallelSub(__global float* A. C[base+0] = A[base+0] + B[base+0]. C[base+12] = A[base+12] + B[base+12]. __global float* B. __global float* B. 84 . C[base+12] = A[base+12] / B[base+12]. C[base+4] = A[base+4] / B[base+4]. int base = 2. C[base+4] = A[base+4] + B[base+4]. C[base+8] = A[base+8] / B[base+8]. int base = 3. int base = 1.
cl_uint ret_num_platforms. cl_context context = NULL. 85 .11: Task parallel model . cl_mem Cmobj = NULL: A = (float*)malloc(4*4*sizeof(float)). cl_mem Amobj = NULL.h> 006: #else 007: #include <CL/cl.h> 002: #include <stdlib. NULL}. cl_program program = NULL.B01-02632560-294 The OpenCL Programming Book List 4.c 001: #include <stdio.host taskParallel. int i. NULL. float* B. cl_platform_id platform_id = NULL. NULL. cl_device_id device_id = NULL. cl_command_queue command_queue = NULL. float* A. cl_kernel kernel[4] = {NULL. j. cl_int ret. B = (float*)malloc(4*4*sizeof(float)).h> 003: 004: #ifdef __APPLE__ 005: #include <OpenCL/opencl. cl_mem Bmobj = NULL. cl_uint ret_num_devices. float* C.
&ret). 1. 1.¥n"). CL_DEVICE_TYPE_DEFAULT. j++) { A[i*4+j] = i*4+j+1. size_t source_size. FILE *fp.cl". /* Initialize input data */ for (i=0. NULL./taskParallel. &device_id. /* Load kernel source file */ fp = fopen(fileName. &device_id. &ret_num_platforms). } source_str = (char *)malloc(MAX_SOURCE_SIZE).B01-02632560-294 The OpenCL Programming Book: C = (float*)malloc(4*4*sizeof(float)). 1. if (!fp) { fprintf(stderr. device_id. } } /* Get platform/device information */ ret = clGetPlatformIDs(1. fp). exit(1). &ret_num_devices). i < 4. 86 . MAX_SOURCE_SIZE. fclose(fp). char *source_str. j < 4. B[i*4+j] = j*4+i+1. "Failed to load kernel. i++) { for (j=0. "rb"). source_size = fread(source_str. &platform_id. /* Create command queue */ command_queue = clCreateCommandQueue(context. NULL. ret = clGetDeviceIDs(platform_id. const char fileName[] = ". /* Create OpenCL Context */ context = clCreateContext(NULL.
4*4*sizeof(float). 073: &ret). ret = clSetKernelArg(kernel[i]. "taskParallelMul". &ret). &device_id. NULL). Cmobj = clCreateBuffer(context. NULL). i++) { } /* Set OpenCL kernel arguments */ for (i=0. 074: 075: 076: 077: 078: 079: 080: 081: 082: 083: 084: 085: 086: 087: 088: 089: 090: 091: 092: 093: 094: 095: 096: 097: /* Execute OpenCL kernel as task parallel */ for (i=0. /* Copy input data to memory buffer */ ret = clEnqueueWriteBuffer(command_queue.B01-02632560-294 The OpenCL Programming Book CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE. 0. 4*4*sizeof(float). NULL. i < 4. &ret). (const char **)&source_str. NULL. (void *)&Bmobj). i++) { ret = clSetKernelArg(kernel[i]. (void *)&Cmobj). 0. &ret). &ret). ret = clEnqueueWriteBuffer(command_queue. Bmobj. NULL. 1. CL_TRUE. i < 4. 1. 4*4*sizeof(float). Amobj. 0. B. "taskParallelDiv". sizeof(cl_mem). (void *)&Amobj). Bmobj = clCreateBuffer(context. CL_MEM_READ_WRITE. kernel[2] = clCreateKernel(program. size_t *)&source_size. sizeof(cl_mem). CL_MEM_READ_WRITE. 0. NULL. /* Create task parallel OpenCL kernel */ kernel[0] = clCreateKernel(program. CL_TRUE. /* Create kernel from source */ program = clCreateProgramWithSource(context. 0. 4*4*sizeof(float). NULL. 2. 072: &ret). 1. (const ret = clBuildProgram(program. "taskParallelSub". CL_MEM_READ_WRITE. 87 . 4*4*sizeof(float). kernel[1] = clCreateKernel(program. "taskParallelAdd". &ret). NULL. sizeof(cl_mem). NULL). A. &ret). 069: 070: 071: &ret). ret = clSetKernelArg(kernel[i]. kernel[3] = clCreateKernel(program. NULL. /* Create buffer object */ Amobj = clCreateBuffer(context.
B01-02632560-294 The OpenCL Programming Book 098: 099: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: return 0. ret = clReleaseKernel(kernel[3]). } } ret = clEnqueueTask(command_queue. free(C). ret = clReleaseProgram(program). ret = clReleaseKernel(kernel[0]). Cmobj. ret = clReleaseMemObject(Amobj). } printf("¥n"). 0. C[i*4+j]). CL_TRUE. ret = clFinish(command_queue). 0. ret = clReleaseKernel(kernel[2]). kernel[i].2f ". 4*4*sizeof(float). ret = clReleaseContext(context). ret = clReleaseKernel(kernel[1]). NULL). 0. free(B). C. /* Display result */ for (i=0. ret = clReleaseMemObject(Bmobj). j < 4. free(A). NULL). i < 4. /* Finalization */ ret = clFlush(command_queue). free(source_str). j++) { printf("%7. ret = clReleaseCommandQueue(command_queue). ret = clReleaseMemObject(Cmobj). 88 . i++) { for (j=0. NULL. NULL. /* Copy result to host */ ret = clEnqueueReadBuffer(command_queue.
Process the subset of data corresponding to the work-item ID A block diagram of the process is shown in Figure 4. and the way to execute these kernels. data parallel processing is done using the following steps. __global float * C) When the data parallel task is queued. so the parallelization model must be considered wisely in the planning stage of the application. and performance can vary by choosing one over the other. 001: __kernel void dataParallel(__global float * A.5. However. the source codes are very similar.B01-02632560-294 The OpenCL Programming Book 133: } As you can see. In the data parallel model. The get_global_id(0) gets the global work-item ID. 003: int base = 4*get_global_id(0). Get work-item ID 2. Figure 4. Each of these work-items executes the same kernel in parallel. The only differences are in the kernels themselves. Despite this fact. while in the task parallel model. __global float * B. which is used to decide the data to process. some problems are easier.5: Block diagram of the data-parallel model in relation to work-items 89 . the 4 arithmetic operations are grouped as one set of commands in a kernel. it may seem that since the task parallel model requires more code. that it also must perform more operations. 1. work-items are created. We will now walkthrough the source code for the data parallel model. regardless of which model is used for this problem. so that each work-items can process different sets of data in parallel. 4 different kernels are implemented for each type of arithmetic operation. the number of operations being performed by the device is actually the same. In general. At a glance.
In this case. kernel. but we have not touched upon how to decide the number of work-items to create. We have discussed that numerous work items get created. size_t global_item_size = 4. In this way. the global_item_size is set to 4. the variable "base" also have a different value for each work-item. NULL. The overall steps are summarized as follows. large amount of data can be processed concurrently. which keeps the work-items from processing the same data. the global work-item is multiplied by 4 and stored in the variable "base". This value is used to decide which element of the array A and B gets processed. C[base+1] = A[base+1] . 005: 006: 007: 008: C[base+0] = A[base+0] + B[base+0]. &global_item_size. and the local_item_size is set to 1. size_t local_item_size = 1.B[base+1]. C[base+3] = A[base+3] / B[base+3]. 90 . This is done in the following code segment from the host code. The 5th and 6th arguments determine the work-item size.B01-02632560-294 The OpenCL Programming Book In this example. The clEnqueueNDRangeKernel() is an OpenCL API command used to queue data parallel tasks. Since each work-item have different IDs. 0. NULL. NULL). 1. C[base+2] = A[base+2] * B[base+2]. &local_item_size. 090: 091: 092: 093: 094: 095: /* Execute OpenCL kernel as data parallel */ ret = clEnqueueNDRangeKernel(command_queue.
0. the queued task does not wait until the previous task is finished if there are idle compute units available that can be executing that task. Note that different kernels are implemented for each of the 4 arithmetic operations.6: Command queues and parallel execution 91 . In this model. CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE. i++) { ret = clEnqueueTask(command_queue. The above code segment queues the 4 kernels. 096: 097: 098: 099: } /* Execute OpenCL kernel as task parallel */ for (i=0. the out-of-order mode must be enabled when the command queue is created.6. The block diagram of the nature of command queues and parallel execution are shown in Figure 4. different kernels are allowed to be executed in parallel. i < 4. In OpenCL. Process data corresponding to the global work item ID on the kernel We will now walkthrough the source code for the task parallel model. kernel[i]. NULL). Figure 4. in order to execute a task parallel process. &ret).B01-02632560-294 The OpenCL Programming Book 1. 067: /* Create command queue */ 068: command_queue = clCreateCommandQueue(context. Using this mode. device_id. NULL. Create work-items on the host 2.
and the maximum is dependent on the platform. The work-items within a work-group can synchronize. since PCI Express supports simultaneous bi-directional memory transfers. such as clEnqueueNDRangeKernel(). provided that the commands are being performed by different processors. Work Group The last section discussed the concept of work-items. queuing the clEnqueueReadBuffer() and clEnqueueWriteBuffer() can execute read and write commands simultaneously. In order to implement a data parallel kernel. but a similar parallel processing could take place for other combinations of enqueue-functions. For example.B01-02632560-294 The OpenCL Programming Book The clEnqueueTask() is used as an example in the above figure. the number of work-groups must be specified in addition to the number of work-items. This section will introduce the concept of work-groups. and clEnqueueWriteBuffer(). This is why 2 different parameters had to be sent to the clEnqueueNDRangeKernel() function. 090: size_t global_item_size = 4. we can expect the 4 tasks to be executed in parallel. A work-group must consist of at least 1 work-item. since they are being queued in a command queue that has out-of-execution enabled. clEnqueueReadBuffer(). In the above diagram. Work-items are grouped together into work-groups. 92 . as well as share local memory with each other.
and that there are 4 work-groups to be processed. Figure 4.7. the work-items and work-groups can be specified in 2 or 3 dimensions. Figure 4. If the number of work-items cannot be divided evenly among the work-groups. Figure 4.1. local work-item ID. returning the error value CL_INVALID_WORK_GROUP_SIZE.8: Work-group and work-item defined in 2-D 93 . but it is also possible to retrieve the local work-item ID corresponding to the work-group ID.8 shows an example where the work-group and the work-item are defined in 2-D.7: Work-group ID and Work-item ID Table 4. and the work-group ID are shown below in Figure 4.B01-02632560-294 The OpenCL Programming Book 091: size_t local_item_size = 1. clEnqueueNDRangeKernel() fails.9 only used the global work-item ID to process the kernel. The number of work-items per work-group is consistent throughout every work-group. The function used to retrieve these ID's from within the kernel are shown in Table 4. The above code means that each work-group is made up of 1 work-item.1: Functions used to retrieve the ID's Function get_group_id get_global_id get_local_id Retrieved value Work-group ID Global work-item ID Local work-item ID Since 2-D images or 3-D spaces are commonly processed. The relationship between the global work-item ID. The code List 4.
it is an array of type size_t. 94 . get_global_id(). and the maximum number of work-items per work-group can be obtained by getting the value of CL_DEVICE_IMAGE_SUPPORT. and for CL_DEVICE_IMAGE_SUPPORT. The data-type of CL_DEVICE_MAX_WORK_ITEM is cl_uint.2. the ID's that are used to index them also have 3 dimensions.8 are shown below in Table 4. The get_group_id(). The maximum index space dimension can be obtained using the clGetDeviceInfo() function to get the value of CL_DEVICE_WORK_ITEM_DIMENSIONS. each corresponding to the dimension.2: The ID's of the work-item in Figure 4. The ID's for the work-items in Figure 4. Table 4.B01-02632560-294 The OpenCL Programming Book Since the work-group and the work-items can have up to 3 dimensions. get_local_id() can each take an argument between 0 and 2.8 Call get_group_id(0) get_group_id(1) get_global_id(0) get_global_id(1) get_local_id(0) get_local_id(1) Retrieved ID 1 0 10 5 2 5 Note that the index space dimension and the number of work-items per work-group can vary depending on the device.
12 shows an example of how the event objects can be used. NULL. kernel_C. clEnqueueTask(command_queue. List 4. as of this writing (12/2009). &events[0]). In this example. cl_uint num_events_in_wait_list. kernel_B.B01-02632560-294 The OpenCL Programming Book Also. they need to be executed sequentially. the OpenCL implementation for the CPU on Mac OS X only allows 1 work-item per work-group. 0. For example. clEnqueueTask(command_queue. cl_int clEnqueueTask (cl_command_queue command_queue. NULL. In order to make sure task A executes before task B. const cl_event *event_wait_list.12: Event object usage example clEnqueue events[4]. This object is returned on all commands that start with "clEnqueue". kernel_C. 0. the event object returned when task A is queued can be one of the inputs to task B. but these must be completed before kernel_E is executed. the execution order can be set using an event object. List 4. which keeps task B from executing until task A is completed. NULL. Task Parallelism and Event Object The tasks placed in the command-queue are executed in parallel. 0. The 5th parameter is the event object returned by this task when it is placed in the queue. and the 3rd argument is the number of events on the list. NULL. kernel_A. In OpenCL. the function prototype for clPEnqueueTask() is shown below. clEnqueueTask(command_queue. An event object contains information about the execution status of queued commands. cl_event *event) The 4th argument is a list of events to be processed before this task can be run. cl_kernel kernel. kernel_B. &events[1]). kernel_D. &events[2]). &events[3]). kernel_D can all be executed in any order. kernel_A. clEnqueueTask(command_queue. but in cases where different tasks have data dependencies. 0. 95 .
As an example. ---COLUMN: Relationship between execution order and parallel execution--In OpenCL. (A) → (C) → (B) → (D) If tasks B and C are not dependent on each other. events. If they are not. task B may finish before task C. Also. For example. NULL). kernel_E. the two sets of tasks will result in the same output. This processing is only allowed in the case where the tasks B and C do not depend on each other. This problem of whether a certain set of tasks can be performed in different order is a process-dependent problem.B01-02632560-294 The OpenCL Programming Book clEnqueueTask(command_queue. First. 4. 96 . then the 2 tasks cannot be processed in parallel. we will switch the order in which task B and C are performed. it may make more sense to implement all the tasks in a single thread. the concept of "order" and "parallel" need to be fully understood. there is usually a section on "order". the tasks placed in the command queue are executed regardless of the order in which it is placed in the queue. On the other hand. all the tasks must be performed sequentially. the two sets of tasks will not yield the correct result. These need to be considered when implementing an algorithm. When working on parallel processing algorithms. let's assume tasks B and C are processed in parallel. we will discuss the concept of "order". if the tasks are executed on a single-core processor. Parallel processing is a type of optimization that deals with changing the order of tasks. (A) → (B) → (C) → (D) Now. Thus. In this case. In the specification sheet for parallel processors. let's assume the following 4 tasks are performed sequentially in the order shown below. but task D waits for the results of both tasks B and C. if task C must be performed after task B.
one may wonder if it meets OpenMP's specification. two problems must be solved. • Tasks must be executed in a specific order = Cannot be parallelized • Tasks can be executed out of order = Can be parallelized Specifications are written to be a general reference of the capabilities. For example.B01-02632560-294 The OpenCL Programming Book In essence. OpenMP's "parallel" construct specifies the code segment to be executed in parallel. but often times. and the other is whether to process the tasks in parallel. 97 . it contains information such as how certain tasks are guaranteed to be processed in order. it clears up the definition. Decision to execute certain tasks in parallel is thus not discussed inside the specification. treating "order" as the basis when implementing parallel algorithms can clear up existing bottlenecks in the program. Instead. but placing this construct in a single-core processor will not process the code segment in parallel. but that they do not have to be. and do not deal with the actual implementation. since it means that the ordering can be changed or the tasks can be run parallel. One is whether some tasks can be executed out of order. Explanations on "ordering" is often times difficult to follow (Example: PowerPC's Storage Access Ordering). In this case. If you think about the "parallel" construct as something that tells the compiler and the processors that the loops can be executed out-of-order.
• Predefined identifiers are not supported. allowing for a more a flexible and optimized OpenCL program. This language is used to program the kernel. OpenCL C OpenCL C language is basically standard C (C99) with some extensions and restrictions. auto and register storage-class specifiers are not supported. • Pointer to a pointer cannot be passed as an argument to a kernel function. i++) { sum += a[i]. Restrictions Below lists the restricted portion from the C language in OpenCL C. and half are not supported. __constant. • The pointer passed as an argument to a kernel function must be of type __global. uchar. short. the language can be treated the same as C. 98 . • C99 standard headers cannot be included • The extern. i < n. ushort. Aside from these extensions and restrictions. • Bit-fields are not supported. • The function using the __kernel qualifier can only have return type void in the source code. for (int i=0. • Recursion is not supported. char2.1 shows a simple function written in OpenCL C. int n) { /* Sum every component in array "a" */ 002: 003: 004: 005: 006: 007: } } return sum. This chapter will go further in depth. • Variadic macros and functions are not supported. or __local. • Writes to a pointer of type char. int sum = 0. List 5. uchar2.1: OpenCL C Sample Code 001: int sum(int *a. • Variable length arrays and structures with flexible (or unsized) arrays are not supported.B01-02632560-294 The OpenCL Programming Book Advanced OpenCL Chapter 4 discussed the basic concepts required to write a simple OpenCL program. List 5. static.
// 128 integers allocated on global memory // pointer placed on the private memory. these address space qualifiers are used to specify which memory on the device to use. Some implementation allows access to a different memory space via pointer casting. local. List 5.1: Address Space Qualifiers and their corresponding memory Qualifier __global (or global) __local (or local) __private (or private) __constant (or constant) Corresponding memory Global memory Local memory Private memory Constant memory The "__" prefix is not required before the qualifiers.B01-02632560-294 The OpenCL Programming Book • Support for double precision floating-point is currently an optional extension.2. which points to a // 8 pointers stored on the local memory that points to single-precision float located on the local memory __global char * __local lgc[8].2: Variables declared with address space qualifiers 001: 002: 003: __global int global_data[128]. Address Space Qualifiers OpenCL supports 4 memory types: global. constant. If the qualifier is not specified. the pointers can be used to write to an address space as in standard C. but we will continue to use the prefix in this text for consistency.1. A few example variable declarations are given in List 5. Table 5. Similarly. It may or may not be implemented. The memory type corresponding to each address space qualifiers are shown in Table 5. with the exception for "__constant" pointers. the variable gets allocated to "__private". __local float *lf. In OpenCL C. and private. but this is not the case for all implementations. A type-cast using address space qualifiers is undefined. a char located on the global memory The pointers can be used to read address in the same way as in standard C. which is the default qualifier. Built-in Function 99 .
3: Kernel that uses sin() 001: 002: 003: 004 005: } } __kernel void runtest(__global float *out. i++) { out[i] = sin(in[i]/16. /* The float version is called */ double df = sin(in_double[i]). An example of calls to overloaded functions is shown in List 5. log(). __global float *in) { for (int i=0. reducing the need for functions such as sinf() in standard C.0f). List 5. Refer to chapter 7 for a full listing of built-in functions. • Math Functions Extended version of math. Many built-in functions are overloaded. i<16. dot().4: Calls to overloaded functions 001: __kernel void runtest(__global float *out. most math functions are overloaded.3 below shows an example of a kernel that uses the sin() function. • Geometric Functions Includes functions such as length(). In OpenCL. For example. i < 16. /* The double version is called */ 100 . Allows usage of functions such as sin(). __global double *in_double) { 002: 003: 004: for (int i=0. These can be used without having to include a header file or linking to a library. exp(). A few examples are shown below.4 below. since different functions exist for each of the passed in data-types. List 5. __global float *in_single. List 5. Get_local_size() are some examples. i++) { float sf = sin(in_single[i]).B01-02632560-294 The OpenCL Programming Book OpenCL contains several built-in functions for scalar and vector operations. Note that header files do not have to be included. • Work-Item Functions Functions to query information on groups and work-items. the sin() function is overloaded such that the precision of the returned value depends on whether a float or a double value is passed in as an argument.h in C. Get_work_dim(). A function is said to be overloaded if the same function name can be used to call different function definitions based on the arguments passed into that function.
Vector literals are used to place values in these variables.1 shows some example of vector data-types. Figure 5. Usage of these SIMD units can accelerate some processes by many folds. // Variable made up of 8 float values OpenCL defines scalar types char. Declaring a variable using a vector type creates a variable that can contain the specified number of scalar types. ushort. and 16. uchar. List 5. int. adding a number after the scalar type creates a vector type consisting of those scalar types. uint. float8 f8.5: Vector-type variable declaration int i4.1: Vector data-type examples Each component in the vector is referred to as a scalar-type. Figure 5. 8. which is basically a struct consisting of many components of the same data-type. // Variable made up of 4 int values // Variable made up of 2 char values char2 c2. which allows numerous data to be processed using one instruction. 4. long. such as in "int4". and vector-types with size 2. List 5. short. The use of vector data-types in OpenCL can aid in efficient usage of these SIMD units. ulong. 101 .5 shows examples of declaring vector-type variables. A group of these scalar-type values defines a vector data-type. double. In OpenCL C. Recent CPUs contain compute units called SIMD. float.B01-02632560-294 The OpenCL Programming Book 005: 006: } } Vector Data OpenCL defines vector data-types.
The above code performs the operation shown below. • ". float4 f4 = (float4)(sin(1. 3. List 5. The number of values set in the vector literals must equal the size of the vector. • The vector can be accessed via a number index using ". and ". • ".0f.3. float4 g4 = (float4)(1. 4. 1.0f). The built-in math functions are overloaded such that an component-by-component processing is allowed for vector-types.7 shows a few examples of component accesses.4).2.7f. sin(2.4f.0f)).xyzw" accesses indices 0 through 3. This number is in hex. 3.2f. sin(4.0f). List 5. and ". 1. 1.0f. Functions such as sin() and log() performs these operations on each component of the vector-type.6.0f. 1. List 5. 3. (float8) (1. 1.s" followed by a number.8f). 2.0f).2). 1) */ 102 . 1. 1.wzyx.hi" extracts the upper half of the vector.0f).even" extracts the even indices.xyzw. This can be done by adding .odd" extracts the odd indices. (int2)(3.8)). float4 g4 = (float4)(1.7. allowing access to up to 16 elements by using a~f or A~F for indices above 9.1f.B01-02632560-294 The OpenCL Programming Book A vector literal is written as a parenthesized vector type followed by a parenthesized set of expressions.6f. (int4)(5. It cannot access higher indices. accessing by number.7: Vector component access int4 x = (int4)(1. float4 f4 = sin(g4). The vector component can be accessed by adding an extension to the variable.6 shows some example usage of vector literals.lo" extracts the lower half of the vector.0f. List 5.5f. 2. 3. 2. (int8) ((int2)(1. /* a = (4.3f.0f.6: Vector Literal (int4) (1. 4). or by odd/even/hi/lo. 2. sin(3.0f.4). 4.0f). int4 a = x. ".
Figure 5. 1) */ int2 d = x. i < 4. 3. i++) { out4[3-i] = in4[i]. 4. List 5.8 shows a kernel code that reverses the order of an array consisting of 16 components. 4) */ We will now show an example of changing the order of data using the introduced concepts.2: Addition of 2 vector-types 103 .s3210.odd. Some operators are overloaded to support arithmetic operation on vector types. 4) */ int2 e = x.hi. An example is shown in Figure 5. 2.2. 2. • 005: Vector component access by index number.s01233210. List 5. 3.xx.8: Reverse the order of a 16-element array 001: __kernel void runtest(__global float *out.B01-02632560-294 The OpenCL Programming Book int2 b = x. 4. For these operations. /* c = (1. /* b = (1. • 002~003: Type cast allow access as a vector type • 004: Each loop processes 4 elements. __global float *in) { 002: 003: 004: 005: 006: 007: } } __global float4 *in4 = (__global float4*)in. /* d = (2. The loop is run 4 times to process 16 elements. /* e = (3. for (int i=0. arithmetic operation is performed for each component in the vector. __global float4 *out4 = (__global float4*)out. 1) */ int8 c = x.
List 5. 1. 0. 1. int4 tf = (float4)(1. Table 5.0f. 1. 104 . Logic operations such as "&&" and "||" are undefined. which would not use the SIMD unit effectively. ulong.0f. since it is more convenient when using SIMD units. a 0 (all bits are 0) is returned like usual. uint. 3. if (a<b) out[i] = a.0f). the branch must be performed for each vector component serially. For example.0f. with each vector component having a TRUE or FALSE value. else out[i] = b. a -1 (all bits are 1) is returned. 2. b = in1[i].2 below. a comparison of two-float4 types returns an int4 type. double Type after comparison char short int long Also. a vector type (not necessarily the same as the vector-types being compared) is returned. in the code shown in List 5.0f. ushort int. For example.2: Resulting vector-type after a comparison Operand type char. // tf = (int4)(0. Since SIMD operation performs the same operation on different data in parallel. branch instructions should be avoided when possible. The operand types and the returned vector-type after a comparison are shown in Table 5.0f) == (float4)(0. if the comparison is FALSE.0f. but if it is TRUE.9. 0) A 0/-1 is returned instead of 0/1.0f. -1. The result of comparison and selection operations are shown in the sections to follow. float long. the vector operation would be the same for each component.9: Branch process // "out" gets the smaller of "in0" and "in1" for each component in the vector int a = in0[i]. When 2 vector-types are compared. 1. with the exception to comparison and ternary selection operations.B01-02632560-294 The OpenCL Programming Book In general. uchar short. an integer value of either 0 or 1 is returned. Comparison Operations When 2 scalar-types are compared.
// a when TRUE and b when FALSE --. // a when TRUE and b when FALSE In this case. if the statement to the left of "?" evaluates to be FALSE.10 that does not use a branch. and if it evaluates to be TRUE. In a selection operation. then the value to the right of ":" is selected. then the value between the "?" and ":" is selected. If FALSE. b = in1[i]. out[i] = (a & cmp) | (b & ~cmp). out[i] = a<b ? a : b.9 rewritten without the branch // "out" gets the smaller of "in0" and "in1" for each component in the vector int a = in0[i]. and to do this. the SIMD unit is used effectively. which can rewrite the line out[i] = (a & cmp) | (b & ~cmp) // a when TRUE and b when FALSE with the line out[i] = bitselect(cmp. branch instruction should be taken out to use SIMD units. List 5. On a side note. a).B01-02632560-294 The OpenCL Programming Book Since a "-1" is returned when the condition is TRUE.11. it is much more convenient to have the TRUE value to be -1 instead of 1. OpenCL C language has a built-in function bitselect(). Ternary Selection Operations The difference in comparison operation brings about a difference in ternary selection operations as well.9 can be replaced by the code in 5. List 5. the code in List 5.10: List 5.10 can be rewritten as the code shown in List 5. cmp=0xffffffff.COLUMN: Should you use a vector-type? --105 . the code from List 5. // If TRUE. To summarize. int cmp = a < b.11: Ternary Selection Operator Usage Example // "out" gets the smaller of "in0" and "in1" for each component in the vector int a = in0[i]. since each processing elements are running the same set of instructions. b = in1[i]. cmp=0x00000000. b. Using this operation.
Also. (for example. Figure 5.3: Bit layout of "half" The "half" type is not as well known as 32-bit floats or 64-bit doubles. One bit is used for sign. NVIDIA GPU). but it does not specify how its operations are implemented. and auto-vectorization is still under development. Figure 5.3 below. and when vector operations are performed on these processors. In these cases. A list of types defined in OpenCL C as well as their bit widths are shown in Table 5. Thus. the operations will be performed sequentially for each scalars.B01-02632560-294 The OpenCL Programming Book The OpenCL C language defines vector type. and the remaining 10 bits are used as the mantissa (also known as significant or coefficient). the compiler should take care of deciding on the vector length to use the SIMD unit for optimal performance. In fact. Half OpenCL C language defines a 16-bit floating point type referred to as "half". 106 . OpenCL variable types Some defined types in OpenCL C may differ. resulting in slower execution. large vector-types such as double16 may fill up the hardware register. and some types may not be defined in the standard C language.3 shows the bit layout of a half-type. Since not all processors contain SIMD units. 5 bits are used for exponent. the optimization to effectively use SIMD units is placed on the hands of the programmers. but this type is defined as a standard in IEEE 754. the operation will not benefit from using a vector type. compilers are still not perfect. However.
h not required stddef.3: OpenCL variable types Data types bool char unsigned char. as well what how the numbers are rounded in each of the situations. or when a double is casted to a float. Table 5.4 shows a listing of situations when rounding occurs. ulong float half size_t intptr_t uintptr_t void Bit width Undefined 8 8 16 16 32 32 64 64 32 16 * * * stddef.h not required Remarks Rounding of floats When a float is casted to integer.B01-02632560-294 The OpenCL Programming Book Table 5.h not required stddef. Table 5. uchar short unsigned short. rounding must take place from the lack of available bits. Others may be set as an option. uint long unsigned long. The default may not be round to nearest even for Embedded Profiles Round to nearest even only Round towards zero only Same as for floating point arithmetic Builtin functions Cast from float to int Cast from int to float Cast from float to fixed point Same as for floating point arithmetic Type casting can be performed in the same way as in standard C. Explicit conversion can also be 107 .4: OpenCL C Rounding Operation Floating point arithmetic Rounding Method Round to nearest even by default. ushort int unsigned int.
14 shows the case where it is used to look at the bit value of a float variable. convert_<type>[_<rounding>][_sat] <type> is the variable type to be converted to. Table 5. The explicit conversion can be done as follows. <rounding> gets one of the rounding mode shown in Table 5. // Round to nearest even // Round toward zero // Round toward -∞ // Round toward ∞ Bit Reinterpreting In OpenCL the union() function can be used to access the bits of a variable. which allows for an option of how the number gets rounded.5. out->y = convert_int_rtz(in->y). List 5. out->z = convert_int_rtn(in->z). List 5. out->w = convert_int_rtp(in->w).13: Rounding example 001: __kernel void round_xyzw(__global int *out.B01-02632560-294 The OpenCL Programming Book performed. "_sat" can be used at the end to saturate the value when the value is above the max value or below the minimum value. <rounding> sets the rounding mode. List 5. than the rounding method will be the same as for type casting.14: Get bit values using union 108 .5: Explicit specification of the rounding mode Rounding mode rte rtz rtp rtn Rounding toward Nearest even 0 +∞ -∞ List 5.13 shows an example where floats are explicitly converted to integers using different rounding modes. If this mode is not set. __global float *in) 002: { 003: 004: 005: 006: 007: } out->x = convert_int_rte(in->x).
List 5. for example.B01-02632560-294 The OpenCL Programming Book 001: // Get bit values of a float 002: int float_int(float a) { 003: 004: 005: 006: } union { int i. where the number of bits is different. List 5. u. OpenCL memory and pointer seems complicated when compared to the standard C language. return as_int(a). where the total number of bits is the same. between float and short. float f. The action of the above code using standard C is not defined.15: Reinterpretation using as_int() 001: // Get the bit pattern of a float 002: int float_int(float a) { 003: 004:} 005: 006: // 0x3f800000(=1. is undefined and the answer may vary depending on the OpenCL implementation. } u. Reinterpretation between short4 and int2. Reinterpretation cannot be performed.0f) 007: int float1_int(void) { 008: 009: } return as_int(1. Local Memory We have mentioned the OpenCL memory hierarchy from time to time so far in this text.i.15 shows an example where the "as_int()" function is called with a 32-bit float as an argument. This section will discuss the reason for the seemingly-complex memory hierarchy. as well as one of the memory types in the hierarchy.0f). the bits of the float can be reinterpreted as an integer. called the local memory. OpenCL includes several built-in functions that make this reinterpretation easier. 109 . but when using OpenCL C. The function has the name "as_<type>".f = a. and is used to reinterpret a variable as another type without changing the bits. return u.
One is called SRAM (Static RAM) and the other is called DRAM (Dynamic RAM). __local int larr[128]. The cache is the SRAM in this case. memory space larger than the memory space cannot be allocated. and local storage on Cell/B. but cannot be used throughout due to cost and the complex circuitry. In most computers.16 shows some examples of declaring variables to be stored on the local memory.E. SRAM can be accessed quickly. In CPU. memory space can be made smaller than cache memory.B01-02632560-294 The OpenCL Programming Book There are two main types of memory. the frequently-used data uses the SRAM. since this memory was made small in order to speed up access to it. OpenCL calls these scratch-pad memory "local memory" [16]. This cache memory may not be implemented for processors such as GPU and Cell/B. This is mainly due to the fact that caches were not of utmost necessity for 3D graphics.16: Declaring variables on the local memory __local int lvar. Local memory that belongs to another work-group may not be accessed. __local int *ptr. for which the processor was designed for. and that cache hardware adds complexity to the hardware to maintain coherency. but cannot be accessed quickly as in the case for SRAM. Work-items within a work-group can use the same local memory. Some examples of scratch-pad memory include shared memory on NVIDIA's GPU. The advantage of using these scratch-pad memories is that it keeps the hardware simple since the coherency is maintained via software rather than on the cache hardware. DRAM on the other hand is cheap. Local memory is allocated per work-group. One disadvantage is that everything has to be managed by the software.E. List 5. The size of the local memory space that can be used on a work-group can be found by using the 110 . List 5.. where numerous compute units are available. // Declare lvar on the local memory // Declare array larr on the local memory // Declare a pointer that points to an address on the local memory The local memory size must be taken into account. Local memory can be used by inserting the "__local" qualifier before a variable declaration. the last accessed memory content is kept in cache located in the memory space near the CPU. Naturally. while less frequently-used data is kept in the DRAM. Also. Processors that do not have cache hardware usually contain a scratch-pad memory in order to accelerate memory access. since the memory content can be altered as needed via the software.
Since this memory size varies depending on the hardware.h> 006: #endif 007: #include <stdio. there may be cases where you may want to set the memory size at runtime. } for (int i=0. but it is typically between 10 KB and a few hundred KB. and each kernel is given half of the available local memory.B01-02632560-294 The OpenCL Programming Book clGetDeviceInfo function.18 shows an example where the local memory size for a kernel is specified based on the available local memory on the device. cl_command_queue command_queue = NULL. i < local_size. OpenCL expects at least 16 KB of local memory.h> 004: #else 005: #include <CL/cl.h> 008: 009: #define MAX_SOURCE_SIZE (0x100000) 010: 011: int main() { 012: 013: 014: 015: 016: 017: cl_platform_id platform_id = NULL. cl_uint ret_num_devices.18: Set local memory size at runtime (host) 001: #include <stdlib. The available local memory is retrieved using the clGetDeviceInfo function. 111 . passing CL_DEVICE_LOCAL_MEM_SIZE as an argument. cl_device_id device_id = NULL. List 5. int local_size) { 002: 003: 004: 005: } List 5. List 5. cl_context context = NULL. This can be done by passing in an appropriate value to the kernel via clSetKernelArg().h> 002: #ifdef __APPLE__ 003: #include <OpenCL/opencl. cl_uint ret_num_platforms.17: Set local memory size at runtime (kernel) 001: __kernel void local_test(__local char *p. i++) { p[i] = i. The local memory size depends on the hardware used.17 and List 5.
/* Set kernel argument */ clSetKernelArg(kernel. 1. size_t kernel_code_size. clGetPlatformIDs(1. cl_int ret. "local_test". 0. &device_id. (const size_t *)&kernel_code_size. NULL. cl_ulong local_size. kernel = clCreateKernel(program. &local_size. cl_local_size = local_size / 2. cl_local_size. NULL. 1. NULL. &ret_num_platforms). cl_int cl_local_size. local_size_size. &device_id. /* Get available local memory size */ clGetDeviceInfo(device_id. sizeof(local_size). cl_kernel kernel = NULL. cl_event ev. 1. (int)local_size). /* Build Program */ program = clCreateProgramWithSource(context. &device_id.cl". (const char **)&kernel_src_str. MAX_SOURCE_SIZE. command_queue = clCreateCommandQueue(context. 1. &ret). 0. 1. &ret). fclose(fp). "". NULL). &ret). printf("CL_DEVICE_LOCAL_MEM_SIZE = %d¥n". kernel_src_str = (char*)malloc(MAX_SOURCE_SIZE). char *kernel_src_str. &ret). &platform_id. FILE *fp. context = clCreateContext(NULL. clBuildProgram(program. fp). NULL). clGetDeviceIDs(platform_id. CL_DEVICE_LOCAL_MEM_SIZE. &local_size_size). "r"). &ret_num_devices). CL_DEVICE_TYPE_DEFAULT.B01-02632560-294 The OpenCL Programming Book: cl_program program = NULL. kernel_code_size = fread(kernel_src_str. fp = fopen("local. device_id. 112 .
data stored on the local memory must be transferred over to the global memory in order to be accessed by the host. 001: __kernel void local_test(__local char *p. This pointer can be used like any other pointer. clReleaseKernel(kernel). the value computed in this kernel gets thrown away. 002: 003: 004: } for (int i=0. &ev). However. since the local memory cannot be read by the host program. &cl_local_size). kernel. 0. i++) { p[i] = i. return 0. } /* Wait for the kernel to finish */ clWaitForEvents(1. starting with the kernel code. We will now go through the above code. clReleaseContext(context). 113 . i < local_size. int local_size) { The kernel receives a pointer to the local memory for dynamic local memory allocation. if (ret == CL_OUT_OF_RESOURCES) { puts("too large local"). clReleaseProgram(program). clReleaseCommandQueue(command_queue). In actual programs. sizeof(cl_local_size). 1.B01-02632560-294 The OpenCL Programming Book 053: 054: 055: 056: 057: 058: 059: 060: 061: 062: 063: 064: 065: 066: 067: 068: 069: 070: 071: 072: } clSetKernelArg(kernel. return 1. &ev). free(kernel_src_str). NULL. /* Execute kernel */ ret = clEnqueueTask(command_queue.
039: 040: 041: /* Get available local memory size */ clGetDeviceInfo(device_id. If the specified local memory size is too large. 0. &ev). (int)local_size). 0. The 4th argument is set to NULL. which is the value of the argument. you may find the 114 . sizeof(local_size). NULL). 049: cl_local_size = local_size / 2. --. which specifies the argument size. This is given in the 3rd argument. The clGetDeviceInfo() retrieves the local memory size.B01-02632560-294 The OpenCL Programming Book We will now look at the host code. kernel. For the record. so the actual usable local memory size may be smaller than the value retrieved using clGetDeviceInfo. &local_size_size).COLUMN: Parallel Programming and Memory Hierarchy --For those of you new to programming in a heterogeneous environment. 051: /* Set Kernel Argument */ 052: clSetKernelArg(kernel. &local_size. 056: 057: 058: 059: 060: } ret = clEnqueueTask(command_queue. NULL. The local memory may be used by the OpenCL implementation in some cases. CL_DEVICE_LOCAL_MEM_SIZE. The above code sets the size of local memory to be used by the kernel. printf("CL_DEVICE_LOCAL_MEM_SIZE = %d¥n". return 1. if (ret == CL_OUT_OF_RESOURCES) { puts("too large local"). We are only using half of the available local memory here to be on the safe side. the kernel will not be executed. cl_local_size. which is of the type cl_ulong. The kernel is enqueued using clEnqueueTask(). returning the error code CL_OUT_OF_RESOURCES. the local memory does not need to be freed. and this size is returned to the address of "local_size".
B01-02632560-294
The OpenCL Programming Book
emphasis on memory usage to be a bit confusing and unnecessary (those familiar with GPU or Cell/B.E. probably find most of the content to be rather intuitive). However, effective parallel programming essentially boils down to efficient usage of available memory. Therefore, memory management is emphasized in this text. This column will go over the basics of parallel programming and memory hierarchy. First important fact is that memory access cannot be accelerated effectively through the use of cache on multi-core/many-processor systems, as it had been previously with single cores. A cache is a fast storage buffer on a processor that temporarily stores the previously accessed content of the main memory, so that this content can be accessed quickly by the processor. The problem with this is that with multiple processors, the coherency of the cache is not guaranteed, since the data on the memory can be changed by one processor, while another processor still keeps the old data on cache. Therefore, there needs to be a way to guarantee coherency of the cache coherency across multiple processors. This requires data transfers between the processors. So how is data transferred between processors? For 2 processors A and B, data transfer occurs between A and B (1 transfer). For 3 processors A, B, and C, data is transferred from A to B, A to C, or B to C (3 transfers). For 4 processors A, B, C, and D, this becomes A to B, A to C, A to D, B to C, B to D, C to D (6 transfers). As the number of processors increase, the number of transfers explodes. The number of processing units (such as ALU), on the other hand, is proportional to the number of processors. This should make apparent of the fact that the data transfer between processors becomes the bottleneck, and not the number of processing units. Use of a cache requires the synchronization of the newest content of the main memory, which can be viewed as a type of data transfer between processors. Since the data transfer is a bottleneck in multi-core systems, the use of cache to speed up memory access becomes a difficult task. For this reason, the concept of scratch-pad memory was introduced to replace cache, which the programmer must handle instead of depending on the cache hardware. On Cell/B.E. SPEs and NVIDIA GPUs, one thing they have in common is that neither of them have a cache. Because of this, the memory transfer cost is strictly just the data transfer cost, 115
B01-02632560-294
The OpenCL Programming Book
which reduce the data transfer cost in cache that arises from using multiple processors. Each SPE on Cell/B.E. has a local storage space and a hardware called MFC. The transfer between the local storage and the main memory (accessible from all SPE) is controlled in software. The software looks at where memory transfers are taking place in order to keep the program running coherently. NVIDIA GPUs do not allow DMA transfer to the local memory (shared memory), and thus data must be loaded from the global memory on the device. When memory access instruction is called, the processor stalls for a few hundred clock cycles, which manifest the slow memory access speed that gets hidden on normal CPUs due to the existence of cache. On NVIDIA GPU, however, a hardware thread is implemented, which allows another process to be performed during the memory access. This can be used to hide the slow memory access speed.
Image Object
In image processing, resizing and rotation of 2-D images (textures) are often performed, which requires the processing of other pixels in order to produce the resulting image. The complexity of the processing is typically inversely proportional to the clarity of the processed image. For example, real-time 3-D graphics only performs relatively simple processing such as nearest neighbor interpolation and linear interpolation. Most GPUs implement some of these commonly used methods on a hardware called the texture unit. OpenCL allows the use of these image objects as well as an API to process these image objects. The API allows the texture unit to be used to perform the implemented processes. This API is intended for the existing GPU hardware, which may not be fit to be used on other devices, but the processing may be accelerated if the hardware contains a texture unit. Image object can be used using the following procedure. 1. Create an image object from the host (clCreateImage2D, clCreateImage3D) 2. Write data to the image object from the host (clEnqueueWriteImage) 3. Process the image on the kernel 4. Read data from the image object on the host (clEnqueueReadImage) An example code is shown in List 5.19 and List 5.20 below. 116
B01-02632560-294
The OpenCL Programming Book
List 5.19: Kernel (image.cl)
001: const sampler_t s_nearest = CLK_FILTER_NEAREST | CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE; 002: const sampler_t s_linear = CLK_FILTER_LINEAR | CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE; 003: const sampler_t s_repeat = CLK_FILTER_NEAREST | CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_REPEAT; 004: 005: __kernel void 006: image_test(__read_only image2d_t im, 007: 008: { 009: 010: 011: 012: 013: 014: 015: 016: 017: 018: 019: 020: 021: 022: 023: } /* repeat */ out[6] = read_imagef(im, s_repeat, (float2)(4.5f, 0.5f)); out[7] = read_imagef(im, s_repeat, (float2)(5.0f, 0.5f)); out[8] = read_imagef(im, s_repeat, (float2)(6.5f, 0.5f)); /* linear */ out[3] = read_imagef(im, s_linear, (float2)(0.5f, 0.5f)); out[4] = read_imagef(im, s_linear, (float2)(0.8f, 0.5f)); out[5] = read_imagef(im, s_linear, (float2)(1.3f, 0.5f)); /* nearest */ out[0] = read_imagef(im, s_nearest, (float2)(0.5f, 0.5f)); out[1] = read_imagef(im, s_nearest, (float2)(0.8f, 0.5f)); out[2] = read_imagef(im, s_nearest, (float2)(1.3f, 0.5f)); __global float4 *out)
List 5.20: Host code (image.cpp)
001: #include <stdlib.h> 002: #ifdef __APPLE__ 003: #include <OpenCL/opencl.h> 004: #else 005: #include <CL/cl.h> 006: #endif
117
B01-02632560-294
The OpenCL Programming Book
007: #include <stdio.h> 008: 009: #define MAX_SOURCE_SIZE (0x100000) 010: 011: int main(): /* Check if the device support images */ clGetDeviceInfo(device_id, CL_DEVICE_IMAGE_SUPPORT, sizeof(support), &support, clGetPlatformIDs(1, &platform_id, &ret_num_platforms); clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_DEFAULT, 1, &device_id, &ret_num_devices); context = clCreateContext( NULL, 1, &device_id, NULL, NULL, &ret); result = (float*)malloc(sizeof(cl_float4)*num_out); int num_out = 9; cl_mem image, out; cl_bool support; cl_image_format fmt; cl_platform_id platform_id = NULL; cl_uint ret_num_platforms; cl_device_id device_id = NULL; cl_uint ret_num_devices; cl_context context = NULL; cl_command_queue command_queue = NULL; cl_program program = NULL; cl_kernel kernel = NULL; size_t kernel_code_size; char *kernel_src_str; float *result; cl_int ret; int i; FILE *fp; size_t r_size;
118
40. fp = fopen("image. &ret). /* Transfer target coordinate*/ size_t region[] = {4. CL_MEM_READ_ONLY. image. 119 . 1}. 0. return 1. 40. NULL).image_channel_order = CL_R. 0. 20. 10. "r"). 0. 0}. 10. kernel_src_str = (char*)malloc(MAX_SOURCE_SIZE). 10. fmt. origin. sizeof(cl_float4)*num_out. 30. &fmt. MAX_SOURCE_SIZE. 20. 40. /* Create output buffer */ out = clCreateBuffer(context. command_queue = clCreateCommandQueue(context. 40. /* Set parameter to be used to transfer image object */ size_t origin[] = {0. NULL. &ret).: /* Transfer to device */ clEnqueueWriteImage(command_queue. 20. 30. /* Size of object to be transferred */ /* Create Image Object */ image = clCreateImage2D(context. region. 4.image_channel_data_type = CL_FLOAT. CL_MEM_READ_WRITE. 30. 30. fclose(fp). device_id. CL_TRUE. float data[] = { /* Transfer Data */ 10.cl". fp). kernel_code_size = fread(kernel_src_str. }. 4. /* Create data format for image creation */ fmt. 0. 20.B01-02632560-294 The OpenCL Programming Book &r_size). 4. 1. } if (support != CL_TRUE) { puts("image not supported").
0. kernel. 1.B01-02632560-294 The OpenCL Programming Book 4*sizeof(float). 1. NULL. clReleaseProgram(program). clReleaseMemObject(image). 120 . result. NULL. out. 0. data. sizeof(cl_float4)*num_out. (const char **)&kernel_src_str. NULL). i < num_out. &ret). 0.result[i*4+0]. 077: 078: 079: 080: 081: 082: 083: 084: 085: 086: 087: 088: 089: 090: 091: 092: 093: 094: 095: 096: 097: 098: 099: 0100: 0101: 0102: 0103: 0104: 0105: 0106: 0107: 0108: 0109: 0110: } return 0.result[i*4+2]. /* Set Kernel Arguments */ clSetKernelArg(kernel. i++) { printf("%f. NULL). for (i=0. "". clSetKernelArg(kernel. (void*)&image).result[i*4+1]. (const size_t *)&kernel_code_size. CL_TRUE. 0. free(kernel_src_str). &device_id. NULL. cl_event ev. (void*)&out).%f. clReleaseMemObject(out). clBuildProgram(program. NULL. /* Build program */ program = clCreateProgramWithSource(context.%f.result[i*4+3]).%f¥n". 0. &ret). kernel = clCreateKernel(program. &ev). } /* Retrieve result */ clEnqueueReadBuffer(command_queue. 1. clReleaseContext(context). 0. "image_test". clEnqueueTask(command_queue. sizeof(cl_mem). free(result). clReleaseCommandQueue(command_queue). sizeof(cl_mem). NULL). clReleaseKernel(kernel).
000000.000000.000000.1.000000 13.0.000000. and "image_channel_data_type" sets the type of the element.1. fmt.1.0.0.0.000000 30.000000 10. 041: 042: &r_size).000000.1. CL_DEVICE_IMAGE_SUPPORT.000000. sizeof(support). 10.0.0. The above code sets the format of the image object.000000 We will start the explanation from the host side.000000. 057: 058: 059: /* Create data format for image creation */ fmt.000000 10.0.000000.000000.0. /* Check if the device support images */ clGetDeviceInfo(device_id. The format is of type cl_image_format. return 1. as not all OpenCL implementation may support image objects. &support.000000 10.000000.B01-02632560-294 The OpenCL Programming Book The result is the following (the result may vary slightly.0.0.1.000000.image_channel_data_type = CL_FLOAT.000000.000000.0.0. 043: 044: 045: 046: } if (support != CL_TRUE) { puts("image not supported").000000. Each data in the image object is of a vector type containing 4 components.000000. since OpenCL does not guarantee precision of operations).1.1. It is supported if CL_DEVICE_IMAGE_SUPPORT returns CL_TRUE [17].0.000000.000000. which is a struct containing two elements.000000.000000.000000.0. The possible values 121 .1.000000.000000 10.0. "image_channel_order" sets the order of the element.image_channel_order = CL_R.000000.000000.000000.000000 18.0.0.000000.1.000000 10.0.000000. The above must be performed.000000.
X) (X. CL_UNORM_SHORT_101010 can only be set when "image_channel_order" is set to "CL_RGB".0. Of these.0.0.6 below.Y.7: Possible values for "image_channel_data_types" Image Channel Data Type CL_SNORM_INT8 CL_SNORM_INT16 CL_UNORM_INT8 CL_UNORM_INT16 CL_UNORM_SHORT_565 CL_UNORM_SHORT_555 CL_UNORM_SHORT_101010 CL_SIGNED_INT8 CL_SIGNED_INT16 CL_SIGNED_INT32 CL_UNSIGNED_INT8 CL_UNSIGNED_INT16 CL_UNSIGNED_INT32 CL_FLOAT CL_HALF_FLOAT Corresponding Type char short uchar ushort ushort (with RGB) ushort (with RGB) uint (with RGB) char short int uchar ushort uint float half 122 .0f.1) (X.X) (X.0.Y.1) The values that can be set for "image_channel_data_type" is shown in Table 5.CL_BGRA.X.6: Possible values for "image_channel_order" Enum values for channel order CL_R CL_A CL_RG CL_RA CL_RGB CL_RGBA.CL_ARGB CL_INTENSITY CL_LUMINANCE Corresponding Format (X.7 below.X. Table 5. The 0/1 value represent the fact that those components are set to 0.1) (0. CL_UNORM_SHORT_555.W) (X.B01-02632560-294 The OpenCL Programming Book for "image_channel_order" are shown in Table 5. Table 5.Y) (X.X.Z.0f/1.Z.0.Y. The X/Y/Z/W are the values that can be set for the format. CL_UNORM_SHORT_565.0.0.1) (X.X.
0}. 30. The arguments are the corresponding context. NULL). data. 0. width. As shown above. 10. the image row pitch must be specified. image object. height. 40. host pointer. The target coordinate and target size are specified in a 3-component vector of type size_t. /* Set parameter to be used to transfer image object */ size_t origin[] = {0. 061: 062: /* Create image object */ image = clCreateImage2D(context. NULL. NULL). 1}. read/write permission. 4. 064: 065: 066: 067: 068: 069: 070: 071: 072: 073: 074: 075: 076: /* Transfer to device */ clEnqueueWriteImage(command_queue. 0. 20. CL_MEM_READ_ONLY. 10. 40. image object is created using clCreateImage2D(). 4. 4. we are ready to create the image object. If this is set. 123 . 40. 20. pointer to data to be transferred. image data format. input row pitch. }. region. 30. target coordinate. Now the data for the image object is transferred from the host to device. image. 30. Refer to 4-1-3 for explanation on the block enable and events objects. 20. Host pointer is used if the data already exists on the host. and the data is to be used directly from the kernel. 10. block enable. float data[] = { /* Transfer Data */ 10. origin. The clEnqueueWriteImage() is used to transfer the image data. number of events in wait list. the 3rd component to target coordinate is 0.B01-02632560-294 The OpenCL Programming Book Now that the image format is specified. 20. 0. input slice pitch. The host pointer is not specified in this case. and event object. 30. and the 3rd component to the size is 1. and error code. 0. The arguments are command queue. /* Size of object to be transferred */ 4*sizeof(float). &fmt. Passing this image object into the device program will allow the data to be accessed. 0. image row pitch. If the image object is 2-D. target size. 40. /* Transfer target coordinate*/ size_t region[] = {4. event wait list. CL_TRUE.
OpenCL allows different modes on how image objects are read. which gets passed in as a parameter when reading an image object. 002: const sampler_t s_linear = CLK_FILTER_LINEAR | CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE. 001: const sampler_t s_nearest = CLK_FILTER_NEAREST | CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE. Table 5. The "sampler_t" type defines a sampler object. The properties that can be set are the following.B01-02632560-294 The OpenCL Programming Book Now we will go over the device program.8: Sampler Object Property Values Sampler state <filter mode> Predefined Enums CLK_FILTER_NEAREST Description Use nearest defined coordinate Interpolate between neighboring values <normalized coords> <address mode> CLK_NORMALIZED_COORDS_FALSE CLK_NORMALIZED_COORDS_TRUE CLK_ADDRESS_REPEAT Unnormalized Normalized Out-of-range image coordinates wrapped to valid range CLK_FILTER_LINEAR 124 .8 below. and these properties are defined in this object type. 003: const sampler_t s_repeat = CLK_FILTER_NEAREST | CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_REPEAT. • Filter Mode • Normalize Mode • Addressing Mode The values that can be set for each property are shown in Table 5.
CL_LUMINANCE Clamp point (0. 0.0f) (0. CL_BGRA.4. Plot of the results for different sample modes are shown in Figure 5.0f. The CLK_FILTER_NEAREST mode determines the closest coordinate defined. CLK_ADDRESS_CLAMP CLK_ADDRESS_NONE The filter mode specifies the how non-exact coordinates are handled. CL_RGBA CL_R.0f.B01-02632560-294 The OpenCL Programming Book CLK_ADDRESS_CLAMP_TO_EDGE Out-of-range coord clamped to the extent Out-of-range coord clamped to border color Undefined.9.0f. 0. CL_INTENSITY. The addressing mode specifies how out-of-range image coordinates are handled. OpenCL defines the CLK_FILTER_NEAREST and CLK_FILTER_LINEAR modes. If CLK_ADDRESS_CLAMP is specified. CL_ARGB.0f. CL_RGB. 0. CL_RG. the input data is set to (10.0f) In our sample code. Table 5.0f. The CLK_FILTER_LINEAR mode interpolates the values from nearby coordinates (nearest 4 points if 2D and nearest 8 points if 3D). CL_RA. 0. The filter mode decides how a value at non-exact coordinate is obtained. 1. 20. 30). The address mode decides what to do when a coordinate outside the range of the image is accessed. then the returned value is determined based on the "image_channel_order" as shown in Table 5.0f. and uses this coordinate to access the value at the coordinate. Figure 5. 0.9: CLK_ADDRESS_CLAMP Result as a function of "image_channel_order" Enum values for channel order CL_A.4: Sampler object examples 125 .
0. 126 . This normalizes the image object so that its coordinates are accessed by a value between 0 and 1. However.B01-02632560-294 The OpenCL Programming Book The coordinates are normalized if the CLK_NORMALIZED_COORDS_TRUE is specified. the normalization must be either enabled or disabled for all image reads within a kernel.
5f)). s_nearest. out[1] = read_imagef(im.10 below. sampler object. 0.0 ~ 1. 0. 0. Embedded Profile OpenCL is intended to not only to be used on desktops environments. or uint4 depending on the format. The returned type is float4.3f.0 (-32768 becomes -1. (Note: The action of the read_image*() function is undefined when there is a format mismatch) Table 5.0) 0 ~ 255 normalized to 0. (float2)(1.0 ~ 1.0 ~ 1. or read_imageui(). read_imagei(). (float2)(0.5f)).0 as is Half value converted to float -128 ~ 127 CL_UNORM_INT16 0 ~ 65535 normalized to 0. The format when the image object is read must match the format used when the object was created using clCreateImage2D. The image object can be read using the built-in functions read_imagef(). int4. 010: 011: 012: out[0] = read_imagef(im. The coordinate is specified as a float2 type.10: Format to specify when reading an image object Function read_imagef() Format CL_SNORM_INT8 CL_SNORM_INT16 CL_UNORM_INT8 CL_FLOAT CL_HALF_FLOAT read_imagei() CL_SIGNED_INT8 Description -127 ~ 127 normalized to -1. The formats are shown in Table 5. s_nearest.0 CL_SIGNED_INT16 -32768 ~ 32767 CL_SIGNED_INT32 -2147483648 ~ 2147483647 read_imageui() CL_SIGNED_INT8 0 ~ 255 CL_SIGNED_INT16 0 ~ 65535 CL_SIGNED_INT32 0 ~ 4294967296 The arguments of the read_image*() functions are the image object. (float2)(0.0 ~ 1.0) -32767 ~ 32767 normalized to -1.5f. but for embedded systems 127 . and the coordinate to read.0 (-128 becomes -1. out[2] = read_imagef(im.5f)).B01-02632560-294 The OpenCL Programming Book Now we are ready to read the image object.8f. s_nearest.
. }. The result of operating on Inf or NaN is undefined. typedef struct __attribute__(((packed))) packed_struct_t { . float Inf and NaN may not be implemented. The attribute can be placed on variables. OpenCL defines the Embedded Profile. it may use the round-towards-zero method if the former is not implemented. __attribute__(( value )) This extension is starting to be supported by compilers other than GCC.. Below is an example of an attribute being placed on a variable. • Rounding of floats OpenCL typically uses the round-to-nearest-even method by default for rounding. This is a language extension to standard C that is supported in GCC. and functions. Attribute Qualifiers OpenCL allows the usage of attribute qualifiers. • Other optional functionalities In addition to the above. it may not be possible to implement every functions defined in OpenCL for embedded systems. However. 64-bit long/ulong. as they are optional.B01-02632560-294 The OpenCL Programming Book as well. Examples of an attribute being placed on types are shown below. int a __attribute__((aligned(16))). and will vary depending on the implementation. 3D image filter. 128 . types (typedef. typedef int aligned_int_t __attribute__((aligned(16))). The implementation that only supports the Embedded Profile may have the following restrictions. • Precision of Built-in functions Some built-in functions may have lower precision than the precision defined in OpenCL. struct). but in the Embedded Profile. This should be checked using the clGetDeviceInfo() function to get the "CL_DEVICE_SINGLE_FP_CONFIG" property. For this reason. which gives specific instructions to the compiler.
• reqd_work_group_size() Specifies the number of work-items/work-group. the start address of that variable gets aligned. Pragma OpenCL defines several pragmas. 129 . (1. The syntax is to use "#pragma OPENCL". 2 pragmas. • packed Same as the "packed" in GCC. the start address of that type gets aligned. There are also other attributes defined for function. which gives optimization hints to the compiler. each member in the struct gets padded. • aligned Same as the "aligned" in GCC. the address between this variable and the previously defined variable gets padded. The attributes that can be set in OpenCL are shown below. • endian This specifies the byte order used on a variable. When specified on a variable. type or function to set the attribute to. When specified on a struct. When specified on a type. "host" or "device" can be passed in as an argument to make the byte order the same as either host or device. When specified on a variable. This attribute on a function is undefined in OpenCL. Some hints are given below: • vec_type_hint() Suggests the type of vector to use for optimization • work_group_size_hint() Suggests the number of work-items/work-group.1) should be specified if the kernel is queued using clEnqueueTask().B01-02632560-294 The OpenCL Programming Book The basic grammar is to place an attribute after the variable. The kernel will throw an error when the number of work-items/work-group is a different number.1.
#pragma OPENCL EXTENSION <extension_name> : <behavior> <extension_name> gets the name of the OpenCL extension. the precision may be different from when the operations are performed separately. In some cases. EXTENSION This enables or disables optional OpenCL extensions to be used. This FP_CONTRACT pragma enables or disables the usage of these contract operations. #pragma OPENCL FP_CONTRACT on-off-switch Some hardware supports "FMA" instructions. The standard extensions are shown in Table 5. FP_CONTRACT This is the same as the FP_CONTRACT defined in standard C.11: Extension name Extension name cl_khr_fp64 cl_khr_fp16 cl_khr_select_fprounding_mode cl_khr_global_int32_base_atomics. These types of instructions. and EXTENSION are defined. cl_khr_global_int64_extended_atomics cl_khr_3d_image_writes cl_khr_byte_addressable_store all Extended capability Support for double precision Support for half precision Support for setting the rounding type Support for atomic operations of 32-bit values Support for atomic operations of 64-bit values Enable writes to 3-D image object Enable byte-size writes to address Support for all extensions <behavior> gets one of the value on Table 5.B01-02632560-294 The OpenCL Programming Book FP_CONTRACT. where multiple operations are performed as 1 operation.11 below. which sums a number with the product of 2 numbers in one instruction. 130 .12. are known as contract operations. Specifying "require" when the enabled extension is "all" will display an error. Table 5. cl_khr_global_int32_extended_atomics cl_khr_global_int64_base_atomics.
• Stock price data in passed in as an int-array named "value". A moving average filter is used commonly in image processing and signal processing as a low-pass filter. and gradually convert sections of the code to be processed in parallel. • The array length is passed in as "length" of type int • The width of the data to compute the average for is passed in as "width" of type int To make the code more intuitive. the code on List 5. We will use a sample application that analyzes stock price data to walk through porting of standard C code to OpenCL C in order to utilize a device.12: Supported values for <behavior> Behavior require disable enable Description Check that extension is supported (compile error otherwise) Disable extensions Enable extensions OpenCL Programming Practice This section will go over some parallel processing methods that can be used in OpenCL. You may not experience any speed-up depending on the type of hardware you have. We will start from a normal C code. This should aid you in gaining intuition on how to parallelize your code. The result of the moving average is returned as an array of floats with the name "average". Note that the sample code shown in this section is meant to be pedagogical in order to show how OpenCL is used. The analysis done in this application is to compute the moving average of the stock price for different stocks.B01-02632560-294 The OpenCL Programming Book Table 5. Standard Single-Thread Programming We will first walk through a standard C code of the moving average function.21 gets rid of all error checks that would 131 . The function has the following properties.
so this is the code will eventually be ported into kernel code. float *average. i++) { add_value += values[i]. i < length. This function is what we want to process on the device. for (i=0. int i. i++) { average[i] /= (float)width. i < length. } /* Compute sum for the (width)th ~ (length-1)th elements */ for (i=width. int add_value. i < width.: } } /* Compute average from the sum */ for (i=width-1. /* Compute sum for the first "width" elements */ add_value = 0. List 5. i++) { average[i] = 0. } /* Insert zeros to 0th ~ (width-2)th element */ for (i=0.B01-02632560-294 The OpenCL Programming Book normally be performed. i < width-1.0f.21: Moving average of integers implemented in standard C 001: void moving_average(int *values. } average[width-1] = (float)add_value. int length. average[i] = (float)(add_value).values[i-width] + values[i]. i++) { add_value = add_value . int width) 132 .
Zeros are placed for average[0] ~ average[width-2] in lines 22~25. i < width-1. each indices of the average array contain the average of the previous width-1 values and the value of that index. int width) 133 . i++) { add_value = 0. Lines 16-20 computes the sum for the remaining indices. which can become significant over time. The average itself is computed by first summing up the "width" number of values and storing it into the average array (lines 9-20). this method may result in rounding errors. and stores it in average[width-1]. List 5. In other words. subtracting the oldest value and adding the newest value. i < length. The value of average[0] ~ average[width-2] = average[1] are zeros. float *average. float add_value. average[3] contain the average of value[1].22 should be used. j++) { add_value += values[i . j. i++) { average[i] = 0.0f.22: Moving average of floats implemented in standard C 001: void moving_average_float(float *values. but if the input is of type float. for (j=0. Lines 9-14 computes the sum of the first "width" elements.j]. value[2] and value[3].B01-02632560-294 The OpenCL Programming Book In this example. a method shown in List 5. int length. which is more efficient than computing the sum of "width" elements each time.0f. since this computation will require values not contained in the input array. } /* Insert zeros to 0th ~ (width-2)th elements */ for (i=0. 002: 003: 004: 005: { 006: 007: 008: 009: 010: 011: 012: 013: 014: 015: 016: 017: 018: 019: } /* Compute average of (width-1) ~ (length-1) elements */ for (i=width-1. In this case. j < width. if the width is 3. int i. This works since the input data is an integer type. This is done by starting from the previously computed sum. since it would require value[-2] and value[-1].
B01-02632560-294 The OpenCL Programming Book 020: 021: 022: } } average[i] = add_value / (float)width. 50 List 5. We will now show a main() function that will call the function in List 5.24). 008: 009: /* Define width for the moving average */ 010: #define WINDOW_SIZE (13) 011: 012: int main(int argc.21 to perform the computation (List 5.24: Standard C main() function to all the moving average function 001: #include <stdio. 107.23: Input data (stock_array1.txt".h> 003: 004: /* Read Stock data */ 005: int stock_array1[] = { 006: 007: }. float *result. .23. #include "stock_array1. 109. char *argv[]) 013: { 014: 015: 016: 017: 018: int data_num = sizeof(stock_array1) / sizeof(stock_array1[0]). int window_num = (int)WINDOW_SIZE.. whose content is shown in List 5.txt) 100.. 98.h> 002: #include <stdlib.txt" 134 . 104. List 5. The input data is placed in a file called "stock_array1.
result[i]). i < data_num. The code in List 5. i. i++) { printf("result[%d] = %f¥n". We have now finished writing a single threaded program to compute the moving average. int i.25 after being ported. 002: __global float *average. window_num). Porting to OpenCL The first step is to convert the moving_average() function to kernel code. This code will be executed on the device. data_num. /* Allocate space for the result */ result = (float *)malloc(data_num*sizeof(float)). result. List 5. This will now be converted to OpenCL code to use the device. The above code will be eventually transformed into a host code that will call the moving average kernel.cl) 001: __kernel void moving_average(__global int *values.21 becomes as shown in List 5.25: Moving average kernel (moving_average. or OpenCL C. /* Call the moving average function */ moving_average(stock_array1. } /* Print result */ for (i=0. Our journey has just begun.B01-02632560-294 The OpenCL Programming Book 019: 020: 021: 022: 023: 024: 025: 026: 027: 028: 029: 030: 031: 032: 033: 034: 035: 036: 037: 038: } /* Deallocate memory */ free(result). 135 .
i < length. which adds the __kernel qualifier to the function. i++) { add_value += values[i]. } /* Insert zeros to 0th ~ (width-2)th elements */ for (i=0. i++) { average[i] = 0. int width) int i. int add_value.0f. } Note that we have only changed lines 1 and 2. and the address qualifier __global specifying the location of the input data and where the result will be placed. 136 .B01-02632560-294 The OpenCL Programming Book: } int length. i < length. for (i=0. i < width. i++) { average[i] /= (float)width.26. i++) { add_value = add_value . The host code is shown in List 5. /* Compute sum for the first "width" elements */ add_value = 0.values[i-width] + values[i]. } /* Compute average of (width-1) ~ (length-1) elements */ for (i=width-1. average[i] = (float)(add_value). } average[width-1] = (float)add_value. i < width-1. /* Compute sum for the (width)th ~ (length-1)th elements */ for (i=width.
B01-02632560-294
The OpenCL Programming Book
List 5.26: Host code to execute the moving_average() kernel
001: #include <stdlib.h> 002: #ifdef __APPLE__ 003: #include <OpenCL/opencl.h> 004: #else 005: #include <CL/cl.h> 006: #endif 007: #include <stdio.h> 008: 009: /* Read Stock data */ 010: int stock_array1[] = { 011: 012: }; 013: 014: /* Define width for the moving average */ 015: #define WINDOW_SIZE (13) 016: 017: #define MAX_SOURCE_SIZE (0x100000) 018: 019: int main(void) 020: { 021: 022: 023: 024: 025: 026: 027: 028: 029: 030: 031: 032: 033: 034: 035: cl_platform_id platform_id = NULL; cl_uint ret_num_platforms; cl_device_id device_id = NULL; cl_uint ret_num_devices; cl_context context = NULL; cl_command_queue command_queue = NULL; cl_mem memobj_in = NULL; cl_mem memobj_out = NULL; cl_program program = NULL; cl_kernel kernel = NULL; size_t kernel_code_size; char *kernel_src_str; float *result; cl_int ret; FILE *fp; #include "stock_array1.txt"
137: /* Create Kernel */ /* Create Program Object */ program = clCreateProgramWithSource(context, 1, (const char **)&kernel_src_str, (const size_t *)&kernel_code_size, &ret); /* Compile kernel */ ret = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL); /* Read Kernel Code */ fp = fopen("moving_average.cl", "r"); kernel_code_size = fread(kernel_src_str, 1, MAX_SOURCE_SIZE, fp); fclose(fp); /* Create Command Queue */ command_queue = clCreateCommandQueue(context, device_id, 0, &ret); /* Create Context */ context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &ret); /* Get Device */ ret = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_DEFAULT, 1, &device_id, &ret_num_devices); /* Get Platform */ ret = clGetPlatformIDs(1, &platform_id, &ret_num_platforms); /* Allocate space for the result on the host side */ result = (float *)malloc(data_num*sizeof(float)); /* Allocate space to read in kernel code */ kernel_src_str = (char *)malloc(MAX_SOURCE_SIZE); int data_num = sizeof(stock_array1) / sizeof(stock_array1[0]); int window_num = (int)WINDOW_SIZE; int i;
138
B01-02632560-294
The OpenCL Programming Book:
kernel = clCreateKernel(program, "moving_average", &ret); /* Create buffer for the input data on the device */ memobj_in = clCreateBuffer(context, CL_MEM_READ_WRITE, data_num * sizeof(int), NULL, &ret); /* Create buffer for the result on the device */ memobj_out = clCreateBuffer(context, CL_MEM_READ_WRITE, data_num * sizeof(float), NULL, &ret); /* Copy input data to the global memory on the device*/ ret = clEnqueueWriteBuffer(command_queue, memobj_in, CL_TRUE, 0, data_num * sizeof(int), stock_array1, 0, NULL, NULL); /* Set kernel arguments */ ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&memobj_in); ret = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&memobj_out); ret = clSetKernelArg(kernel, 2, sizeof(int), (void *)&data_num); ret = clSetKernelArg(kernel, 3, sizeof(int), (void *)&window_num); /* Execute the kernel */ ret = clEnqueueTask(command_queue, kernel, 0, NULL, NULL); /* Copy result from device to host */ ret = clEnqueueReadBuffer(command_queue, memobj_out, CL_TRUE, 0, data_num * sizeof(float), result, 0, NULL, NULL);
/* OpenCL Object Finalization */ ret = clReleaseKernel(kernel); ret = clReleaseProgram(program); ret = clReleaseMemObject(memobj_in); ret = clReleaseMemObject(memobj_out); ret = clReleaseCommandQueue(command_queue);
139
B01-02632560-294
The OpenCL Programming Book
108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: }
ret = clReleaseContext(context); /* Display Results */ for (i=0; i < data_num; i++) { printf("result[%d] = %f¥n", i, result[i]); } /* Deallocate memory on the host */ free(result); free(kernel_src_str); return 0;
This host is based on the code in List 5.24, adding the OpenCL runtime API commands required for the kernel execution. Note the code utilizes the online compile method, as the kernel source code is read in (Lines 60-69). However, although the code is executable, it is not written to run anything in parallel. The next section will show how this can be done.
Vector Operations
First step to see whether vector-types can be used for the processing. For vector types, we can expect the OpenCL implementation to perform operations using the SIMD units on the processor to speed up the computation. We will start looking at multiple stocks from this section, as this is more practical. The processing will be vector-ized such that the moving average computation for each stock will be executed in parallel. We will assume that the processor will have a 128-bit SIMD unit, to operate on four 32-bit data in parallel. In OpenCL, types such as int4 and float4 can be used. List 5.27 shows the price data for multiple stocks, where each row contains the price of multiple stocks at one instance in time. For simplicity's sake, we will process the data for 4 stocks in this section.
List 5.27: Price data for multiple stocks (stock_array_many.txt)
140
209. 319. 315. 1098. 783. 1089. /* Compute sum for the first "width" elements for 4 stocks */ add_value = (int4)0.28: Price data for 4 stocks (stock_array_4. . 100. 12 109. 259. 950.. 790.txt) 100. i++) { add_value += values[i]. 313. 100. 980 For processing 4 values at a time. 310. 002: 003: 004: 005: { 006: 007: 008: 009: 010: 011: 012: 013: 014: 015: } average[width-1] = convert_float4(add_value). 1089... 1100.. .. 210. 107. respectively. 995. 1105. 212. 985. 971. 98.. 109. .cl) 001: __kernel void moving_average_vec4(__global int4 *values. int length. 200. int width) 141 . … 50. 210. 315.. List 5... .B01-02632560-294 The OpenCL Programming Book 100. 1098. 687.29: Vector-ized moving average kernel (moving_average_vec4. 212. i < width. 321. 33. 33. 310. 980. 321.29. 319. 21 107. 104. 18 … 50. The new kernel code will look like List 5. 792. 259. . 1098. ... 18 104. 209. for (i=0. 313.. /* A vector to hold 4 components */ __global float4 *average. 9 List 5. 788. 763. 1105. we can just replace int and float with int4 and float4.. 200.. int4 add_value.. 1100.. int i.. 983.. 1098. 15 98. 990.
so these do not need to be changed (Lines 12. average[i] = convert_float4(add_value).h> 006: #endif 007: #include <stdio.values[i-width] + values[i]. } The only differences from List 5.h> 004: #else 005: #include <CL/cl. Note that the operators (+. List 5. -. /) are overloaded to be used on vector-types.h> 008: 009: #define NAME_NUM (4) /* Number of Stocks */ 010: #define DATA_NUM (21) /* Number of data to process for each stock*/ 011: 012: /* Read Stock data */ 013: int stock_array_4[NAME_NUM*DATA_NUM]= { 142 . i < length.h> 002: #ifdef __APPLE__ 003: #include <OpenCL/opencl. and the use of convert_float4() function. 29).0f).7. } /* Compute average of (width-1) ~ (length-1) elements for 4 stocks */ for (i=width-1. } /* Insert zeros to 0th ~ (width-2)th element for 4 stocks*/ for (i=0. *.30: Host code to run the vector-ized moving average kernel 001: #include <stdlib.29 for float). i++) { average[i] /= (float4)width.10 for int and Lines 2. i++) { average[i] = (float4)(0. i < width-1. i++) { add_value = add_value .B01-02632560-294 The OpenCL Programming Book 016: 017: 018: 019: 020: 021: 022: 023: 024: 025: 026: 027: 028: 029: 030: 031: } /* Compute sum for the (width)th ~ (length-1)th elements for 4 stocks */ for (i=width.25 is the conversion of scalar to vector type (Lines 1. 18. i < length.24.
cl_mem memobj_out = NULL. int i. size_t kernel_code_size. int point_num = NAME_NUM * DATA_NUM for the result on the host side */ /* Allocate space to read in kernel code */ kernel_src_str = (char *)malloc(MAX_SOURCE_SIZE). int window_num = (int)WINDOW_SIZE. cl_mem memobj_in = NULL. j. cl_command_queue command_queue = NULL. int name_num = (int)NAME_NUM. cl_platform_id platform_id = NULL. cl_device_id device_id = NULL.B01-02632560-294 The OpenCL Programming Book 014: 015: }. float *result. char *kernel_src_str. FILE *fp. cl_int ret. cl_uint ret_num_devices. 143 . cl_kernel kernel = NULL. int data_num = (int)DATA_NUM. cl_context context = NULL. 016: #include "stock_array_4. cl_uint ret_num_platforms. cl_program program = NULL.
&ret). /* Get Platform */ ret = clGetPlatformIDs(1. /* Get Device */ ret = clGetDeviceIDs(platform_id. /* Read kernel source code */ fp = fopen("moving_average_vec4.cl". (const size_t *)&kernel_code_size. /* Create buffer for the result on the device */ 144 . &device_id. 1. /* Create kernel */ kernel = clCreateKernel(program. 0. /* Create command queue */ command_queue = clCreateCommandQueue(context. &device_id. &ret). &ret). &ret). 1. /* Create buffer for the input data on the device */ memobj_in = clCreateBuffer(context. (const char **)&kernel_src_str. point_num * sizeof(int): result = (float *)malloc(point_num*sizeof(float)). kernel_code_size = fread(kernel_src_str. &ret_num_devices). MAX_SOURCE_SIZE. NULL. /* Create Context */ context = clCreateContext( NULL. NULL. fp). CL_MEM_READ_WRITE. "moving_average_vec4". 1. CL_DEVICE_TYPE_DEFAULT. &ret_num_platforms). NULL. NULL). NULL. fclose(fp). /* Compile kernel */ ret = clBuildProgram(program. /* Create Program Object */ program = clCreateProgramWithSource(context. 1. &device_id. 1. &platform_id. NULL. "r"). &ret). device_id.
sizeof(cl_mem). 3. (void *)&memobj_out). NULL. j++) { printf("%f. 0. /* Set Kernel Arguments */ ret = clSetKernelArg(kernel. sizeof(int). ret = clReleaseMemObject(memobj_in). i < data_num. sizeof(cl_mem). 2. ret = clReleaseCommandQueue(command_queue). CL_TRUE. ". ret = clSetKernelArg(kernel. point_num * sizeof(int). 1. i++) { printf("result[%d]:". j < name_num. CL_MEM_READ_WRITE. ret = clReleaseProgram(program). /* Copy input data to the global memory on the device*/ ret = clEnqueueWriteBuffer(command_queue. 0. ret = clReleaseContext(context). /* Copy result from device to host */ ret = clEnqueueReadBuffer(command_queue. /* Print results */ for (i=0. NULL). ret = clReleaseMemObject(memobj_out). ret = clSetKernelArg(kernel. 0. memobj_in. point_num * sizeof(float). memobj_out. sizeof(int). NULL. (void *)&memobj_in). NULL. for (j=0. /* OpenCL Object Finalization */ ret = clReleaseKernel(kernel). 0. /* Execute kernel */ ret = clEnqueueTask(command_queue. result[i*NAME_NUM+j]). point_num * sizeof(float). (void *)&window_num). NULL). 0. ret = clSetKernelArg(kernel. result. NULL. i). } 145 . (void *)&data_num). kernel. stock_array_4. NULL).: memobj_out = clCreateBuffer(context. &ret). CL_TRUE.
002: 003: 004: 005: 006: { 007: int i. The new kernel code is shown in List 5.27. int length.cl (line 66). the kernel code that gets read is changed to moving_average_vec4. The kernel will take in a parameter "name_num".cl) 001: __kernel void moving_average_many(__global int4 *values. List 5. free(kernel_src_str). we will assume the number of stocks to process is a multiple of 4.26 is that the data to process is increased by a factor of 4. and the kernel name is changed to moving_average_vec4 (line 78). which is the number of stocks to process. } printf("¥n"). int name_num. int width) 146 . but we will instead allow the kernel to take care of this.29 and vector-ize the input data on the host side.B01-02632560-294 The OpenCL Programming Book 122: 123: 124: 125: 126: 127: 128: 129: 130: } return 0. Since we will be processing 4 stocks at a time. We will now change the program to allow processing of more than 4 stocks. We could just call the kernel on List 5.31 below. This will be used to calculate the number of loops required to process all stocks. and that the data length parameter is hard coded.31: Moving average kernel of (multiple of 4) stocks (moving_average_many. __global float4 *average. j. /* Deallocate memory on the host */ free(result). In addition. as in the data in List 5. the kernel code will just have to loop the computation so that more than 4 stocks can be computed within the kernel. For simplicity. The only difference from List 5.
for (i=0.h> 147 .0f). i < width-1. i < width.values[(i-width)*loop_num+j] + average[i*loop_num+j] = convert_float4(add_value). } /* Compute average of (width-1) ~ (length-1) elements for 4 stocks */ for (i=width-1. i < length. /* compute the number of times to loop */ int4 add_value.32.h> 002: #ifdef __APPLE__ 003: #include <OpenCL/opencl.32: Host code for calling the kernel in List 5. } /* Insert zeros to 0th ~ (width-2)th element for 4 stocks*/ for (i=0. 022: 023: 024: 025: 026: 027: 028: 029: 030: 031: 032: 033: 034: 035: } The host code is shown in List 5. i++) { average[i*loop_num+j] = (float4)(0. for (j=0. i++) { average[i*loop_num+j] /= (float4)width. /* Compute sum for the (width)th ~ (length-1)th elements for 4 stocks */ for (i=width. } } values[i*loop_num+j]. List 5. j++) { /* Compute sum for the first "width" elements for 4 stocks */ add_value = (int4)0. i++) { add_value = add_value . } average[(width-1)*loop_num+j] = convert_float4(add_value).B01-02632560-294 The OpenCL Programming Book 008: 009: 010: 011: 012: 013: 014: 015: 016: 017: 018: 019: 020: 021: int loop_num = name_num / 4. j < loop_num.31 001: #include <stdlib. i < length. i++) { add_value += values[i*loop_num+j].
016:: cl_platform_id platform_id = NULL.B01-02632560-294 The OpenCL Programming Book 004: #else 005: #include <CL/cl. cl_program program = NULL. FILE *fp. size_t kernel_code_size. #include "stock_array_many. cl_context context = NULL. cl_mem memobj_in = NULL.h> 006: #endif 007: #include <stdio.txt" 148 .h> 008: 009: #define NAME_NUM (8) /* Number of stocks */ 010: #define DATA_NUM (21) /* Number of data to process for each stock */ 011: 012: /* Read Stock data */ 013: int stock_array_many[NAME_NUM*DATA_NUM]= { 014: 015: }. cl_uint ret_num_platforms. cl_mem memobj_out = NULL. cl_kernel kernel = NULL. char *kernel_src_str. cl_command_queue command_queue = NULL. cl_device_id device_id = NULL. cl_uint ret_num_devices. float *result. cl_int ret.
/* Read kernel source code */ fp = fopen("moving_average_many. (const size_t *)&kernel_code_size. fp). /* Get Platform*/ ret = clGetPlatformIDs(1. &ret). int i. /* Create Program Object */ program = clCreateProgramWithSource(context. int point_num = NAME_NUM * DATA_NUM. 1. NULL.cl". 0. device_id. 1. /* Create Context */ context = clCreateContext(NULL. CL_DEVICE_TYPE_DEFAULT. &platform_id. MAX_SOURCE_SIZE. &ret_num_devices).B01-02632560-294 The OpenCL Programming Book: int window_num = (int)WINDOW_SIZE. &device_id. /* Allocate space for the result on the host side */ result = (float *)malloc(point_num*sizeof(float)). fclose(fp). /* Create Command Queue */ command_queue = clCreateCommandQueue(context. NULL. /* Compile kernel */ 149 . 1. int data_num = (int)DATA_NUM. &ret). /* Get Device */ ret = clGetDeviceIDs(platform_id. &device_id. int name_num = (int)NAME_NUM. "r"). 1. /* Allocate space to read in kernel code */ kernel_src_str = (char *)malloc(MAX_SOURCE_SIZE). &ret_num_platforms). j. &ret). (const char **)&kernel_src_str. kernel_code_size = fread(kernel_src_str.
point_num * sizeof(float). NULL. &ret). /* Create buffer for the input data on the device */ memobj_in = clCreateBuffer(context. (void *)&memobj_out). result. 0. stock_array_many. NULL).B01-02632560-294 The OpenCL Programming Book: ret = clBuildProgram(program. ret = clSetKernelArg(kernel. (void *)&name_num). NULL. CL_MEM_READ_WRITE. CL_TRUE. 4. sizeof(cl_mem). NULL). CL_TRUE. sizeof(cl_mem). 1. NULL). point_num * sizeof(int). sizeof(int). point_num * sizeof(int). /* Create kernel */ kernel = clCreateKernel(program. NULL). NULL. point_num * sizeof(float). /* Create buffer for the result on the device */ memobj_out = clCreateBuffer(context. ret = clSetKernelArg(kernel. 0. /* Copy input data to the global memory on the device*/ ret = clEnqueueWriteBuffer(command_queue. sizeof(int). 0. ret = clSetKernelArg(kernel. (void *)&window_num). 1. (void *)&data_num). NULL. kernel. memobj_out. ret = clSetKernelArg(kernel. NULL. /* Set Kernel Arguments */ ret = clSetKernelArg(kernel. 150 . /* Execute kernel */ ret = clEnqueueTask(command_queue. 0. /* Copy result from device to host */ ret = clEnqueueReadBuffer(command_queue. CL_MEM_READ_WRITE. "moving_average_many". ret = clReleaseProgram(program). 0. sizeof(int). 0. (void *)&memobj_in). &ret). NULL. 2. NULL. memobj_in. /* OpenCL Object Finalization */ ret = clReleaseKernel(kernel). &ret). &device_id. 3.
ret = clReleaseCommandQueue(command_queue). ret = clReleaseContext(context). This is the most basic method of parallelization. } /* Deallocate memory on the host */ free(result). which processed all the data. /* Print results */ for (i=0. only one instance of the kernel was executed. for (j=0. j < name_num. ". result[i*NAME_NUM+j]). To use multiple compute units simultaneously. free(kernel_src_str). the kernel code that gets read is changed to moving_average_many.cl (line 67). which is done simply by replacing scalar-types with vector-types. i). Up until this point. This section concentrated on using SIMD units to perform the same process on multiple data sets in parallel. i++) { printf("result[%d]:". The only difference from List 5. return 0. multiple kernel instances must be executed 151 . In addition. Data Parallel Processing This section will focus on using multiple compute units to perform moving average for multiple stocks. } printf("¥n").30 is that the number of stocks to process has been increased to 8. The next step is expanding this to use multiple compute units capable of performing SIMD operations.B01-02632560-294 The OpenCL Programming Book 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: } ret = clReleaseMemObject(memobj_in). i < data_num. and the kernel name is changed to moving_average_many (line 79). which get passed in as an argument to the kernel (line 98). ret = clReleaseMemObject(memobj_out). j++) { printf("%f.
__global float4 *average. List 5. as this method is more suited for this process. /* "j" decides on the data subset to j = get_global_id(0). for (i=0. the code in List 5.B01-02632560-294 The OpenCL Programming Book in parallel. int4 add_value. /* Compute sum for the first "width" elements for 4 stocks */ add_value = (int4)0. We will use the data parallel model. or different kernels in parallel (task parallel). If this is not done. int name_num. 002: 003: 004: 005: 006: { 007: 008: 009: 010: 011: 012: 013: 014: 015: 016: 017: 018: 019: 020: /* Compute sum for the (width)th ~ (length-1)th elements for 4 stocks */ } average[(width-1)*loop_num+j] = convert_float4(add_value).cl) 001: __kernel void moving_average_vec4_para(__global int4 *values. int length. the same kernel will run on the same data sets.31 as the basis to perform the averaging on 8 stocks. Therefore. which happens to be the same value as the value of the iterator "j". /* Used to select different data set for each instance */ int i. j. each instance of the kernel must know where it is being executed within the index space. int width) process for the kernel instance*/ 152 . int loop_num = name_num / 4. The get_global_id() function can be used to get the kernel instance's global ID. They can either be the same kernel running in parallel (data parallel). i < width.33: Moving average kernel for 4 stocks (moving_average_vec4_para. Since this code operates on 4 data sets at once. This is achieved by setting the work group size to 2 when submitting the task. we can use 2 compute units to perform operations on 8 data sets at once. In order to use the data parallel mode. We will use the kernel in List 5. i++) { add_value += values[i*loop_num+j].33.31 can be rewritten to the following code in List 5.
i < length. i++) { add_value = add_value . i < width-1. In line 11. which specifies the instance of the kernel as well as the data set to process. the host code must be changed as shown below in List 5.h> 002: #ifdef __APPLE__ 003: #include <OpenCL/opencl. the value of "j" is either 0 or 1.h> 004: #else 005: #include <CL/cl. i++) { average[i*loop_num+j] /= (float4)width.0f).B01-02632560-294 The OpenCL Programming Book 021: 022: 023: 024: 025: 026: 027: 028: 029: 030: 031: 032: 033: 034: 035: } for (i=width. Since each compute unit is executing an instance of the kernel.34: Host code for calling the kernel in List 5.h> 008: 009: #define NAME_NUM (8) /* Number of stocks */ 010: #define DATA_NUM (21) /* Number of data to process for each stock */ 011: 012: /* Read Stock data */ 013: int stock_array_many[NAME_NUM*DATA_NUM]= { 153 .values[(i-width)*loop_num+j] + average[i*loop_num+j] = convert_float4(add_value). } /* Compute average of (width-1) ~ (length-1) elements for 4 stocks */ for (i=width-1. To take the change in the kernel into account. i < length. i++) { average[i*loop_num+j] = (float4)(0. } values[i*loop_num+j]. } /* Insert zeros to 0th ~ (width-2)th element for 4 stocks*/ for (i=0.33 001: #include <stdlib. List 5. which performs operations on 4 data sets.34.h> 006: #endif 007: #include <stdio. 8 data sets are processed over 2 compute units.
int window_num = (int)WINDOW_SIZE. int name_num = (int)NAME_NUM. cl_program program = NULL. float *result. cl_context context = NULL. cl_uint ret_num_platforms. cl_kernel kernel = NULL. cl_mem memobj_in = NULL to read in kernel code */ kernel_src_str = (char *)malloc(MAX_SOURCE_SIZE). cl_uint ret_num_devices. 016: #include "stock_array_many. int i. 154 . char *kernel_src_str. cl_int ret. int point_num = NAME_NUM * DATA_NUM.B01-02632560-294 The OpenCL Programming Book 014: 015: }. cl_command_queue command_queue = NULL. cl_platform_id platform_id = NULL. int data_num = (int)DATA_NUM.j. cl_mem memobj_out = NULL. FILE *fp. cl_device_id device_id = NULL. size_t kernel_code_size.
/* Create Context */ context = clCreateContext(NULL. &ret).cl". &ret). 1. point_num * sizeof(int). NULL. &device_id. "moving_average_vec4_para". 1. NULL. 1. /* Compile kernel */ ret = clBuildProgram(program. /* Create Program Object */ program = clCreateProgramWithSource(context. NULL. kernel_code_size = fread(kernel_src_str. /* Create buffer for the result on the device */ 155 . &platform_id. &ret). /* Get Platform*/ ret = clGetPlatformIDs(1. MAX_SOURCE_SIZE. /* Create buffer for the input data on the device */ memobj_in = clCreateBuffer(context. 0. (const size_t *)&kernel_code_size. NULL). CL_MEM_READ_WRITE. &device_id. &ret_num_platforms). /* Create kernel */ kernel = clCreateKernel(program. 1. 1. (const char **)&kernel_src_str. &ret). &ret_num_devices). NULL. device_id. /* Get Device */ ret = clGetDeviceIDs(platform_id: /* Allocate space for the result on the host side */ result = (float *)malloc(point_num*sizeof(float)). CL_DEVICE_TYPE_DEFAULT. NULL. &device_id. "r"). fclose(fp). fp). &ret). /* Read kernel source code */ fp = fopen("moving_average_vec4_para. /* Create Command Queue */ command_queue = clCreateCommandQueue(context.
NULL. ret = clSetKernelArg(kernel. NULL. (void *)&window_num). sizeof(int). (void *)&data_num). kernel. CL_MEM_READ_WRITE. /* Global number of work items */ local_item_size[0] = 1. (void *)&memobj_out). point_num * sizeof(int). CL_TRUE. size_t global_item_size[3]. (void *)&memobj_in). 0. NULL). 156 . 0. which indirectly sets the number of workgroups to 2*/ /* Execute Data Parallel Kernel */ ret = clEnqueueNDRangeKernel(command_queue. /* Set parameters for data parallel processing (work item) */ cl_uint work_dim = 1.: memobj_out = clCreateBuffer(context. /* Set Kernel Arguments */ ret = clSetKernelArg(kernel. 0. /* Number of work items per work group */ /* --> global_item_size[0] / local_item_size[0] becomes 2. point_num * sizeof(float). /* Copy result from device to host */ ret = clEnqueueReadBuffer(command_queue. stock_array_many. CL_TRUE. 0. NULL. ret = clSetKernelArg(kernel. &ret). size_t local_item_size[3]. 1. (void *)&name_num). result. sizeof(cl_mem). NULL. /* Copy input data to the global memory on the device*/ ret = clEnqueueWriteBuffer(command_queue. 0. memobj_out. sizeof(int). NULL. work_dim. sizeof(cl_mem). 3. global_item_size[0] = 2. local_item_size. 0. ret = clSetKernelArg(kernel. memobj_in. global_item_size. ret = clSetKernelArg(kernel. point_num * sizeof(float). 2. NULL). NULL). sizeof(int).
157 . i++) { printf("result[%d]: ". ret = clReleaseProgram(program). which indicates a bull market on the horizon. This will be implemented in a task parallel manner. This is implied from the number of global work items (line 107) and the number of work items to process using one compute unite (line 108).114. } /* Deallocate memory on the host */ free(result). /* Deallocate memory on the host */ for (i=0. } printf("¥n"). It is also possible to execute multiple work items on 1 compute unit. The Golden Cross is a threshold point between a short-term moving average and a long-term moving average over time. free(kernel_src_str). The data parallel processing is performed in lines 112 . Task Parallel Processing We will now look at a different processing commonly performed in stock price analysis. ret = clReleaseContext(context). for (j=0. This number should be equal to the number of processing elements within the compute unit for efficient data parallel execution. ret = clReleaseMemObject(memobj_out). j++) { printf("%f. known as the Golden Cross. i). but notice the number of work groups are not explicitly specified. j < name_num. return 0. ret = clReleaseMemObject(memobj_in).B01-02632560-294 The OpenCL Programming Book 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: } /* OpenCL Object Finalization */ ret = clReleaseKernel(kernel). ". result[i*NAME_NUM+j]). i < data_num. ret = clReleaseCommandQueue(command_queue).
The two moving averages will be performed in a task parallel manner. The out-of-order mode can be set as follows. OpenCL does not have an API to explicitly specify the index space for batch processing.h> 004: #else 158 .29 (moving_average_vec4. As mentioned in Chapter 4.B01-02632560-294 The OpenCL Programming Book Unlike data parallel programming. The 3rd argument CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE allows the command queue to send the next queued task to an available compute unit. Allowing out-of-order execution in the command queue sends the next element in queue to an available compute unit. &ret). The host side must do one of the following: • Allow out-of-order execution of the queued commands • Create multiple command queues Creating multiple command queues will allow for explicit scheduling of the tasks by the programmer. Command_queue = clCreateCommandQueue(context. We will use the code in List 5. we will use the out-of-order method and allow the API to take care of the scheduling. the command queue only allows one task to be executed at a time unless explicitly specified to do otherwise. varying the 4th argument to 13 and 26 for each of the moving average to be performed. In this section.h> 002: #ifdef __APPLE__ 003: #include <OpenCL/opencl. This ends up in a scheduling of task parallel processing. Each process need to be queued explicitly using the API function clEnqueueTask(). CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE.cl).35.35: Host code for task parallel processing of 2 moving averages 001: #include <stdlib. The host code becomes as shown in List 5. List 5. We will now perform task parallel processing to find the Golden Cross between a moving average over 13 weeks. and a moving average over 26 weeks. device_id.
#include "stock_array_4.txt" 159 . cl_uint ret_num_platforms. cl_context context = NULL. cl_mem memobj_out26 = NULL. event26. cl_kernel kernel26 = NULL. cl_event event13. cl_mem memobj_out13 = NULL.B01-02632560-294 The OpenCL Programming Book 005: #include <CL/cl.h> 006: #endif 007: #include <stdio. cl_mem memobj_in = NULL. cl_program program = NULL. cl_command_queue command_queue = NULL. size_t kernel_code_size.h> 008: 009: #define NAME_NUM (4) /* Number of stocks */ 010: #define DATA_NUM (100) /* Number of data to process for each stock */ 011: 012: /* Read Stock data */ 013: int stock_array_4[NAME_NUM*DATA_NUM]= { 014: 015: }. cl_device_id device_id = NULL. cl_kernel kernel13 = NULL. 016: 017: /* Moving average width */ 018: #define WINDOW_SIZE_13 (13) 019: #define WINDOW_SIZE_26 (26) 020: 021: 022: #define MAX_SOURCE_SIZE (0x100000) 023: 024: 025: int main(void) 026: { 027: 028: 029: 030: 031: 032: 033: 034: 035: 036: 037: 038: 039: 040: cl_platform_id platform_id = NULL. cl_uint ret_num_devices.
float *result13. int data_num = (int)DATA_NUM. &device_id. &ret_num_devices). &ret). cl_int ret. FILE *fp.B01-02632560-294 The OpenCL Programming Book: char *kernel_src_str. CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE. int point_num = NAME_NUM * DATA_NUM. /* Create Context */ context = clCreateContext( NULL. 1. &platform_id. /* Allocate space to read in kernel code */ kernel_src_str = (char *)malloc(MAX_SOURCE_SIZE). /* Read kernel source code */ 160 . /* Get Device */ ret = clGetDeviceIDs(platform_id. /* average over 26 weeks */ /* Get Platform */ ret = clGetPlatformIDs(1. &ret_num_platforms). &ret). NULL. NULL. &device_id. /* Create Command Queue */ command_queue = clCreateCommandQueue(context. /* average over 13 weeks */ result26 = (float *)malloc(point_num*sizeof(float)). int i. int window_num_13 = (int)WINDOW_SIZE_13. device_id. int name_num = (int)NAME_NUM. j. 1. CL_DEVICE_TYPE_DEFAULT. int window_num_26 = (int)WINDOW_SIZE_26. float *result26. /* Allocate space for the result on the host side */ result13 = (float *)malloc(point_num*sizeof(float)).
/* 13 weeks */ kernel26 = clCreateKernel(program. 1. NULL. (void *)&memobj_in). /* Create kernel */ kernel13 = clCreateKernel(program. sizeof(int). &device_id: fp = fopen("moving_average_vec4.cl". 0. /* Create buffer for the result on the device */ memobj_out13 = clCreateBuffer(context. ret = clSetKernelArg(kernel13. memobj_in. /* Set Kernel Arguments (13 weeks) */ ret = clSetKernelArg(kernel13. &ret). 0. CL_MEM_READ_WRITE. CL_MEM_READ_WRITE. 2. (void *)&window_num_13). /* 26 weeks */ /* Create buffer for the input data on the device */ memobj_in = clCreateBuffer(context. NULL. 0. "moving_average_vec4". &ret). NULL). ret = clSetKernelArg(kernel13. 1. CL_TRUE. NULL). NULL. sizeof(cl_mem). 1. sizeof(int). 3. &ret). (void *)&memobj_out13). /* 26 weeks */ /* Copy input data to the global memory on the device*/ ret = clEnqueueWriteBuffer(command_queue. 1. MAX_SOURCE_SIZE. fp). NULL. "r"). /* 13 weeks */ memobj_out26 = clCreateBuffer(context. point_num * sizeof(float). ret = clSetKernelArg(kernel13. NULL. "moving_average_vec4". (void *)&data_num). kernel_code_size = fread(kernel_src_str. fclose(fp). stock_array_4. &ret). /* Compile kernel */ ret = clBuildProgram(program. /* Create Program Object */ program = clCreateProgramWithSource(context. point_num * sizeof(int). point_num * sizeof(int). (const size_t *)&kernel_code_size. point_num * sizeof(float). &ret). CL_MEM_READ_WRITE. &ret). NULL. sizeof(cl_mem). 161 . (const char **)&kernel_src_str.
point_num * sizeof(float). /* Copy result for the 26 weeks moving average from device to host */ ret = clEnqueueReadBuffer(command_queue. j < name_num.B01-02632560-294 The OpenCL Programming Book 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: /* Submit task to compute the moving average over 13 weeks */ ret = clEnqueueTask(command_queue. memobj_out26. ret = clReleaseMemObject(memobj_out13). ret = clReleaseContext(context). sizeof(cl_mem). /* Display results */ for (i=window_num_26-1. NULL. result26. i ). memobj_out13. 0. /* OpenCL Object Finalization */ ret = clReleaseKernel(kernel13). 2. sizeof(cl_mem). &event26). 0. (void *)&memobj_out26). (void *)&data_num). ret = clSetKernelArg(kernel26. i++) { printf("result[%d]:". ret = clReleaseProgram(program). ret = clSetKernelArg(kernel26. CL_TRUE. CL_TRUE. point_num * sizeof(float). /* Set Kernel Arguments (26 weeks) */ ret = clSetKernelArg(kernel26. 1. 0. (void *)&memobj_in). ret = clReleaseCommandQueue(command_queue). 1. NULL. 1. NULL). i < data_num. &event26. sizeof(int). kernel26. (void *)&window_num_26). NULL). sizeof(int). ret = clReleaseMemObject(memobj_in). for (j=0. &event13). 3. result13. ret = clSetKernelArg(kernel26. /* Copy result for the 13 weeks moving average from device to host */ ret = clEnqueueReadBuffer(command_queue. 0. kernel13. ret = clReleaseKernel(kernel26). 0. j++ ) { 162 . ret = clReleaseMemObject(memobj_out26). /* Submit task to compute the moving average over 26 weeks */ ret = clEnqueueTask(command_queue. &event13.
B01-02632560-294
The OpenCL Programming Book
149: 150: result26[i*NAME_NUM+j]) ); 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: } return 0; } }
/* Display whether the 13 week average is greater */ printf( "[%d] ", (result13[i*NAME_NUM+j] >
printf("¥n");
/* Deallocate memory on the host */ free(result13); free(result26); free(kernel_src_str);
The Golden Cross Point can be determined by seeing where the displayed result changes from 0 to 1. One thing to note in this example code is that the copying of the result from device to host should not occur until the processing is finished. Otherwise, the memory copy (clEnqueueReadBuffer) can occur during the processing, which would contain garbage. Note in line 114 that "&event13" is passed back from the clEnqueueTask() command. This is known as an event object, which specifies whether this task has finished or not. This event object is seen again in line 128 to the clEnqueueReadBuffer() command, which specifies that the read command does not start execution until the computation of the moving average over 13 weeks is finished. This is done similarly for the moving average over 26 weeks, which is submitted in line 123 and written back in line 131. In summary, the Enqueue API functions in general: • Inputs event object(s) that specify what it must wait for until it can be executed • Ouputs an event object that can be used to tell another task in queue to wait The above two should be used to schedule the tasks in an efficient manner.
163
B01-02632560-294
The OpenCL Programming Book
Case Study
This chapter will look at more practical applications than the sample codes that you have seen so far. You should have the knowledge required to write practical applications in OpenCL after reading this chapter.
FFT (Fast Fourier Transform)
The first application we will look at is a program that will perform band-pass filtering on an image. We will start by first explaining the process known as a Fourier Transform, which is required to perform the image processing.
Fourier Transform
"Fourier Transform" is a process that takes in samples of data, and outputs its frequency content. Its general application can be summarized as follows. • Take in an audio signal and find its frequency content • Take in an image data and find its spatial frequency content The output of the Fourier Transform contains all of its input. A process known as the Inverse Fourier Transform can be used to retrieve the original signal. The Fourier Transform is a process commonly used in many fields. Many programs use this procedure which is required for an equalizer, filter, compressor, etc. The mathematical formula for the Fourier Transform process is shown below
The "i" is an imaginary number, and ω is the frequency in radians. As you can see from its definition, the Fourier Transform operates on continuous data. However, continuous data means it contains infinite number of points with infinite precision. For this processing to be practical, it must be able to process a data set that contains a finite number of elements. Therefore, a process known as the Discrete Fourier Transform (DFT) was developed to estimate the Fourier Transform, which operates on a finite data set. The mathematical formula 164
B01-02632560-294
The OpenCL Programming Book
is shown below.
This formula now allows processing of digital data with a finite number of samples. The problem with this method, however, is that its O(N^2). As the number of points is increased, the processing time grows by a power of 2.
Fast Fourier Transform
There exists an optimized implementation of the DFT, called the "Fast Fourier Transform (FFT)". Many different implementations of FFT exist, so we will concentrate on the most commonly used Cooley-Tukey FFT algorithm. An entire book can be dedicated to explaining the FFT algorithm, so we will only explain the minimal amount required to implement the program. The Cooley-Tukey algorithm takes advantage of the cyclical nature of the Fourier Transform, and solves the problem in O(N log N), by breaking up the DFT into smaller DFTs. The limitation with this algorithm is that the number of input samples must to be a power of 2. This limitation can be overcome by padding the input signal with zeros, or use in conjunction with another FFT algorithm that does not have this requirement. For simplicity, we will only use input signals whose length is a power of 2. The core computation in this FFT algorithm is what is known as the "Butterfly Operation". The operation is performed on a pair of data samples at a time, whose signal flow graph is shown in Figure 6.2 below. The operation got its name due to the fact that each segment of this flow graph looks like a butterfly.
Figure 6.2: Butterfly Operation
165
B01-02632560-294
The OpenCL Programming Book
The "W" seen in the signal flow graph is defined as below.
Looking at Figure 6.2, you may notice the indices of the input are in a seemingly random order. We will not get into details on why this is done in this text except that it is an optimization method, but note that what is known as "bit-reversal" is performed on the indices of the input. The input order in binary is (000, 100, 010, 110, 001, 101, 011, 111). Notice that if you reverse the bit ordering of (100), you get (001). So the new input indices are in numerical order, except that the bits are reversed.
2-D FFT
As the previous section shows, the basic FFT algorithm is to be performed on 1 dimensional data. In order to take the FFT of an image, an FFT is taken row-wise and column-wise. Note that we are not dealing with time any more, but with spatial location. When 2-D FFT is performed, the FFT is first taken for each row, transposed, and the FFT is again taken on this result. This is done for faster memory access, as the data is stored in row-major 166
4a. the edges will be blurred. If transposition is not performed. Figure 6.3: 2-D FFT (a) Original Image (b) The result of taking a 2-D FFT Bandpass Filtering and Inverse Fourier Transform As stated earlier.4: Edge Filter and Low-pass Filter (a) Edged Filter (b) Low-pass Filter 167 . Using this characteristic. If the high-frequency components are cut instead. the signal that has been transformed to the frequency domain via Fourier Transform can be transformed back using the Inverse Fourier Transform. Figure 6.B01-02632560-294 The OpenCL Programming Book form.4b. which can greatly decrease speed of performance as the size of the image increases.3(a). This is known as an "Edge Filter". which leaves the part of the image where a sudden change occurs. For example. and its result is shown in Figure 6.3(b) shows the result of taking a 2-D FFT of Figure 6. the low-frequency components can be cut. resulting in an image shown in Figure 6. Figure 6. it is possible to perform frequency-based filtering while in the frequency domain and transform back to the original domain. This is known as a "low-pass filter". interleaved accessing of memory occurs.
The rest of the procedure is the same. Figure 6. the same kernel can be used to perform either operation.B01-02632560-294 The OpenCL Programming Book The mathematical formula for Inverse Discrete Fourier Transform is shown below.5: Program flow-chart 168 . The only differences are: • Must be normalized by the number of samples • The term within the exp() is positive. Overall Program Flow-chart The overall program flow-chart is shown in Figure 6. Therefore. Note its similarity with the DFT formula.5 below.
B01-02632560-294
The OpenCL Programming Book
Each process is dependent on the previous process, so each of the steps must be followed in sequence. A kernel will be written for each of the processes in Figure 6.5.
Source Code Walkthrough
We will first show the entire source code for this program. List 6.1 is the kernel code, and List 6.2 is the host code.
List 6.1: Kernel Code
001: #define PI 3.14159265358979323846 002: #define PI_2 1.57079632679489661923 003: 004: __kernel void spinFact(__global float2* w, int n) 005: {
169
B01-02632560-294
The OpenCL Programming Book
006: 007: 008: 009: 010: } 011:
unsigned int i = get_global_id(0); float2 angle = (float2)(2*i*PI/(float)n,(2*i*PI/(float)n)+PI_2); w[i] = cos(angle);
012: __kernel void bitReverse(__global float2 *dst, __global float2 *src, int m, int n) 013: { 014: 015: 016: 017: 018: 019: 020: 021: 022: 023: 024: 025: 026: 027: } 028: 029: __kernel void norm(__global float2 *x, int n) 030: { 031: 032: 033: 034: 035: } 036: 037: __kernel void butterfly(__global float2 *x, __global float2* w, int m, int n, int iter, uint flag) 038: { 039: 040: 041: unsigned int gid = get_global_id(0); unsigned int nid = get_global_id(1); x[nid*n+gid] = x[nid*n+gid] / (float2)((float)n, (float)n); unsigned int gid = get_global_id(0); unsigned int nid = get_global_id(1); dst[nid*n+j] = src[nid*n+gid]; j >>= (32-m); unsigned int j = gid; j = (j & 0x55555555) << 1 | (j & 0xAAAAAAAA) >> 1; j = (j & 0x33333333) << 2 | (j & 0xCCCCCCCC) >> 2; j = (j & 0x0F0F0F0F) << 4 | (j & 0xF0F0F0F0) >> 4; j = (j & 0x00FF00FF) << 8 | (j & 0xFF00FF00) >> 8; j = (j & 0x0000FFFF) << 16 | (j & 0xFFFF0000) >> 16; unsigned int gid = get_global_id(0); unsigned int nid = get_global_id(1);
170
B01-02632560-294
The OpenCL Programming Book:
int butterflySize = 1 << (iter-1); int butterflyGrpDist = 1 << iter; int butterflyGrpNum = n >> iter; int butterflyGrpBase = (gid >> (iter-1))*(butterflyGrpDist); int butterflyGrpOffset = gid & (butterflySize-1); int a = nid * n + butterflyGrpBase + butterflyGrpOffset; int b = a + butterflySize; int l = butterflyGrpNum * butterflyGrpOffset; float2 xa, xb, xbxx, xbyy, wab, wayx, wbyx, resa, resb; xa = x[a]; xb = x[b]; xbxx = xb.xx; xbyy = xb.yy; wab = as_float2(as_uint2(w[l]) ^ (uint2)(0x0, flag)); wayx = as_float2(as_uint2(wab.yx) ^ (uint2)(0x80000000, 0x0)); wbyx = as_float2(as_uint2(wab.yx) ^ (uint2)(0x0, 0x80000000)); resa = xa + xbxx*wab + xbyy*wayx; resb = xa - xbxx*wab + xbyy*wbyx; x[a] = resa; x[b] = resb;
071: __kernel void transpose(__global float2 *dst, __global float2* src, int n) 072: { 073: 074: 075: 076: 077: unsigned int iid = ygid * n + xgid; unsigned int oid = xgid * n + ygid; unsigned int xgid = get_global_id(0); unsigned int ygid = get_global_id(1);
171
B01-02632560-294
The OpenCL Programming Book
078: 079: 080: } 081: 082: __kernel void highPassFilter(__global float2* image, int n, int radius) 083: { 084: 085: 086: 087: 088: 089: 090: 091: 092: 093: 094: 095: 096: 097: 098: 099: 100: 101: 102: 103: 104: 105: } image[ygid*n+xgid] = as_float2(as_int2(image[ygid*n+xgid]) & window); } if (dist2 < radius*radius) { window = (int2)(0L, 0L); } else { window = (int2)(-1L, -1L); int2 window; int2 diff = n_2 - gid; int2 diff2 = diff * diff; int dist2 = diff2.x + diff2.y; int2 gid = ((int2)(xgid, ygid) + n_2) & mask; int2 n_2 = (int2)(n>>1, n>>1); int2 mask = (int2)(n-1, n-1); unsigned int xgid = get_global_id(0); unsigned int ygid = get_global_id(1); dst[oid] = src[iid];
List 6.2: Host Code
001: #include <stdio.h> 002: #include <stdlib.h> 003: #include <math.h> 004: 005: #ifdef __APPLE__ 006: #include <OpenCL/opencl.h>
172
size_t* lws.14159265358979 014: 015: #define MAX_SOURCE_SIZE (0x100000) 016: 017: #define AMP(a. default: gws[0] = x. inverse = 1 173 . gws[1] = y. 021: cl_command_queue queue = NULL.h> 009: #endif 010: 011: #include "pgm. 023: 024: enum Mode { 025: 026: 027: }.h" 012: 013: #define PI 3. 020: cl_context context = NULL. lws[1] = 1.B01-02632560-294 The OpenCL Programming Book 007: #else 008: #include <CL/cl. lws[0] = 1. forward = 0. cl_int x. break. cl_int y) 030: { 031: 032: 033: 034: 035: 036: 037: 038: 039: 040: 041: 042: switch(y) { case 1: gws[0] = x. lws[0] = 1. gws[1] = 1. 028: 029: int setWorkSize(size_t* gws. 022: cl_program program = NULL. b) (sqrt((a)*(a)+(b)*(b))) 018: 019: cl_device_id device_id = NULL. lws[1] = 1.
cl_int iter. cl_kernel brev = NULL. norm = clCreateKernel(program. } break. size_t gws[2]. cl_kernel norm = NULL. cl_kernel bfly = NULL. case inverse:flag = 0x80000000. (void *)&m). 1. "norm". cl_event kernelDone. ret = clSetKernelArg(brev. 2. } switch (direction) { case forward:flag = 0x00000000.B01-02632560-294 The OpenCL Programming Book 043: 044: 045: 046: 047: } 048: return 0. size_t lws[2]. cl_int ret. bfly = clCreateKernel(program. &ret). 049: int fftCore(cl_mem dst. cl_mem src. "butterfly". cl_int m. sizeof(cl_mem). 174 . sizeof(cl_mem). (void *)&dst). break. (void *)&src). &ret). &ret). 0. break. ret = clSetKernelArg(brev. enum Mode direction): ret = clSetKernelArg(brev. "bitReverse". cl_mem spin. brev = clCreateKernel(program. cl_int n = 1<<m. cl_uint flag. sizeof(cl_int).
iter <= m. lws. n). /* Perform Butterfly Operations*/ setWorkSize(gws. return 0. n). sizeof(cl_int). (void *)&m). NULL. &kernelDone). 1. bfly. for (iter=1. 2. ret = clSetKernelArg(bfly. sizeof(cl_mem). (void *)&iter). 3. ret = clReleaseKernel(norm). sizeof(cl_uint). (void *)&flag). 2. sizeof(cl_mem). &kernelDone). sizeof(cl_int). lws. (void *)&dst). ret = clSetKernelArg(bfly. NULL. ret = clReleaseKernel(brev). sizeof(cl_int). NULL. lws. 2. 1. ret = clEnqueueNDRangeKernel(queue. norm. } ret = clReleaseKernel(bfly). lws. (void *)&n). n). 3. ret = clWaitForEvents(1. iter++){ ret = clSetKernelArg(bfly.B01-02632560-294 The OpenCL Programming Book: ret = clSetKernelArg(brev. /* Reverse bit ordering */ setWorkSize(gws. NULL. brev. ret = clSetKernelArg(bfly. ret = clWaitForEvents(1. (void *)&dst). NULL). gws. ret = clSetKernelArg(norm. 175 . 0. (void *)&spin). lws. 2. 0. 5. sizeof(cl_int). sizeof(cl_mem). ret = clSetKernelArg(bfly. ret = clEnqueueNDRangeKernel(queue. n. n/2. n. NULL. } if (direction == inverse) { setWorkSize(gws. 4. ret = clSetKernelArg(norm. (void *)&n). &kernelDone). &kernelDone). gws. (void *)&n). 0. 0. gws. sizeof(cl_int). 0. ret = clEnqueueNDRangeKernel(queue. ret = clSetKernelArg(bfly. lws. NULL.
cl_uint ret_num_devices. const char fileName[] = ". size_t source_size. cl_int n. pgm_t ipgm. cl_kernel hpfl = NULL. cl_mem xmobj = NULL. cl_uint ret_num_platforms. pgm_t opgm. cl_float2 *xm. cl_float2 *rm. cl_platform_id platform_id = NULL. 176 .cl". cl_mem wmobj = NULL. cl_kernel trns = NULL. j. cl_int m. char *source_str. size_t lws[2]. cl_int ret. FILE *fp.B01-02632560-294 The OpenCL Programming Book 113: } 114: 115: int main() 116: { 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: size_t gws[2]. cl_float2 *wm. cl_int i. cl_mem rmobj = NULL./fft. cl_kernel sfac = NULL.
xm = (cl_float2 *)malloc(n * n * sizeof(cl_float2)). &device_id. n = ipgm. } } /* Get platform/device */ ret = clGetPlatformIDs(1. source_size = fread(source_str. ((float*)xm)[(2*n*j)+2*i+1] = (float)0. &device_id. CL_DEVICE_TYPE_DEFAULT.buf[n*j+i].width. fclose( fp ). rm = (cl_float2 *)malloc(n * n * sizeof(cl_float2)). "r"). wm = (cl_float2 *)malloc(n / 2 * sizeof(cl_float2)).pgm"). /* Create Command queue */ 177 . /* Read image */ readPGM(&ipgm. i++) { for (j=0. m = (cl_int)(log((double)n)/log(2. j++) { ((float*)xm)[(2*n*j)+2*i+0] = (float)ipgm.0)). } source_str = (char *)malloc(MAX_SOURCE_SIZE). j < n. &platform_id.¥n"). &ret_num_devices). "Failed to load kernel. NULL. 1. i < n.B01-02632560-294 The OpenCL Programming Book 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: /* Load kernel source code */ fp = fopen(fileName. &ret_num_platforms). MAX_SOURCE_SIZE. if (!fp) { fprintf(stderr. /* Create OpenCL context */ context = clCreateContext(NULL. ret = clGetDeviceIDs( platform_id. fp). &ret). 1. 1. exit(1). for (i=0. NULL. "lena.
NULL. /* Build kernel program */ ret = clBuildProgram(program. &device_id. ret = clSetKernelArg(sfac. NULL. NULL). (void *)&wmobj). 0. NULL. wmobj = clCreateBuffer(context. sizeof(cl_mem). /* Transpose matrix */ 178 . lws. 188: &ret). CL_MEM_READ_WRITE. 1. n*n*sizeof(cl_float2). 0. forward). /* Create OpenCL Kernel */ sfac = clCreateKernel(program. CL_MEM_READ_WRITE. hpfl = clCreateKernel(program. 0. NULL. NULL). NULL. /* Transfer data to memory buffer */ ret = clEnqueueWriteBuffer(queue. 1). /* Create kernel program from source */ program = clCreateProgramWithSource(context. 1. &ret). rmobj = clCreateBuffer(context. "spinFact". m. "highPassFilter". gws. &ret). xm. NULL. 1. setWorkSize(gws. CL_MEM_READ_WRITE. &ret). sizeof(cl_int). wmobj. 0. /* Create Buffer Objects */ xmobj = clCreateBuffer(context. trns = clCreateKernel(program. lws. (void *)&n). ret = clEnqueueNDRangeKernel(queue.B01-02632560-294 The OpenCL Programming Book 184: 185: 186: 187: &ret). /* Create spin factor */ ret = clSetKernelArg(sfac. 189: &ret). 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: queue = clCreateCommandQueue(context. n*n*sizeof(cl_float2). 1. sfac. device_id. &ret). CL_TRUE. &ret). n*n*sizeof(cl_float2). 0. xmobj. NULL). (const char **)&source_str. /* Butterfly Operation */ fftCore(rmobj. "transpose". n/2. (const size_t *)&source_size. NULL. (n/2)*sizeof(cl_float2). xmobj. NULL.
2. 0. xmobj. NULL. lws. 0. sizeof(cl_int). NULL). lws. /* Transpose matrix */ ret = clSetKernelArg(trns. NULL. xm. n). m. lws. sizeof(cl_int). (void *)&n). wmobj. ret = clSetKernelArg(trns. inverse). NULL). CL_TRUE. (void *)&rmobj). gws. NULL. 1. 1. /* Apply high-pass filter */ cl_int radius = n/8. 2. rmobj. inverse). lws. ret = clSetKernelArg(hpfl. NULL). (void *)&rmobj). /* Inverse FFT */ /* Butterfly Operation */ fftCore(xmobj. ret = clSetKernelArg(trns. 2. 0. gws. NULL). (void *)&n). sizeof(cl_mem). 2. 0. n). sizeof(cl_int). /* */ 179 . lws. n*n*sizeof(cl_float2). 1. (void *)&xmobj). setWorkSize(gws. m. trns. /* Butterfly Operation */ fftCore(xmobj. NULL. (void *)&xmobj). trns. /* Read data from memory buffer */ ret = clEnqueueReadBuffer(queue. 0. (void *)&radius). n. sizeof(cl_mem). sizeof(cl_mem). n. 2. (void *)&rmobj). xmobj. hpfl.B01-02632560-294 The OpenCL Programming Book 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: ret = clSetKernelArg(trns. ret = clSetKernelArg(hpfl. setWorkSize(gws. ret = clSetKernelArg(hpfl. ret = clEnqueueNDRangeKernel(queue. 0. m. /* Butterfly Operation */ fftCore(rmobj. 0. ret = clEnqueueNDRangeKernel(queue. rmobj. NULL. gws. NULL. sizeof(cl_mem). wmobj. setWorkSize(gws. sizeof(cl_mem). forward). ret = clEnqueueNDRangeKernel(queue. lws. n). wmobj. 0. n. NULL. ret = clSetKernelArg(trns.
free(xm). free(rm). ret = clReleaseMemObject(xmobj). ret = clReleaseMemObject(wmobj). opgm. ret = clReleaseCommandQueue(queue). ret = clReleaseProgram(program). "output. destroyPGM(&opgm).pgm"). ret = clFinish(queue).B01-02632560-294 The OpenCL Programming Book 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: float* ampd. } } opgm. free(source_str). ret = clReleaseMemObject(rmobj). i < n. ampd). /* Write out image */ writePGM(&opgm. destroyPGM(&ipgm). free(ampd). i++) { for (j=0. ret = clReleaseKernel(trns).width = n. for (i=0.height = n. j++) { ampd[n*((i))+((j))] = (AMP(((float*)xm)[(2*n*i)+2*j]. normalizeF2PGM(&opgm. ret = clReleaseKernel(sfac). ret = clReleaseKernel(hpfl). ret = clReleaseContext(context). free(wm). j < n. ampd = (float*)malloc(n*n*sizeof(float)). 180 . /* Finalizations*/ ret = clFlush(queue). ((float*)xm)[(2*n*i)+2*j+1])).
3 is used to pre-compute the value of the spin factor "w". List 6. which is basically the real and imaginary components on the unit circle using cos() and -sin(). 007: 008: float2 angle = (float2)(2*i*PI/(float)n. such as the GPU. int n) 005: { 006: unsigned int i = get_global_id(0). which gets repeatedly used in the butterfly operation.B01-02632560-294 The OpenCL Programming Book 285: 286: 287: } return 0. The "w" is computed for radian angles that are multiples of (2π/n). which stores values to be used repeatedly on the memory.3: Create Spin Factor 004: __kernel void spinFact(__global float2* w. Note the shift by PI/2 in line 8 allows the cosine function to compute -sin(). Figure 6. On some devices. it may prove to 181 . 010: } The code in List 6.(2*i*PI/(float)n)+PI_2).6: Spin factor for n=8 The pre-computing of the values for "w" creates what is known as a "lookup table". We will start by taking a look at each kernel. This is done to utilize the SIMD unit on the OpenCL device if it has one. 009: w[i] = cos(angle).
015: unsigned int nid = get_global_id(1). 015: unsigned int nid = get_global_id(1). 023: 024: j >>= (32-m). The indices are correctly shifted in line 24.5. int n) 013: { 014: unsigned int gid = get_global_id(0).B01-02632560-294 The OpenCL Programming Book be faster if the same operation is performed each time. 025: 026: dst[nid*n+j] = src[nid*n+gid]. List 6. int n) 013: { 014: unsigned int gid = get_global_id(0). Also. 016: 017: unsigned int j = gid.5: Bit reversing (Using synchronization) 012: __kernel void bitReverse(__global float2 *x. 021: j = (j & 0x00FF00FF) << 8 | (j & 0xFF00FF00) >> 8. 027: } List 6. 022: j = (j & 0x0000FFFF) << 16 | (j & 0xFFFF0000) >> 16. int m.4: Bit reversing 012: __kernel void bitReverse(__global float2 *dst. where each work item stores the output locally until all work items are finished. Lines 18~22 performs the bit reversing of the inputs.4 shows the kernel code for reordering the input data such that it is in the order of the bit-reversed index. An alternative solution is shown in List 6. This is done since the coherence of the data cannot be guaranteed if the input gets overwritten each time after processing. 182 . These types of functions are known as an out-of-place function. 019: j = (j & 0x33333333) << 2 | (j & 0xCCCCCCCC) >> 2. 020: j = (j & 0x0F0F0F0F) << 4 | (j & 0xF0F0F0F0) >> 4. note that a separate memory space must be allocated for the output on the global memory. as the max index would otherwise be 2^32-1. int m. at which point the locally stored data is written to the input address space. as it may be more expensive to access the memory. 018: j = (j & 0x55555555) << 1 | (j & 0xAAAAAAAA) >> 1. __global float2 *src. List 6.
6 should be self-explanatory. List 6. It basically just dives the input by the value of "n". 031: } However. It may be supported in the future. 023: 024: j >>= (32-m). Shifting of a float value will result in unwanted results. can potentially decrease performance. but division by shifting is only possible for integer types. 027: 028: SYNC_ALL_THREAD /* Synchronize all work-items */ 029: 030: x[nid*n+j] = val. especially when processing large amounts of data. 025: 026: float2 val = x[nid*n+gid]. the version on List 6. 033: 034: x[nid*n+gid] = x[nid*n+gid] / (float2)((float)n. but depending on the device. these types of synchronization. If there is enough space on the device.4 should be used. 183 . 022: j = (j & 0x0000FFFF) << 16 | (j & 0xFFFF0000) >> 16. 019: j = (j & 0x33333333) << 2 | (j & 0xCCCCCCCC) >> 2. 020: j = (j & 0x0F0F0F0F) << 4 | (j & 0xF0F0F0F0) >> 4. you may be tempted to use shifting.6: Normalizing by the number of samples 029: __kernel void norm(__global float2 *x. 035: } The code in List 6. int n) 030: { 031: unsigned int gid = get_global_id(0). (float)n). 032: unsigned int nid = get_global_id(1). 018: j = (j & 0x55555555) << 1 | (j & 0xAAAAAAAA) >> 1. OpenCL does not currently require the synchronization capability in its specification. 021: j = (j & 0x00FF00FF) << 8 | (j & 0xFF00FF00) >> 8. Since the value of "n" is limited to a power of 2.B01-02632560-294 The OpenCL Programming Book 016: 017: unsigned int j = gid. The operation is performed on a float2 type.
wab. 043: int butterflyGrpDist = 1 << iter. 065: resb = xa .xbxx*wab + xbyy*wbyx. flag)). 062: wbyx = as_float2(as_uint2(wab. 046: int butterflyGrpOffset = gid & (butterflySize-1). 061: wayx = as_float2(as_uint2(wab. xbxx. 047: 048: int a = nid * n + butterflyGrpBase + butterflyGrpOffset.xx. 0x80000000)). resb. 040: unsigned int nid = get_global_id(1). 063: 064: resa = xa + xbxx*wab + xbyy*wayx. 052: 053: float2 xa.yx) ^ (uint2)(0x80000000. 041: 042: int butterflySize = 1 << (iter-1). xbyy. 054: 055: xa = x[a]. is shown in 184 . wayx. 050: 051: int l = butterflyGrpNum * butterflyGrpOffset. 069: } The kernel for the butterfly operation. uint flag) 038: { 039: unsigned int gid = get_global_id(0).yy. 049: int b = a + butterflySize. xb.7: Butterfly operation 037: __kernel void butterfly(__global float2 *x. int iter. 045: int butterflyGrpBase = (gid >> (iter-1))*(butterflyGrpDist). __global float2* w. 066: 067: x[a] = resa. 0x0)). 068: x[b] = resb.B01-02632560-294 The OpenCL Programming Book List 6. resa. 057: xbxx = xb. 056: xb = x[b]. int m. wbyx. 058: xbyy = xb. 059: 060: wab = as_float2(as_uint2(w[l]) ^ (uint2)(0x0. which performs the core of the FFT algorithm. 044: int butterflyGrpNum = n >> iter. int n.yx) ^ (uint2)(0x0.
Refer back to the signal flow graph for the butterfly operation in Figure 6. we need to know how the butterfly operation is grouped.B01-02632560-294 The OpenCL Programming Book List 6. This is stored in the variable butterflyGrpDistance. The differences of the indices between the groups are required as well. Looking at the signal flow graph. Now the indices to perform the butterfly operation and the spin factor can be found. In the first iteration. Lines 60 ~ 62 takes the sign of the spin factor into account to take care of the computation for the real and imaginary components. which can be derived from the "gid". butterflyGrpBase = (gid / butterflySize) * butterflyGrpDistance). as well 185 .2. The intermediate values required in mapping the "gid" to the input and output indices are computed in lines 42-46. we need to determine the indices to read from and to write to. We will now go into the actual calculation. Therefore. the required inputs are the two input data and the spin factor. First. since we are assuming the value of n to be a power of 2. Each work item performs one butterfly operation for a pair of inputs. the number of groups is the same as the number of butterfly operation to perform. it is split up into 2 groups. Next. The butterflyGrpBase variable contains the index to the first butterfly operation within the group. The butterflyGropOffset is the offset within the group. Next.7 above. This value is stored in the variable butterflyGrpNum. butterflyGrpOffset = gid % butterflySize. we can replace the division and the mod operation with bit shifts. The "butterflySize" is 1 for the first iteration. Lines 55 ~ 65 are the core of the butterfly operation. (n * n)/2 work items are required. but in the 2nd iteration. the variable "butterflySize" represents the difference in the indices to the data for the butterfly operation to be performed on. we see that the crossed signal paths occur within independent groups. For our FFT implementation. These are determined using the following formulas. and this value is doubled for each iteration. As the graph shows.
B01-02632560-294 The OpenCL Programming Book as the FFT and IFFT. int n.8 shows a basic implementation of the matrix transpose algorithm. int n) 072: { 073: unsigned int xgid = get_global_id(0). 075: 076: unsigned int iid = ygid * n + xgid. int radius) 083: { 084: unsigned int xgid = get_global_id(0).x + diff2. 088: int2 mask = (int2)(n-1. List 6. and Lines 67 ~ 68 stores the processed data.y. ygid) + n_2) & mask. n>>1). n-1). 091: 092: int2 diff = n_2 . 093: int2 diff2 = diff * diff. 077: unsigned int oid = xgid * n + ygid. 095: 096: int2 window.gid. 078: 079: dst[oid] = src[iid]. 080: } List 6.9: Filtering 082: __kernel void highPassFilter(__global float2* image. 097: 186 . List 6. __global float2* src. but this process can be speed up significantly by using local memory and blocking. 094: int dist2 = diff2. 085: unsigned int ygid = get_global_id(1).8: Matrix Transpose 071: __kernel void transpose(__global float2 *dst. We will not go into optimization of this algorithm. Lines 64 ~ 65 are the actual operations. 089: 090: int2 gid = ((int2)(xgid. 086: 087: int2 n_2 = (int2)(n>>1. 074: unsigned int ygid = get_global_id(1).
Most of what is being done is the same as for the OpenCL programs that we have seen so far. /* Perform butterfly operations */ setWorkSize(gws. (void *)&iter). 105: } List 6. a high pass filter extracts the edges. The main differences are: • Multiple kernels are implemented • Multiple memory objects are used. 094: 095: 096: 097: 098: &kernelDone). lws. The opposite can be performed to create a low pass filter. NULL. -1L). sizeof(cl_int). 187 . Next. for (iter=1. 102: } 103: 104: image[ygid*n+xgid] = as_float2(as_int2(image[ygid*n+xgid]) & window). 0. n/2. 0L). A high pass filter can be created by cutting the frequency within a specified radius that includes these DC components. 100: } else { 101: window = (int2)(-1L. the filter passes high frequencies and gets rid of the lower frequencies. As the kernel name suggests. the clSetKernelArg() only need to be changed for when an argument value changes from the previous time the kernel is called.B01-02632560-294 The OpenCL Programming Book 098: if (dist2 < radius*radius) { 099: window = (int2)(0L. lws. The spatial frequency obtained from the 2-D FFT shows the DC (direct current) component on the 4 edges of the XY coordinate system. In general. iter++){ ret = clSetKernelArg(bfly. requiring appropriate data flow construction Note that when a kernel is called repeatedly.9 is a kernel that filters an image based on frequency. gws. NULL. consider the butterfly operations being called in line 94 on the host side. and a low pass filter blurs the image. &kernelDone). bfly. 2. iter <= m. 4. 099: 100: } ret = clWaitForEvents(1. n). we will go over the host program. For example. ret = clEnqueueNDRangeKernel(queue.
B01-02632560-294 The OpenCL Programming Book This butterfly operation kernel is executed log_2(n) times. a setWorkSize() function is implemented in this program. In this program. cl_mem spin. it would be wise to use as few memory objects as possible. For example. These procedures are all grouped into one function fftCore(). cl_int x. The in-place kernel uses the same memory object for both input and output. the number work items. cl_int m. at least 2 additional memory objects are required. The problem with these types of kernel is that it would require too much memory space on the device. namely the bit reversal and the butterfly operation. Since an out-of-place operation such as the matrix transposition exist. 029: int setWorkSize(size_t* gws. 049: int fftCore(cl_mem dst. When this is called. The kernels in this program is called using clEnqueueNDRangeKernel() to operate on the data in a data parallel manner. Therefore. where the output data is written over the address space of the input data. The kernel must have its iteration number passed in as an argument. when calling the out-of-place transpose operation which is called twice. To reduce careless errors and to make the code more readable. The kernel uses this value to compute which data to perform the butterfly operation on. a memory object is required to store the pre-computed values of the spin factors. for both FFT and IFFT. the pointer to the memory object must be reversed the second time around. cl_int y) The program contains a set of procedures that are repeated numerous times. the data transfers between kernels occur via the memory objects. In fact. and that a data transfer must occur between memory objects. whose values differ depending on the kernel used. For this program. only these 3 memory objects are required for this program to run without errors due to race conditions. must be set beforehand. enum Mode direction) 188 . the arguments to the kernel must be appropriately set using clSetKernelArg() for each call to the kernel. size_t* lws. cl_mem src. To do this. The types of kernels used can be classified to either in-place kernel or out-of-place kernel based on the data flow. The out-of-place kernel uses separate memory objects for input and output.
We will add a new file. const char*. and the FFT direction.10. filename). output. The data structure is quite simple and intuitive to use. The full pgm. This file will define numerous functions and structs to be used in our program. the sample number normalized by the log of 2. and the spin factor. The format used for the image is PGM. int height.h 001: #ifndef _PGM_H_ 002: #define _PGM_H_ 003: 004: #include <math.h". 015: typedef struct _pgm_t { 016: 017: 018: int width.h> 005: #include <string. writePGM(pgm_t* pgm.h file is shown below in List 6.10: pgm. a conversion would need to be performed to represent the pixel information in 8 bits.B01-02632560-294 The OpenCL Programming Book This function takes memory objects for the input. normalizePGM(pgm_t* pgm. called "pgm. const char* filename). we will briefly explain the outputting of the processed data to an image. unsigned char *buf. 019: } pgm_t.h> 006: 189 . The width and the height gets the size of the image. Since each pixel of the PGM is stored as unsigned char. readPGM(pgm_t* pgm. This function can be used for 1-D FFT if the arguments are appropriately set. First is the pgm_t struct. and buf gets the image data. double* data). List 6. Lastly. This can read in or written to a file using the following functions. which is a gray-scale format that requires 8 bits for each pixel.
long begin. 019: } pgm_t. } FILE* fp. "rb"))==NULL) { fprintf(stderr. del. 190 . fseek(fp. unsigned char *buf. "Failed to open file¥n"). saveptr) 011: #else 012: #define STRTOK_R(ptr. del.B01-02632560-294 The OpenCL Programming Book 007: #define PGM_MAGIC "P5" 008: 009: #ifdef _WIN32 010: #define STRTOK_R(ptr. unsigned char *dot. begin = ftell(fp). char *token. char del[] = " ¥t¥n". pixs. end. int filesize. return -1. 0. w. saveptr) 013: #endif 014: 015: typedef struct _pgm_t { 016: 017: 018: 020: 021: int readPGM(pgm_t* pgm. h. if ((fp = fopen(filename. const char* filename) 022: { 023: 024: 025: 026: 027: 028: 029: 030: 031: 032: 033: 034: 035: 036: 037: 038: 039: 040: 041: 042: fseek(fp. saveptr) strtok_r(ptr. SEEK_END). int height. int width. int i. *pc. 0. *saveptr. del. saveptr) strtok_s(ptr. SEEK_SET). size_t bufsize. char *buf. luma. del.
del. filesize * sizeof(char). i++. &pc. dot++) { *dot = *token++. } 191 . } w = strtoul(token. token = (char *)STRTOK_R(NULL. bufsize = fread(buf. &saveptr). 2) != 0) { return -1. fseek(fp. token = (char *)STRTOK_R(NULL.B01-02632560-294 The OpenCL Programming Book: end = ftell(fp). luma = strtoul(token. token = (char *)STRTOK_R(buf. for (i=0. } token = (char *)STRTOK_R(NULL. del. del. 0. 10). token = (char *)STRTOK_R(NULL. &pc. filesize = (int)(end . if (token[0] == '#' ) { token = (char *)STRTOK_R(NULL. del. i< pixs. PGM_MAGIC. 1. buf = (char*)malloc(filesize * sizeof(char)). fp).begin). pixs = w * h. &saveptr). 10). token = pc + 1. del. if (strncmp(token. h = strtoul(token. &saveptr). &saveptr). &saveptr). dot = pgm->buf. SEEK_SET). 10). &saveptr). fclose(fp). &pc. "¥n". pgm->buf = (unsigned char *)malloc(pixs * sizeof(unsigned char)).
return -1. fprintf (fp. fclose(fp). w. PGM_MAGIC. h). pgm->height = h. double* x) return 0. pixs. w. pixs = w * h. i<pixs. dot = pgm->buf. int i. "Failed to open file¥n"). pgm->width = w. i++. dot++) { putc((unsigned char)*dot.B01-02632560-294 The OpenCL Programming Book 079: 080: 081: 082: 083: 084: } 085: 086: int writePGM(pgm_t* pgm. "wb+")) ==NULL) { fprintf(stderr. return 0. FILE* fp. } for (i=0. h = pgm->height. unsigned char* dot. h. "%s¥n%d %d¥n255¥n". 192 . fp). const char* filename) 087: { 088: 089: 090: 091: 092: 093: 094: 095: 096: 097: 098: 099: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: } 113: 114: int normalizeD2PGM(pgm_t* pgm. w = pgm->width. } if ((fp = fopen(filename.
i++) { for (j=0. h = pgm->height. float* x) 147: { 148: 149: 150: w = pgm->width. h. j++) { if (max < x[i*w+j]) max = x[i*w+j]. int i. i < h. j++) { if((max-min)!=0) pgm->buf[i*w+j] = (unsigned char)(255*(x[i*w+j]-min)/(max-min)). i < h.B01-02632560-294 The OpenCL Programming Book 115: { 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: } 145: 146: int normalizeF2PGM(pgm_t* pgm. j. i++) { for (j=0. j < w. j < w. double max = 0. w. j. w. } } double min = 0. w = pgm->width. 193 . pgm->buf = (unsigned char*)malloc(w * h * sizeof(unsigned char)). return 0. for (i=0. if (min > x[i*w+j]) min = x[i*w+j]. } } else pgm->buf[i*w+j]= 0. int i. for (i=0. h.
i++) { for (j=0. } } return 0. else pgm->buf[i*w+j]= 0.B01-02632560-294 The OpenCL Programming Book 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: } 177: h = pgm->height. float min = 0. i < h. j++) { if((max-min)!=0) pgm->buf[i*w+j] = (unsigned char)(255*(x[i*w+j]-min)/(max-min)). j++) { if (max < x[i*w+j]) max = x[i*w+j]. pgm->buf = (unsigned char*)malloc(w * h * sizeof(unsigned char)). i++) { for (j=0. 178: int destroyPGM(pgm_t* pgm) 179: { 180: 181: 182: 183: 184: 185: } 186: return 0. for (i=0. if (min > x[i*w+j]) min = x[i*w+j]. j < w. } } for (i=0. float max = 0. 194 . j < w. i < h. } if (pgm->buf) { free(pgm->buf).
We will now show how this can be done within the OpenCL framework for portability. The speed of execution is dependent on the device.B01-02632560-294 The OpenCL Programming Book 187: #endif /* _PGM_H_ */ When all the sources are compiled and executed on an image. The edges in the original picture become white. Time measurement can be done in OpenCL. as well as the type of parallelism used. in order to get the maximum performance. 195 . but this only guarantee that program can be executed. In order to tune a program.11.7(b).7(a) becomes the picture shown in Figure 6. which is triggered by event objects associated with certain clEnqueue-type commands. This code is shown in List 6. the execution time must be measured. List 6. a device and parallelism dependent tuning must be performed.11: Time measurement using event objects cl_context context. Figure 6. since it would otherwise be very difficult to see the result.7: Edge Detection (a) Original Image (b) Edge Detection Measuring Execution Time OpenCL is an abstraction layer that allows the same code to be executed on different platforms. the picture shown in Figure 6. Therefore. while everything else becomes black.
List 6. The first argument gets the number of events to wait for. clGetEventProfilingInfo(event.12: Event synchronization ret = clEnqueueNDRangeKernel(queue. clGetEventProfilingInfo() is used to get the start and end times.B01-02632560-294 The OpenCL Programming Book cl_command_queue queue. &event). The clWaitForEvents keeps the next line of the code to be executed until the specified events in the event list has finished its execution. CL_PROFILING_COMMAND_START. gws. lws. CL_PROFILING_COMMAND_START. 0. NULL). This can be done by using the clWaitForEvents() as in List 6.5f [ms]¥n". m. One thing to note when getting the end time is that the kernel queuing is performed asynchronously. NULL. We need to make sure. &ret). &start.11 shows the code required to measure execution time. … queue = clCreateCommandQueue(context. Command queue is created with the "CL_QUEUE_PROFILING_ENABLE" option 2. that the kernel has actually finished executing before we get the end time. NULL. MEM_SIZE. cl_event event. kernel. CL_PROFILING_COMMAND_END. clWaitForEvents(1. sizeof(cl_ulong). mobj. (end . sizeof(cl_ulong). and the 2nd argument gets the pointer to the event list. The code on List 6. cl_ulong start. in this case. CL_QUEUE_PROFILING_ENABLE.12. sizeof(cl_ulong). printf(" memory buffer write: %10. cl_ulong end. sizeof(cl_ulong). CL_TRUE.start)/1000000.0). device_id. &end. &event). clGetEventProfilingInfo(event. CL_PROFILING_COMMAND_END. &event). Kernel and memory object queuing is associated with events 3. &start. 0. 2. The code can be summarized as follows: 1. NULL). NULL). NULL). … clGetEventProfilingInfo(event. NULL. &end. clGetEventProfilingInfo(event. … ret = clEnqueueWriteBuffer(queue. 0. 196 .
CL_DEVICE_MAX_WORK_ITEM_SIZES. 512 work items can be split up into 2 work groups each having 256 work items. What values are allowed for the number of work groups and work items? 2. clGetDeviceInfo(device_id. size_t work_group_size.13: Get maximum values for the number of work groups and work items cl_uint work_item_dim. &work_group_size. NULL). List 6.1. clGetDeviceInfo(device_id. What are the optimal values to use for the number of work groups and work items? The first question can be answered using the clGetDeviceInfo() introduced in Section 5. or 512 work groups each having 1 work item. NULL).1]. The first clGetDeviceInfo() gets the maximum number of dimensions allowed for the work item. This raises the following questions: 1. This section focuses on what these values should be set to for optimal performance. The smallest value is [1. clGetDeviceInfo(device_id. sizeof(cl_uint). NULL). CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS.B01-02632560-294 The OpenCL Programming Book You should now be able to measure execution times using OpenCL. 197 . The code is shown in List 6. CL_DEVICE_MAX_WORK_GROUP_SIZE. Index Parameter Tuning Recall that the number of work items and work groups had to be specified when executing data parallel kernels.13 below. size_t work_item_sizes[3]. work_item_sizes. There is quite a bit of freedom when setting these values.1. This returns either 1. 2 or 3. For example. sizeof(work_item_sizes). &work_item_dim. The second clGetDeviceInfo() gets the maximum values that can be used for each dimensions of the work item. sizeof(size_t).
Running the above code using NVIDIA OpenCL would generate the results shown below. For example.1} Yet another combination is: gws[] = {512.16. the number of work items and the work groups must be set before executing a kernel.1} The following is also possible: gws[] = {512. gws[] = {512.1} lws[] = {256.512.1} The following example seems to not have any problems at a glance.32. lws=local work-item size).1} lws[] = {32. since the size of the work-group size exceeds that of the allowed size (32*32 = 1024 > 512). and the work item ID within the work group. but would result in an error. The real problem is figuring out the optimal 198 .1} lws[] = {1. gws[] = {512.1} lws[] = {16.1.1.B01-02632560-294 The OpenCL Programming Book The third clGetDeviceInfo() gets the maximum work item size that can be set for each work group. The smallest value for this is 1. the following combination is possible. if the work item is 512 x 512. (gws=global work-item size.512. Max work-item dimensions : 3 Max work-item sizes Max work-group size : 512 512 64 : 512 As mentioned before.512. The global work item index and the local work item index each correspond to the work item ID of all the submitted jobs.1} Hopefully you have found the above to be intuitive.512.
B01-02632560-294 The OpenCL Programming Book combination to use. as shown in List 6. and see how it affects the processing time. The work-item corresponds to the processing element.1: Execution time when varying lws (units in ms) Process membuf write 1 0.53 32 0. In NVIDIA GPUs. A processing element corresponds to what is called CUDA cores. 16.53 . At this point. sizeof(cl_uint). the OpenCL architecture assumes the device to contain compute unit(s). We will now go back to the subject of FFT.36 199 64 0. and 512 local work-group size (Table 6. &compute_unit.14: Find the number of compute units cl_uint comput_unit = 0. As discussed in Chapter 2. 256. 64.54 16 0. This implies that the knowledge of the number of compute units and processing elements is required in deducing the optimal combination to use for the local work group size. In other words. ret = clGetDeviceInfo(device_id. 32. • All compute units can be used if the number of work groups is greater than 30. we need to look at the hardware architecture of the actual device.52 128 0. These can be found using clGetDeviceInfo(). 128. The following generations can be made from the above information: • Processor elements can be used efficiently if the number of work items within a work group is a multiple of 32. a work group gets executed on a compute unit. Each compute unit contains 8 processing elements.1). List 6. a compute unit corresponds to what is known as Streaming Multi-processor (SM). Execution time was measured for 1.14. which is made up of several processing elements. We will vary the number of work-items per work group (local work-group size).53 256 0. CL_DEVICE_MAX_COMPUTE_UNITS. and the work group corresponds to the compute unit. GT 200-series GPUs such as Tesla C1060 and GTX285 contain 30 compute units. NULL). we will use a 512 x 512 image. and a work-item gets executed on a processing element.54 512 0. but 32 processes can logically be performed in parallel. Table 6. For simplicity.
Note that the techniques used so far are rather basic.75 2.09 1.53 0. This algorithm was developed by a professor at the Hiroshima University in Japan.57 0.58 As you can see.51 0.54 37.51 3. but when combined wisely. • Long period • Efficient use of memory • High performance 200 .87 0.20 1.06 0.47 3.07 0.09 1. For example.12 0.01 0.49 3.10 0. which lead us to assume a similar auto-parallelization algorithms are implemented to be used within the OpenCL framework.58 0.83 1. a complex algorithm like the FFT can be implemented to be run efficiently over an OpenCL device. MT has the following advantages. We can only assume that the parallelization is performed by the framework itself. Mac OS X Snow Leopard comes with an auto-parallelization framework called the "Grand Central Dispatch". The FFT algorithm is a textbook model of a data parallel algorithm. We performed parameter tuning specifically for the NVIDIA GPU.01 0. This is due to the fact that 32 processes can logically be performed in parallel for each compute unit.02 0.01 6. Apple's OpenCL for multi-core CPUs only allows 1 work-item for each work group.07 0.12 1.01 0. but the optimal value would vary depending on the architecture of the device. We will now conclude our case study of the OpenCL implementation of FFT.06 0. Mersenne Twister This case study will use Mersenne Twister (MT) to generate pseudorandom numbers.50 3.61 0.96 0.41 0.49 0. At the time of this writing (December 2009).01 0.56 0.07 0. since the NVIDIA GPU hardware performs the thread switching.01 0.60 3.10 0.10 0.86 2.60 0.06 0. The implemented code should work over any platform where an OpenCL framework exists.42 0.95 0. the optimal performance occurs when the local work-group size is a multiple of 32. The performance does not suffer significantly when the local work-group size is increased.57 0.B01-02632560-294 The OpenCL Programming Book spinFactor bitReverse butterfly normalize transpose highPassFilter membuf read 0.01 0.88 0.62 0.47 2.
8. • Parallelize the state change operation The state is made up of a series of 32-bit words. each processing of the word can be parallelized. In this manner. By going through a process called "tempering" on this state. and depending 201 . The initial state then undergoes a set of operations. A block diagram of the steps is shown in Figure 6. more random numbers are generated. MT starts out with an initial state made up of an array of bits. Since the next state generation is done by operating on one 32-bit word at a time. However. an array of random numbers is generated.8. the following 2 methods come to mind.8: MT processing Studying the diagram in Figure 6. Parallelizing MT A full understanding of the MT algorithm requires knowledge of advanced algebra. which creates another state. An array of random numbers is again generated from this state. which gets in the way of parallel processing. we see a dependency of the states.B01-02632560-294 The OpenCL Programming Book • Good distribution properties We will now implement this algorithm using OpenCL. but the actual program itself is comprised of bit operations and memory accesses. To get around this problem. Figure 6. since the processing on each word does not require many instructions.
32 sets of parameters are generated. The sample code in List 6. n = 32. it may not be enough to take advantage of the 100s of cores on GPUs. Also.%d. would not be the same as that generated sequentially from one state.15 below shows how the get_mt_parameters() function in the "dc" library can be used. This type of processing would benefit more from using a SIMD unit that has low synchronization cost and designed to run few processes in parallel. 006: mt_struct **mts.%d. 009: for (i=0.h> 002: #include "dc. The generated random number. since the number of processes that can be parallelized is dependent on the number of words that make up the state.%d}¥n". and process these in parallel Since the dependency is between each state.%d.B01-02632560-294 The OpenCL Programming Book on the cost of synchronization. 202 . Dynamic Creator (dc) NVIDIA's CUDA SDK sample contains a method called the Dynamic Creator (dc) which can be used to generate random numbers over multiple devices [18]. performance may potentially suffer from parallelization.%d. in order to run OpenCL on the GPU. however.%d. 007: init_dc(4172).%d. 240 MT can be processed in parallel. i++) { 010: printf("{%d. "dc" is a library that dynamically creates Mersenne Twisters parameters.15: Using "dc" to generate Mersenne Twisters parameters 001: #include <stdio.%d. In this code. We will use the latter method. • Create numerous initial states. generating an initial state for each processing element will allow for parallel execution of the MT algorithm. i < n.h" 003: int main(int argc. This section will show how to generate random numbers in OpenCL using "dc". but this can be changed by using a different value for the variable "n".n).%d.521. for example.%d.%d.%d. If the code is executed on Tesla C1060. List 6. char **argv) 004: { 005: int i.%d. 008: mts = get_mt_parameters(32.
the value of PI can be computed. the proportion of the area inside the circle is equal to PI / 4.mts[i]->nn. and using the fact that the radius of the circle equals the edge of the square.mts[i]->maskC). Now points are chosen at random inside the square. 012: mts[i]->lmask. Assume that a quarter of a circle is contained in a square. which can be used to figure out if that point is within the quarter of a circle.mts[i]->wmask.9). 016: } OpenCL MT We will now implement MT in OpenCL. Figure 6.mts[i]->shiftB. We will use the Mersenne Twister algorithm to generate random numbers. solving for PI.mts[i]->shift0. Since the area of the quarter of a circle is PI * R^2 / 4.9: Computing PI using Monte Carlo 203 . we would get PI = 4 * (proportion).mts[i]->shift1. then use these numbers to compute the value of PI using the Monte Carlo method. 013: mts[i]->maskB.B01-02632560-294 The OpenCL Programming Book 011: mts[i]->aaa. The Monte Carlo method can be used as follows. and the area of the square is R^2. Using the proportion of hit versus the number of points.mts[i]->mm.mts[i]->shiftC.mts[i]->ww. 014: } 015: return 0.mts[i]->umask.mts[i]->rr. When this is equated to the proportion found using the Monte Carlo method. such that the radius of the circle and the edge of the square are equivalent (Figure 6.
1. uint aaa.lmask.17 shows the host code for this program. lll = mts->lmask. uint maskB. shift1. k++) { x = (st[k]&uuu)|(st[k+1]&lll). uint uuu = mts->umask. uint aa = mts->aaa. uint wmask. int k. List 6.nn.16: Kernel Code 001: typedef struct mt_struct_s { 002: 003: 004: 005: 006: 008: 009: /* Initialize state using a seed */ 010: static void sgenrand_mt(uint seed. for (k=0. i < mts->nn. shiftC. shiftB.16 shows the kernel code and List 6. which we will use when we get to the optimization phase.B01-02632560-294 The OpenCL Programming Book List 6. maskC. st[k] = st[k+m] ^ (x>>1) ^ (x&1U ? aa : 0U).umask. uint *state) { 011: 012: 013: 014: 015: 016: 017: 018: } 019: 020: /* Update state */ 021: static void update_state(__global const mt_struct *mts.rr. 204 . x.lim. for (i=0. int mm. seed = (1812433253 * (seed ^ (seed >> 30))) + i + 1. int shift0. i++) state[i] &= mts->wmask. The host program includes the commands required to measure the execution time. __global const mt_struct *mts. i < mts->nn. 007: } mt_struct.m. } for (i=0. k < lim. lim = n .ww. uint *st) { 022: 023: 024: 025: 026: 027: 028: 029: 030: 031: } lim = n . int i. int n = mts->nn. i++) { state[i] = seed. m = mts->mm.
n.__global mt_struct *mts. /* mts for this item */ out += gid * num_rand. mts. for (j=0. k++) { x = (st[k]&uuu)|(st[k+1]&lll). x ^= (x << mts->shiftB) & mts->maskB. out[i*nn + j] = x. state). st[n-1] = st[m-1] ^ (x>>1) ^ (x&1U ? aa : 0U). update_state(mts. j++) { /* Generate random numbers */ uint x = state[j]. st[k] = st[k+m-n] ^ (x>>1) ^ (x&1U ? aa : 0U). /* Output buffer for this item */ sgenrand_mt(0x33ff*gid. x ^= x >> mts->shift0. mts. x ^= (x << mts->shiftC) & mts->maskC. uint *state. 205 . x ^= x >> mts->shift1. 040: static inline void gen(__global uint *out. for (i=0. (uint*)state. mts += gid. i++) { int m = nn. uint state[17]. } x = (st[n-1]&uuu)|(st[0]&lll). (uint*)state). i < n. k < lim. n = (num_rand+(nn-1)) / nn. num_rand). uint seed = gid*3. j < m. int num_rand) { 041: 042: 043: 044: 045: 046: 047: 048: 049: 050: 051: 052: 053: 054: 055: 056: 057: } 058: 059: __kernel void genrand(__global uint *out.int num_rand){ 060: 061: 062: 063: 064: 065: 066: int gid = get_global_id(0). nn = mts->nn. j. /* Generate random numbers */ } } int i. /* Initialize random numbers */ gen(out. const __global mt_struct *mts.B01-02632560-294 The OpenCL Programming Book 032: 033: 034: 035: 036: 037: 038: } 039: for (. if (i == n-1) m = num_rand%nn.
__global uint *rand.h> 002: #include <CL/cl.lmask.umask. cl_uint wmask. for (i=0. int count = 0. cl_uint maskB.h> 005: 006: typedef struct mt_struct_s { 007: 008: 009: 010: 011: cl_uint aaa. i < num_rand.ww. int i.rr. y. } } if (len < 1) { /* sqrt(len) < 1 = len < 1 */ count++.nn. shiftC. /* x coordinate */ y = ((float)(rand[i]&0xffff))/65535. maskC. int num_rand) { 071: 072: 073: 074: 075: 076: 077: 078: 079: 080: 081: 082: 083: 084: 085: 086: 087: 088: 089: } out[gid] = count. cl_int shift0.B01-02632560-294 The OpenCL Programming Book 067: } 068: 069: /* Count the number of points within the circle */ 070: __kernel void calc_pi(__global uint *out.17: Host Code 001: #include <stdlib. /* Distance from the origin */ rand += gid*num_rand. x = ((float)(rand[i]>>16))/65535. cl_int mm. List 6. shift1. int gid = get_global_id(0).0f.h> 004: #include <math. len. 206 .0f.h> 003: #include <stdio. shiftB. i++) { float x. /* y coordinate */ len = (x*x + y*y).
8388607.8.32.7.8.8.15.8388607.8388607.15.12.-8388608.18.17.-1.32.-1.-2785280}.23.17.-8388608.1004886656.-605200512.-1.8388607.-8388608.-1.12.17.15.-1230685312.-173220480.8388607.15.-8388608.8.8388607. {-883314023.32.8388607.8388607.8.18.15.32.17.-8552448}.8.18. {-504393846.-8388608.12.8388607.23.8388607.-1114112}.8.-8388608.15.7.8388607.12.-8388608.23.-34242560}.8388607.17.8.-8388608.-8388608.15.7.23.7.-1.23. {-171838771.-2785280}.23.18.7. {-96493045.8.8388607.8388607.17.-1.-1.-8388608.-8388608.-8388608.32.7.-1.-1.-1.8.8.7.18.8388607.32.32.32.12.8388607.12. 032: {-558849839.12.18.32.17.-411738496.12.17.12.7.15.17.23.17.17.1001217664.-2785280}. {-1524638763.17.17.18.17.17.17.18. {-1611140857.12.-34275328}.18.653090688.8.18.32.32.18.-1. {-1001052777.-1.32.-1.-36372480}.23.15.922049152.23.7.-36339712}.8388607.-8388608.32.-1. {-1723207278.8388607.-8388608.15.18.12.32.18.17.-8388608.7.15.18.-8388608. {-72754417.-8388608.8388607.18.23.8388607.23.17.1727880064.-1.18.-608739712.32.-1263215232. {-588451954.8.18.-1.17.-638264704.-453715328.17.23.-1. {-2145422714.7.-1.-8388608.-1.-1.-1769472}.-1.32.8388607.7.7.-1736704}.8388607.7.7.12.-1242112640.17.-2785280}.23.18.7.-1.8388607.-8388608.8. {-1779704749.2000501632.8388607. 207 .15.23.23.8.12.7.12.8388607.32. 033: 034: 035: 036: 037: 038: 039: 040: 041: 042: {-1009388965. {-1331085928. {-291834292.32.23.-1535844992.17.1722112896.12.8.32.17.18.12.-2785280}.12.-8388608.17.7.15.8388607.-2818048}.23.-8388608.12.1970625920.8388607.921000576.18.17.8.8.15.32.8.-2686976}.-8388608.-8388608.23.18.15.7.17.-151201152.18.-1.7.32.B01-02632560-294 The OpenCL Programming Book 012: } mt_struct. {-250871863.17. {-489740155.18.12.18.-8388608.15.23.-1.12.8.-8388608.15.23.8.-2818048}.8.12.-1. {-1154537980.23.15.23.18.12.12.15.-8388608.7.18. {-189104639. {-1028775805.15.18.7.938827392.1958042496.-2785280}.32.15.15.-45776896}.23.8.23.8388607.-1. {-822663744.-184755584.-8388608.8.7.-1.15.32.1702190464. 013: 014: mt_struct mts[] = { /* Parameters generated by the Dynamic Creater */ 015: 016: 017: {-1162865726.18. 018: 019: 020: 021: 022: 023: 024: 025: 026: 027: 028: 029: 030: 031: {-1086664688.-2785280}.-34177024}.32.12.8. {-2061554476.-688128}.15.32.32.-2785280}.-1263215232. {-474740330. {-692780774.-3833856}.18.-2785280}.32.8.32.23.12.8.7. 043: {-690295716.15.17.17.12.12.23.-8388608.-2785280}.23.8388607.-196608}.-1946722688.7. {-1514624952.-1494951296.7.-2785280}.15.-1.8.-8388608.32.7.-688432512.7.23.15.8.12.12.15.-2785280}.-1.-36339712}.23.-1514742400.7.15.
32.-1.12. cl_mem dev_mts. {-1172830434.8388607. cl_ulong prof_start.1970625920. cl_int ret. cl_context context = NULL.-8388608.17.17.8.7.32.15.8.-8388608. cl_uint *result.-1.-2785280}.2000509824.B01-02632560-294 The OpenCL Programming Book 044: 045: 046: {-1787515619. clGetDeviceIDs(platform_id. &ret_num_devices). cl_event ev_mt_end. CL_DEVICE_TYPE_DEFAULT.8388607.-688128}. /* The number of random numbers generated using one int count_all.-8388608. cl_mem rand. num_generator = sizeof(mts)/sizeof(mts[0]). 047: 048: #define MAX_SOURCE_SIZE (0x100000) 049: 050: int main(): clGetPlatformIDs(1. cl_uint ret_num_platforms.12.}.-1. /* The number of double pi.17.23. {-746112289.23. ev_copy_end.12.32. &platform_id. prof_pi_end. prof_mt_end. cl_int num_rand = 4096*256. cl_platform_id platform_id = NULL.-2654208}. local_item_size[3].15. size_t kernel_code_size. cl_device_id device_id = NULL. generator */ generators */ 208 . cl_uint ret_num_devices. cl_kernel kernel_mt = NULL. kernel_pi = NULL. char *kernel_src_str. cl_command_queue command_queue = NULL.23. prof_copy_end.8.7. &device_id.18. count. FILE *fp.18.15. &ret_num_platforms). ev_pi_end.8388607. i.720452480. size_t global_item_size[3]. cl_program program = NULL.18. 1.7.
&ret). clEnqueueWriteBuffer(command_queue. /* MT parameter clSetKernelArg(kernel_mt. sizeof(mts). 2. clBuildProgram(program. sizeof(cl_uint)*num_generator. sizeof(num_rand). fp). NULL. kernel_src_str = (char*)malloc(MAX_SOURCE_SIZE). /* Number of random (output of genrand) */ (input to genrand) */ numbers to generate */ 209 . &device_id. (void*)&rand). NULL. sizeof(cl_mem). CL_QUEUE_PROFILING_ENABLE. /* Set Kernel Arguments */ clSetKernelArg(kernel_mt. fclose(fp). fp = fopen("mt. &ret). (const char **)&kernel_src_str. mts. NULL). "calc_pi". (void*)&dev_mts). CL_MEM_READ_WRITE. dev_mts. 1. &ret). /* Create input parameter */ dev_mts = clCreateBuffer(context. &num_rand). (const size_t *)&kernel_code_size. "r"). kernel_code_size = fread(kernel_src_str. NULL. kernel_pi = clCreateKernel(program. &ret). 0. &ret). sizeof(cl_mem). /* Random numbers clSetKernelArg(kernel_mt. command_queue = clCreateCommandQueue(context. NULL.cl". sizeof(cl_uint)*num_rand*num_generator. NULL. 1. NULL). 1: context = clCreateContext( NULL. "". CL_MEM_READ_WRITE. sizeof(mts). "genrand". count = clCreateBuffer(context. device_id. kernel_mt = clCreateKernel(program. CL_TRUE. CL_MEM_READ_WRITE. NULL. result = (cl_uint*)malloc(sizeof(cl_uint)*num_generator). 1. 0. &ret). &ret). MAX_SOURCE_SIZE. &ret). /* Build Program*/ program = clCreateProgramWithSource(context. &device_id. NULL. 1. 0. /* Create output buffer */ rand = clCreateBuffer(context.
B01-02632560-294 The OpenCL Programming Book 106: 107: 108: 109: 110: 1. kernel_pi. sizeof(num_rand). global_item_size. &ev_pi_end). local_item_size. 1. NULL. CL_TRUE. 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: clSetKernelArg(kernel_pi. &prof_start. (void*)&rand). sizeof(cl_uint)*num_generator. /* Average the values of PI */ count_all = 0. 1. /* Get result */ clEnqueueReadBuffer(command_queue. /* Counter for points clSetKernelArg(kernel_pi. NULL. global_item_size. result. CL_PROFILING_COMMAND_END. NULL. &ev_copy_end). 1. local_item_size[2] = 1. local_item_size[1] = 1. NULL. i < num_generator. /* Get execution time info */ clGetEventProfilingInfo(ev_mt_end. global_item_size[1] = 1. } pi = ((double)count_all)/(num_rand * num_generator) * 4. &ev_mt_end). sizeof(cl_mem). i++) { count_all += result[i]. &num_rand). printf("pi = %f¥n". sizeof(cl_ulong). 0. sizeof(cl_ulong). NULL). for (i=0. 0. (void*)&count). 0. 0. /* Create a random number array */ clEnqueueNDRangeKernel(command_queue. sizeof(cl_mem). local_item_size. CL_PROFILING_COMMAND_QUEUED. kernel_mt. count. /* Random numbers clSetKernelArg(kernel_pi. /* Number of random within circle (output of calc_pi) */ (input to calc_pi) */ numbers used */ global_item_size[0] = num_generator. global_item_size[2] = local_item_size[0] = num_generator. /* Compute PI */ clEnqueueNDRangeKernel(command_queue. pi). 2. 210 . clGetEventProfilingInfo(ev_mt_end. NULL. 0.
NULL). return 0. We will start by looking at the kernel code 009: /* Initialize state using a seed */ 010: static void sgenrand_mt(uint seed. for (i=0. clReleaseKernel(kernel_pi).0). clReleaseEvent(ev_copy_end). (prof_pi_end .prof_pi_end)/(1000000.prof_mt_end)/(1000000. CL_PROFILING_COMMAND_END. sizeof(cl_ulong). clReleaseProgram(program). NULL). __global const mt_struct *mts. clReleaseEvent(ev_pi_end). clReleaseContext(context). 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: } clReleaseMemObject(rand). (prof_copy_end . &prof_pi_end. clReleaseCommandQueue(command_queue). free(kernel_src_str). clReleaseEvent(ev_mt_end). i < mts->nn. i++) { state[i] = seed. &prof_copy_end. clGetEventProfilingInfo(ev_copy_end. free(result).0)). clGetEventProfilingInfo(ev_pi_end. 211 . NULL).B01-02632560-294 The OpenCL Programming Book &prof_mt_end. clReleaseMemObject(count). printf(" mt: %f[ms]¥n" " pi: %f[ms]¥n" " copy: %f[ms]¥n". CL_PROFILING_COMMAND_END. (prof_mt_end . sizeof(cl_ulong).prof_start)/(1000000. clReleaseKernel(kernel_mt).0). uint *state) { 011: 012: 013: int i.
int n = mts->nn. for (. n = (num_rand+(nn-1)) / nn. k++) { x = (st[k]&uuu)|(st[k+1]&lll). const __global mt_struct *mts. The above code is actually copied from the original code used for MT. k < lim. n. The above code updates the state bits. st[k] = st[k+m-n] ^ (x>>1) ^ (x&1U ? aa : 0U). m = mts->mm. lll = mts->lmask. for (k=0. nn = mts->nn.lim. k++) { x = (st[k]&uuu)|(st[k+1]&lll). st[n-1] = st[m-1] ^ (x>>1) ^ (x&1U ? aa : 0U).B01-02632560-294 The OpenCL Programming Book 014: 015: 016: 017: 018: } } seed = (1812433253 * (seed ^ (seed >> 30))) + i + 1.1. i < n. i++) state[i] &= mts->wmask. st[k] = st[k+m] ^ (x>>1) ^ (x&1U ? aa : 0U). 040: static inline void gen(__global uint *out. x.m. lim = n . int k. for (i=0. } lim = n . uint uuu = mts->umask. uint aa = mts->aaa. j. int num_rand) { 041: 042: 043: int i. i++) { 212 . i < mts->nn. uint *st) { 022: 023: 024: 025: 026: 027: 028: 029: 030: 031: 032: 033: 034: 035: 036: 037: 038: } } x = (st[n-1]&uuu)|(st[0]&lll). 020: /* Update state */ 021: static void update_state(__global const mt_struct *mts. for (i=0. The state bit array is being initialized. uint *state. k < lim.
update_state(mts. 213 . x ^= (x << mts->shiftB) & mts->maskB. /* mts for this item */ out += gid * num_rand. uint seed = gid*3. /* Initialize random numbers */ gen(out. (uint*)state. j++) { /* Generate random numbers */ uint x = state[j]. 059: __kernel void genrand(__global uint *out. __global uint *rand. uint state[17].int num_rand){ 060: 061: 062: 063: 064: 065: 066: 067: } int gid = get_global_id(0). int num_rand) { 071: int gid = get_global_id(0). 069: /* Count the number of points within the circle */ 070: __kernel void calc_pi(__global uint *out. num_rand). mts. The kernel takes the output address. and the number of random number to generate as arguments. x ^= (x << mts->shiftC) & mts->maskC. j < m. The update_state() is called to update the state bits. and a random number is generated from the state bits. } The code above generates "num_rand" random numbers. mts += gid. out[i*nn + j] = x. if (i == n-1) m = num_rand%nn. x ^= x >> mts->shift0.B01-02632560-294 The OpenCL Programming Book 044: 045: 046: 047: 048: 049: 050: 051: 052: 053: 054: 055: 056: 057: } } int m = nn. x ^= x >> mts->shift1. The global ID is used to calculate the addresses to be used by this kernel. (uint*)state).__global mt_struct *mts. The "mts" and "out" are pointers to the beginning of the spaces allocated to be used by all work-items. /* Output buffer for this item */ sgenrand_mt(0x33ff*gid. state). /* Generate random numbers */ The above shows the kernel that generates random numbers by calling the above functions. mts. MT parameters. for (j=0.
Next we will take a look at the host code. 046: {-746112289. Since a 32-bit random number is generated.8. /* Distance from the origin */ if (len < 1) { /* sqrt(len) < 1 = len < 1 */ count++.18.8388607. 214 . for (i=0. i++) { float x.12.-1.7.-2785280}.-1.32. /* x coordinate */ y = ((float)(rand[i]&0xffff))/65535. /* y coordinate */ len = (x*x + y*y).32.17. 014: mt_struct mts[] = { /* Parameters generated by the Dynamic Creater */ 015: .-1514742400. {-822663744. x = ((float)(rand[i]>>16))/65535.8. } } out[gid] = count. If the distance from the origin is less than 1.15. int i.12. &device_id.18.-2785280}. the upper 16 bits are used for the x coordinate. y.B01-02632560-294 The OpenCL Programming Book 072: 073: 074: 075: 076: 077: 078: 079: 080: 081: 082: 083: 084: 085: 086: 087: 088: 089: } int count = 0. i < num_rand. The above is an array of struct for the MT parameters generated using "dc". then the chosen point is inside the circle..0f.0f.-8388608.}.23. The above code counts the number of times the randomly chosen point within the square is inside the section of the circle. rand += gid*num_rand.17. 1. and the lower 16 bits are used for the y coordinate.23. CL_DEVICE_TYPE_DEFAULT.2000509824.8388607. 075: 076: clGetDeviceIDs(platform_id. &ret_num_devices).7.15..-8388608. len.
device_id. kernel_code_size = fread(kernel_src_str. &ret). (void*)&rand). /* Number of random (output of genrand) */ (input to genrand) */ 215 . 0. The code above transfers the MT parameters generated by "dc" to global memory. fp = fopen("mt. CL_MEM_READ_WRITE. &ret). NULL. sizeof(cl_uint)*num_generator. kernel_src_str = (char*)malloc(MAX_SOURCE_SIZE). sizeof(mts). 0. &device_id. 2. /* Create output buffer */ rand = clCreateBuffer(context. "". NULL. clBuildProgram(program: context = clCreateContext( NULL. /* MT parameter clSetKernelArg(kernel_mt. kernel_mt = clCreateKernel(program. CL_TRUE. /* Create input parameter */ dev_mts = clCreateBuffer(context. &ret). (const char **)&kernel_src_str. 1. (const size_t *)&kernel_code_size. NULL). NULL. mts. dev_mts. clEnqueueWriteBuffer(command_queue. CL_QUEUE_PROFILING_ENABLE. (void*)&dev_mts). sizeof(num_rand). sizeof(cl_uint)*num_rand*num_generator. sizeof(cl_mem). sizeof(cl_mem). &ret). "genrand". &ret). /* Random numbers clSetKernelArg(kernel_mt. 1. fclose(fp).cl". NULL). kernel_pi = clCreateKernel(program. NULL. "r"). NULL. "calc_pi". MAX_SOURCE_SIZE. &ret). &device_id. 1. 1. fp). 0. NULL. 101: 102: 103: 104: /* Set Kernel Arguments */ clSetKernelArg(kernel_mt. NULL. &ret). /* Build Program*/ program = clCreateProgramWithSource(context. &num_rand). result = (cl_uint*)malloc(sizeof(cl_uint)*num_generator). command_queue = clCreateCommandQueue(context. CL_MEM_READ_WRITE. count = clCreateBuffer(context. &ret). CL_MEM_READ_WRITE. 1. sizeof(mts).
/* Number of random within circle (output of calc_pi) */ (input to calc_pi) */ numbers used */ The code segment above sets the arguments to the kernels "kernel_mt". and "kernel_pi". global_item_size[2] local_item_size. /* Create a random number array */ clEnqueueNDRangeKernel(command_queue. This means that the kernels are executed such that only 1 work-group is created. global_item_size[0] = num_generator.B01-02632560-294 The OpenCL Programming Book numbers to generate */ 105: 106: 107: 108: clSetKernelArg(kernel_pi. NULL. 0. sizeof(cl_mem). 0. } /* Average the values of PI */ count_all = 0. /* Random numbers clSetKernelArg(kernel_pi. 1. which generates random numbers. NULL. kernel_pi. (void*)&count). for (i=0. 110: = 1. 2. 216 . printf("pi = %f¥n". 1. global_item_size. NULL. local_item_size[2] = 1. local_item_size[1] = 1. 122: 123: 124: 125: 126: 127: 128: 129: pi = ((double)count_all)/(num_rand * num_generator) * 4. sizeof(cl_mem). 111: 112: 113: 114: 115: 116: 117: /* Compute PI */ clEnqueueNDRangeKernel(command_queue. i++) { count_all += result[i]. local_item_size. /* Counter for points clSetKernelArg(kernel_pi. sizeof(num_rand). kernel_mt. which performs the processing on one compute unit. 1. i < num_generator. global_item_size[1] = 1. NULL. &num_rand). which counts the number of points within the circle. (void*)&rand). &ev_mt_end). pi). global_item_size. &ev_pi_end). 0. The global item size and the local item size are both set to the number of random numbers. local_item_size[0] = num_generator.
2. The correspondence of the global work-item and the local work-item to the hardware (at least as of this writing) are summarized in Table 6. Unlike OS threads. the value of PI is this proportion multiplied by 4. Table 6. Since the time required for the memory transfer operation is negligible compared to the other operations. Parallelization Now we will go through the code in the previous section. fibers do not execute over multiple cores. and use parallelization where we can.8 409.3.B01-02632560-294 The OpenCL Programming Book The value of PI is calculated by tallying up the number of points chosen within the circle by each thread to calculate the proportion of hits.8 536. As discussed earlier. but are capable of 217 .8 364. "Fibers" are lightweight threads capable of performing context switching by saving the register contents.9 copy (ms) 0. Table 6.2 243. Running the code as is on Core i7-920 + Tesla C 1060 environment.8 pi (ms) 2399. The code in the previous section performed all the operation on one compute unit.3: Correspondence of hardware with OpenCL work-item OpenCL NVIDIA AMD FOXC Global work-item SM OS thread OS thread Local work-item CUDA core Fiber Fiber "OS threads" are threads managed by the operating systems.002 We will look at how these processing times change by parallelization. such as pthreads and Win32 threads.07 0.2: Processing Times OpenCL NVIDIA AMD FOXC mt (ms) 3420.02 0. we will not concentrate on this part. the execution time using different OpenCL implementations for kernel executions and memory copy are shown below in Figure 6.
B01-02632560-294 The OpenCL Programming Book performing context switching quickly. A CUDA core is the smallest unit capable of performing computations. sizeof(cl_uint). We will change the code such that the local work-item size is the number of generated parameters created using "dc" divided by CL_DEVICE_MAX_COMPUTE_UNITS. 218 . Figure 6.10 shows the basic block diagram. "SM (Streaming Multiprocessor)" and "CUDA Core" are unit names specific to NVIDIA GPUs.10: OpenCL work-item and its hardware correspondences Please refer to the "CUDA ™ Programming Guide" contained in the NVIDIA SDK for more details on the NVIDIA processor architecture [19]. if (num_compute_unit > 32) num_compute_unit = 32. clGetDeviceInfo(device_id. &num_compute_unit. igure 6. NULL). This would require multiple work-groups to be created. A group of CUDA cores make up the SM. The number of work-groups and work-items can be set using the code shown below. Since the code on the previous section only uses one work-group. parallel execution via OS threads or SM is not performed. CL_DEVICE_MAX_COMPUTE_UNITS.
&num_rand). and each work-group requires a MT parameter. &num_rand). We have limited the maximum number of work-groups to 32. 0. sizeof(num_rand). local_item_size[2] = 1. (void*)&count). /* Set Kernel Arguments */ clSetKernelArg(kernel_mt. (void*)&dev_mts). /* Number of MT parameters */ clSetKernelArg(kernel_pi. __kernel void genrand(__global uint *out. local_item_size[0] = num_work_item. (void*)&rand). /* Random numbers(input to calc_pi) */ clSetKernelArg(kernel_pi. /* Random numbers(output of genrand) */ clSetKernelArg(kernel_mt. 3.__global mt_struct *mts. &num_generator). 2. global_item_size[1] = 1. 1. int num_generator){ 219 . sizeof(cl_mem). sizeof(cl_mem).B01-02632560-294 The OpenCL Programming Book /* Number of work items */ num_work_item = (num_generator+(num_compute_unit-1)) / num_compute_unit. sizeof(num_generator). /* Number of random numbers to generate */ clSetKernelArg(kernel_mt. sizeof(num_generator). global_item_size[2] = 1. 2. /* MT parameter(input to genrand) */ clSetKernelArg(kernel_mt. sizeof(cl_mem). since we have only defined 32 sets of MT parameters in List 6. (void*)&rand). 1. /* Number of MT parameters */ On the device side. &num_generator). local_item_size[1] = 1. /* Random numbers (input to calc_pi) */ clSetKernelArg(kernel_pi. /* Set work-group and work-item size */ global_item_size[0] = num_work_item * num_compute_unit.17. /* Counter for points withincircle (output of calc_pi) */ clSetKernelArg(kernel_pi. the number of random numbers to generate is limited by the number of available MT parameters. sizeof(num_rand).int num_rand. 3. sizeof(cl_mem). 0.
As shown in Figure 6. which has 4 cores. Thus.6 92. So the difference is in whether the work-items were executed in parallel over the processing units.B01-02632560-294 The OpenCL Programming Book int gid = get_global_id(0). int i. or the work-items were executed in parallel over the compute units. where parallelism is present over the multiple processing units.10. This was expected.4: Processing time after parallelization OpenCL NVIDIA AMD FOXC mt (ms) 2800. … } The processing times after making the changes are shown below in Table 6. int num_rand. the processing time was not reduced significantly.8 94. The code in this section allows one work-item to be executed on each compute-unit. Table 6. since it is executed on Core i7-920. NVIDIA GPUs can perform parallel execution over multiple work-items. if (gid >= num_generator) return. the processing time has not changed for NVIDIA's OpenCL. In the code in the previous section.4 73. However. int count = 0. uint seed = gid*3. if (gid >= num_generator) return. uint state[17]. all work items are performed in one compute unit. and this speed up is merely from less chance of register data being stored in another memory during context switching.8 pi (ms) 1018.6 59. 220 . __global uint *rand. int num_generator) { int gid = get_global_id(0).4.1 Note the processing time using FOXC and AMD are reduced by a factor of 4. … } __kernel void calc_pi(__global uint *out.
4 94.6 60.5: Processing times from increasing parallelism # MT parameters 128 NVIDIA AMD FOXC 256 NVIDIA AMD FOXC 512 NVIDIA AMD FOXC mt (ms) 767.3 379. but that it reduces significantly on the GPU.4 73.5. We will now look into optimizing the code to be executed on the GPU. Compared to processor with cache.8 214. The processing time is shown in Table 6. accessing the global memory each time can slow down the average access times by a large margin. To get around this problem on the NVIDIA GPU.B01-02632560-294 The OpenCL Programming Book To use the GPU effectively.8 94.8 pi (ms) 288. Since Tesla does not have any cache hardware.3 94. execution is slower on the NVIDIA despite increasing the parallelism. a wise usage of the local memory is required.4 92. Table 6.3 91.8 73. Increasing Parallelism This section will focus on increasing parallelism for efficient execution on the NVIDIA GPU.4 491. This will be done by increasing the number of MT parameters generated by "dc". Looking at the code again.5 below.6 59.6 62. access to the global memory requires a few hundred clock cycles. The first thing to look at for efficient execution on the GPU is the memory access.4 Note that the processing time does not change on the CPU. Optimization for NVIDIA GPU Looking at Table 6.7 117. the variables "state" and "mts" accesses the same memory space many 221 . parallel execution should occur in both the compute units and the CUDA cores.5 94.0 73.
NULL). /* Number of random numbers to generate */ clSetKernelArg(kernel_mt. /* MT parameter(input to genrand) */ clSetKernelArg(kernel_mt. (void*)&rand). We will change the code so that these data are written to the local memory. sizeof(mt_struct)*num_work_item. we will change the host-side code so the data to be local memory is passed in as an argument to the kernel. __local const mt_struct *mts. by using the __local qualifier. 1. __local uint *st) { /* … */ } static inline void gen(__global uint *out. sizeof(cl_mem). sizeof(cl_mem). (void*)&dev_mts). &num_rand). /* Local Memory(mts) */ The kernel will now be changed to use the local memory. /* Initialize state using a seed */ static void sgenrand_mt(uint seed.B01-02632560-294 The OpenCL Programming Book times. __local uint *state) { /* … */ } /* Update State */ static void update_state(__local const mt_struct *mts. sizeof(num_rand). /* Random numbers(output of genrand)*/ clSetKernelArg(kernel_mt. 0. 5. 2. &num_generator). int num_rand) { /* … */ } 222 . First. sizeof(cl_uint)*17*num_work_item. /* Set kernel arguments */ clSetKernelArg(kernel_mt. sizeof(num_generator). __local uint *state. 4. NULL). const __local mt_struct *mts. 3. /* Number of MT parameters */ clSetKernelArg(kernel_mt. /* Local Memory (state) */ clSetKernelArg(kernel_mt.
shiftB.shift0.6: Processing times on the Tesla using local memory # MT parameters 128 256 512 mt (ms) 246. mts. mts->shift1 = mts_g[gid].wmask.rr. mts->rr = mts_g[gid]. mts.1 223 . mts->umask = mts_g[gid]. mts->nn = mts_g[gid]. /* Output buffer for this item*/ sgenrand_mt(0x33ff*gid.maskC.8 206. mts->wmask = mts_g[gid]. __local uint *state_mem. num_rand).lmask. (__local uint*)state. mts->maskC = mts_g[gid]. Table 6. mts->shiftB = mts_g[gid].4 108.2 143.7 pi (ms) 287.maskB. /* Store current state in local memory */ if (gid >= num_generator) return. mts->shift0 = mts_g[gid]. __local uint *state = state_mem + lid*17.shiftC. /* Copy MT parameters to local memory */ mts->aaa = mts_g[gid]. /* Generate random numbers */ } The new execution times are shown in Table 6. mts += lid. __local mt_struct *mts){ int lid = get_local_id(0).7 113.nn. mts->maskB = mts_g[gid].int num_rand. int num_generator. out += gid * num_rand.6. (__local uint*)state).umask.B01-02632560-294 The OpenCL Programming Book __kernel void genrand(__global uint *out. int gid = get_global_id(0).shift1.__global mt_struct *mts_g.aaa. mts->mm = mts_g[gid]. mts->ww = mts_g[gid]. mts->lmask = mts_g[gid]. /* Initialize random numbers */ gen(out. mts->shiftC = mts_g[gid].ww.mm.
11: Grouping of work-items 224 . as well as the MT parameters. This would not be a problem for Tesla. which is 17 x 4 = 68 bytes. the local memory size is 16. In the original code. each work-item processes a different part of an array. This is known as a coalesced access. each work-item requires the storage of the state. each work-item requires 124 bytes.11. since the value of CL_DEVICE_MAX_COMPUT_UNITS is 30. On NVIDIA GPUs. Figure 6.384 bytes. Therefore. since the number of work-items per work-group will be increased. which can be broken up into the next 3 processes: • Updating state • Tempering • Computing the value of PI First. This change is illustrated in Figure 6.B01-02632560-294 The OpenCL Programming Book We see a definite increase in speed. Using this knowledge. which is 14 x 4 = 56. For our program. meaning 16384/124 ≈ 132 work-items can be processed within a work-group. it may not be able to process if the number of parameters is increased to 256 or 512. One of the properties of the NVIDIA GPU is that it is capable of accessing a block of continuous memory at once to be processed within a work-group. For GPUs that do not have many compute units. we will tackle the computation of PI. The thing to note about the local memory is that it is rather limited. we will write the code such that each work-group accesses continuous data on the memory. We will now further tune our program.
NULL. local_item_size_pi[0] = 128. 225 . global_item_size_pi[2] = 1. __local uint *count_per_wi) { int gid = get_group_id(0). int num_rand_all. /* Count the number of points within the circle */ __kernel void calc_pi(__global uint *out. int num_rand_per_compute_unit. end. begin. local_item_size_pi. kernel_pi. &ev_pi_end). 0. local_item_size_pi[1] = 1. int lid = get_local_id(0). int i. global_item_size_pi[0] = num_compute_unit * 128. and the number of work-items is set to 128. The number of work-groups is changed to CL_DEVICE_MAX_COMPUT_UNITS. The above is the change made on the host-side. int num_compute_unit. __global uint *rand. global_item_size_pi[1] = 1. /* Compute PI */ ret = clEnqueueNDRangeKernel(command_queue. NULL.B01-02632560-294 The OpenCL Programming Book The changes in the code are shown below. 1. local_item_size_pi[2] = 1. int count = 0. global_item_size_pi.
/* y coordinate */ len = (x*x + y*y). /* Reduce the end boundary index it is greater than the number of random numbers to generate*/ if (end > num_rand_all) end = num_rand_all.0f. x = ((float)(rand[i]>>16))/65535. } } /* Process the remaining elements */ if ((i + lid) < end) { float x.0f. end = begin + num_rand_per_compute_unit.0f. i < end-128. len. } } count_per_wi[lid] = count. /* Sum the counters from each work-item */ barrier(CLK_LOCAL_MEM_FENCE). /* Wait until all work-items are finished */ if (lid == 0) { int count = 0. 226 . i+=128) { float x. /* Process 128 elements at a time */ for (i=begin. // Compute the reference address corresponding to the local ID rand += lid. /* x coordinate */ y = ((float)(rand[i]&0xffff))/65535. y.B01-02632560-294 The OpenCL Programming Book /* Indices to be processed in this work-group */ begin = gid * num_rand_per_compute_unit. /* Distance from the origin */ if (len < 1) { /* sqrt(len) < 1 = len < 1 */ count++. /* Distance from the origin */ if (len < 1) { /* sqrt(len) < 1 = len < 1 */ count++. /* y coordinate */ len = (x*x + y*y). y. /* x coordinate */ y = ((float)(rand[i]&0xffff))/65535.0f. x = ((float)(rand[i]>>16))/65535. len.
and depending on the cost of synchronization. i++) { count += count_per_wi[i]. The code includes the case when the number of data to process is not a multiple of 128. /* Sum the counters */ } out[gid] = count. as well as the tempering process.B01-02632560-294 The OpenCL Programming Book for (i=0.05 ms. since the processing on each word does not require many instructions. and all work-items within a warp are executed synchronously. Figure 6. we will optimize the tempering algorithm. However. performance may potentially suffer from parallelization.10 below. some operations can be performed in parallel without the need to synchronize. Taking advantage of this property. 9 state update and 17 tempering can be performed in parallel. Next. For the parameters in our example program. NVIDIA GPUs performs its processes in "warps". A warp is made up of 32 work-items. this process has a parallel nature. Note that each work-group processes the input data such that all the work-items within the work-group access continuous address space. which is a 10-fold improvement over the previous code. } } The above code shows the changes made on the device side. The processing time using this code is 9. A new block diagram of the distribution of work-items and work-groups are shown in Figure 6. As stated earlier. This would enable these processes to be performed without increasing the synchronization cost. We had concluded previously that a use of SIMD units would be optimal for this process. to reduce the cost of synchronization. We will use one warp to perform the update of the state.10: Distribution of work-items for MT 227 . i < 128.
so making this change may not allow for proper operation on other devices. /* Number of work-items per group (warp = 32work items) */ 228 .B01-02632560-294 The OpenCL Programming Book Note that this optimization is done by using the property of NVIDIA GPUs. /* Total number of warps */ num_warp = warp_per_compute_unit * num_compute_unit . The changes to the program are shown below. /* Each compute unit process 4 warps */ warp_per_compute_unit = 4. /* Number of MT parameters per warp (rounded up) */ num_param_per_warp = (num_generator + (num_warp-1)) / num_warp.
sizeof(cl_uint)*17*num_work_item. 1. &num_rand_per_generator). sizeof(num_generator). 2. and this is sent in as an argument. &num_generator). /* Local Memory (mts) */ /* Set the number of work-groups and work-items per work-group */ global_item_size_mt[0] = num_work_item * num_compute_unit. /* Local Memory (state) */ clSetKernelArg(kernel_mt. int wlid) { int n = 17. local_item_size_mt[2] = 1. /* Set Kernel Arguments */ clSetKernelArg(kernel_mt. local_item_size_mt[1] = 1. The above shows the changes made on the host-side. /* Update state */ static void update_state(__local const mt_struct *mts. x. 0. /* Number of parameters to process per work-group */ clSetKernelArg(kernel_mt. __local uint *st. 3. lll = mts->lmask. sizeof(mt_struct)*num_work_item. &num_param_per_warp). sizeof(num_param_per_warp). /* Number of random numbers to generate for each MT parameter */ clSetKernelArg(kernel_mt. global_item_size_mt[1] = 1. uint aa = mts->aaa. local_item_size_mt[0] = num_work_item.B01-02632560-294 The OpenCL Programming Book num_work_item = 32 * warp_per_compute_unit. /* Number of random numbers to generate */ clSetKernelArg(kernel_mt. sizeof(num_rand_per_generator). 5. 229 . The number of random numbers to be generated by each work-group is first computed. 6. which is 4 warps. /* Number of random numbers per group */ num_rand_per_compute_unit = (num_rand_all + (num_compute_unit-1)) / num_compute_unit.lim. sizeof(cl_mem). (void*)&rand). NULL). /* Random numbers (output of genrand) */ clSetKernelArg(kernel_mt. m = 8. The number of work-items in each work-group is set to 128. 4. /* MT parameter (input to genrand) */ clSetKernelArg(kernel_mt. uint uuu = mts->umask. global_item_size_mt[2] = 1. sizeof(cl_mem). (void*)&dev_mts). NULL). int k.
No problem as long as the read operation * for each work-item within a work-group is finished before writing */ k = wlid + 9. * but since the operations within a warp is synchronized. wlid). const __local mt_struct *mts. x = (st[k]&uuu)|(st[k+1]&lll). } if (wlid < 7) { /* Same reasoning as above. if (i == n-1) m = num_rand%nn. j. nn = mts->nn. } } static inline void gen(__global uint *out. st[n-1] = st[m-1] ^ (x>>1) ^ (x&1U ? aa : 0U). the write to * st[k] by each work-item occurs after read from st[k+1] and st[k+m] */ k = wlid. if (wlid < m) { /* tempering performed within 1 warp */ 230 . st[k] = st[k+m-n] ^ (x>>1) ^ (x&1U ? aa : 0U). state. __local uint *state.B01-02632560-294 The OpenCL Programming Book if (wlid < 9) { /* Accessing indices k+1 and k+m would normally have dependency issues. int num_rand. for (i=0. x = (st[k]&uuu)|(st[k+1]&lll). } if (wlid == 0) { x = (st[n-1]&uuu)|(st[0]&lll). int wlid) { int i. update_state(mts. i++) { int m = nn. n. n = (num_rand+(nn-1)) / nn. i < n. st[k] = st[k+m] ^ (x>>1) ^ (x&1U ? aa : 0U).
int num_rand. } } } __kernel void genrand(__global uint *out. end. generator_id < end. int generator_id. uint x = state[j]. mts = mts + warp_id. /* Local ID within the warp */ __local uint *state = state_mem + warp_id*17. x ^= (x << mts->shiftB) & mts->maskB. __local mt_struct *mts){ int warp_per_compute_unit = 4. __local uint *state_mem. int workitem_per_warp = 32. /* Store state in local memory */ end = num_param_per_warp*warp_id + num_param_per_warp. int warp_id = wid * warp_per_compute_unit + lid / workitem_per_warp. generator_id ++) { 231 .__global mt_struct *mts_g. uint num_param_per_warp. int wlid = lid % workitem_per_warp. int num_generator. x ^= (x << mts->shiftC) & mts->maskC. x ^= x >> mts->shift1. int lid = get_local_id(0). /* Loop for each MT parameter within this work-group */ for (generator_id = num_param_per_warp*warp_id. if (end > num_generator) end = num_generator. x ^= x >> mts->shift0.B01-02632560-294 The OpenCL Programming Book int j = wlid. out[i*nn + j] = x. int wid = get_group_id(0).
shiftB. (__local uint*)state. mts->shiftC = mts_g[generator_id]. and parallel processing is performed within the warp.B01-02632560-294 The OpenCL Programming Book if (wlid == 0) { /* Copy MT parameters to local memory */ mts->aaa = mts_g[generator_id]. num_rand. wlid).lmask. reducing the need for synchronization.aaa. (__local uint*)state). mts->shift1 = mts_g[generator_id]. mts->wmask = mts_g[generator_id].nn.8 35. mts->shiftB = mts_g[generator_id]. mts->shift0 = mts_g[generator_id]. It is changed such that one DC parameter is processed on each warp. mts->maskB = mts_g[generator_id]. /* Initialize random numbers */ } gen(out + generator_id*num_rand. mts->nn = mts_g[generator_id]. Table 6. mts.7: Processing times after optimization # MT parameters 128 256 512 mt (ms) 57. mts->rr = mts_g[generator_id].shift1. mts->maskC = mts_g[generator_id].7 Note the processing times are reduced significantly.0 42.rr. mts->umask = mts_g[generator_id]. sgenrand_mt(0x33ff*generator_id.maskC. 232 . mts->lmask = mts_g[generator_id].maskB. /* Generate random numbers */ } } The above code shows the changes made on the device-side.ww.umask. The processing times after making these changes are shown in Table 6.wmask. mts->ww = mts_g[generator_id].mm. mts.7 below. mts->mm = mts_g[generator_id].shift0.shiftC.
lmask. char **argv) 019:{ 020: */ 021: 022: 023: 024: 025: 026: 027: 028: 029: 030: cl_int num_rand_per_compute_unit.19 (device). 011: cl_uint maskB. double pi.h> 005: 006:typedef struct mt_struct_s { 007: cl_uint aaa. cl_device_id device_id = NULL. List 6.h" 015: 016:#define MAX_SOURCE_SIZE (0x100000) 017: 018:int main(int argc. maskC.18 (host) and List 6. shiftC.h> 004:#include <math. cl_platform_id platform_id = NULL. cl_context context = NULL. cl_uint ret_num_devices. /* The number of random numbers to generate 233 . shiftB. int count_all. 009: cl_uint wmask.umask. 008: cl_int mm. shift1. num_rand_per_generator.h> 003:#include <stdio. cl_int num_rand_all = 4096*256*32. 013: 014:#include "mts.ww. cl_uint ret_num_platforms. 010: cl_int shift0.nn.B01-02632560-294 The OpenCL Programming Book The final code for the program with all the changes discussed is shown in List 6. cl_uint num_generator.h> 002:#include <CL/cl.18: Host-side optimized for NVIDIA GPU 001:#include <stdlib. unsigned int num_work_item. i.rr. there is a 90-fold improvement since the original program [20]. Running this code on Tesla. 012:} mt_struct .
prof_pi_end. cl_kernel kernel_mt = NULL. count. cl_uint num_compute_unit. cl_ulong prof_start. char *kernel_src_str. if (n == 128) { mts = mts128. num_rand_per_generator = num_rand_all / 256. mts_size = sizeof(mts128). size_t global_item_size_mt[3]. size_t global_item_size_pi[3]. ev_copy_end. num_generator = 256. } } num_param_per_warp. cl_program program = NULL. cl_event ev_mt_end. mt_struct *mts = NULL. int mts_size. num_warp. mts_size = sizeof(mts256). prof_mt_end: cl_command_queue command_queue = NULL. kernel_pi = NULL. warp_per_compute_unit. } if (n == 256) { mts = mts256. num_generator = 128. cl_mem rand. num_rand_per_generator = num_rand_all / 128. 234 . size_t kernel_code_size. ev_pi_end. cl_int ret. local_item_size_pi[3]. local_item_size_mt[3]. prof_copy_end. if (argc >= 2) { int n = atoi(argv[1]). cl_uint *result. FILE *fp. cl_mem dev_mts.
CL_MEM_READ_WRITE. "r"). mts_size = sizeof(mts512). 1. clGetDeviceIDs(platform_id. fclose(fp). NULL. /* Build Program*/ program = clCreateProgramWithSource(context. &ret). NULL. &platform_id. kernel_pi = clCreateKernel(program. kernel_src_str = (char*)malloc(MAX_SOURCE_SIZE). num_generator = 512. sizeof(cl_uint)*num_generator. "genrand". 1. &device_id. count = clCreateBuffer(context. clBuildProgram(program. NULL. &ret_num_platforms). CL_QUEUE_PROFILING_ENABLE. NULL. fp). &device_id. &ret). &ret_num_devices). context = clCreateContext( NULL. 1. &ret). result = (cl_uint*)malloc(sizeof(cl_uint)*num_generator).cl". fp = fopen("mt. 1.B01-02632560-294 The OpenCL Programming Book: kernel_mt = clCreateKernel(program. kernel_code_size = fread(kernel_src_str. &ret). num_rand_per_generator = num_rand_all / 512. NULL). &ret). /* Create output buffer */ rand = clCreateBuffer(context. sizeof(cl_uint)*num_rand_all. "calc_pi". CL_DEVICE_TYPE_DEFAULT. &ret). 1. "". CL_MEM_READ_WRITE. MAX_SOURCE_SIZE. command_queue = clCreateCommandQueue(context. &ret). device_id. 235 . clGetPlatformIDs(1. (const char **)&kernel_src_str. NULL. &device_id. (const size_t *)&kernel_code_size. } if (mts == NULL) { mts = mts512.
(void*)&dev_mts). NULL). /* MT parameter clSetKernelArg(kernel_mt. sizeof(cl_mem). (output of genrand) */ (input to genrand) */ &num_rand_per_generator). NULL). (void*)&rand). 4. /* Local clSetKernelArg(kernel_mt. /* Number of MT parameters per warp (rounded up) */ num_param_per_warp = (num_generator + (num_warp-1)) / num_warp. 6. sizeof(mt_struct)*num_work_item. /* Local random numbers to generate */ /* Number of parameters to process per work-group */ Memory (state) */ Memory (mts) */ 236 . &num_generator). NULL. clGetDeviceInfo(device_id. mts_size. mts. sizeof(num_param_per_warp). mts_size. &num_param_per_warp). sizeof(cl_mem). /* Total number of warps */ num_warp = warp_per_compute_unit * num_compute_unit . 3. sizeof(num_rand_per_generator). /* Number of random numbers per group */ num_rand_per_compute_unit = (num_rand_all + (num_compute_unit-1)) / num_compute_unit. 1. /* Number of work-items per group (warp = 32work items) */ num_work_item = 32 * warp_per_compute_unit.B01-02632560-294 The OpenCL Programming Book 099: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: /* Create input parameter */ dev_mts = clCreateBuffer(context. CL_MEM_READ_WRITE. clSetKernelArg(kernel_mt. NULL. 0. NULL). sizeof(cl_uint). 0. sizeof(cl_uint)*17*num_work_item. CL_DEVICE_MAX_COMPUTE_UNITS. /* Number of clSetKernelArg(kernel_mt. /* Set Kernel Arguments */ clSetKernelArg(kernel_mt. 0. dev_mts. &num_compute_unit. /* Number of random numbers to generate for each MT parameter */ 120: 121: 122: 123: clSetKernelArg(kernel_mt. sizeof(num_generator). &ret). NULL). /* Random numbers clSetKernelArg(kernel_mt. 5. /* Each compute unit process 4 warps */ warp_per_compute_unit = 4. CL_TRUE. clEnqueueWriteBuffer(command_queue. 2.
local_item_size_pi. &ev_mt_end). 1. /* Number of random numbers to process per work-group */ Number of MT parameters */ random numbers used */ global_item_size_mt[1] = 1. &ev_copy_end). sizeof(cl_uint)*num_generator. NULL. 0. sizeof(cl_mem). 4. (void*)&count). &num_rand_all). 0. sizeof(num_rand_per_compute_unit). local_item_size_mt. local_item_size_mt[2] = 1. NULL. 0. /* Number of clSetKernelArg(kernel_pi. (void*)&rand). sizeof(cl_uint)*128. &ev_pi_end). sizeof(num_compute_unit). clSetKernelArg(kernel_pi. local_item_size_pi[2] = 1. local_item_size_mt[0] = num_work_item. 5. /* clSetKernelArg(kernel_pi. sizeof(cl_mem). NULL. NULL). global_item_size_pi[1] = 1. kernel_mt. 3. kernel_pi. 237 .B01-02632560-294 The OpenCL Programming Book 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: /* Average the values of PI */ /* Get result */ clEnqueueReadBuffer(command_queue. sizeof(num_rand_all). global_item_size_mt. 0. count. result. global_item_size_mt[2] = 1. global_item_size_pi[2] = 1. /* Memory used for counter */ within circle (output of calc_pi) */ (input to calc_pi) */ &num_rand_per_compute_unit). &num_compute_unit). 2. clSetKernelArg(kernel_pi. /* Random numbers clSetKernelArg(kernel_pi. 1. /* Create a random number array */ clEnqueueNDRangeKernel(command_queue. local_item_size_pi[0] = 128. 1. /* Counter for points clSetKernelArg(kernel_pi. local_item_size_mt[1] = 1. CL_TRUE. global_item_size_pi. local_item_size_pi[1] = 1. NULL. NULL. 0. /* Set the number of work-groups and work-items per work-group */ global_item_size_mt[0] = num_work_item * num_compute_unit. global_item_size_pi[0] = num_compute_unit * 128. /* Compute PI */ clEnqueueNDRangeKernel(command_queue.
0).0).0)). i<(int)num_compute_unit. sizeof(cl_ulong). &prof_pi_end. (prof_pi_end . 238 . clReleaseEvent(ev_pi_end).prof_mt_end)/(1000000. clReleaseProgram(program). clReleaseCommandQueue(command_queue). printf("pi = %. for (i=0. pi). NULL). } pi = ((double)count_all)/(num_rand_all) * 4. sizeof(cl_ulong). clReleaseEvent(ev_mt_end). clReleaseEvent(ev_copy_end). &prof_mt_end. NULL).prof_pi_end)/(1000000. NULL). clReleaseContext(context). clGetEventProfilingInfo(ev_pi_end. i++) { count_all += result[i]. clGetEventProfilingInfo(ev_copy_end. &prof_copy_end. sizeof(cl_ulong). printf(" mt: %f[ms]¥n" " pi: %f[ms]¥n" " copy: %f[ms]¥n".20f¥n". clReleaseKernel(kernel_pi). CL_PROFILING_COMMAND_QUEUED. (prof_mt_end . sizeof(cl_ulong). CL_PROFILING_COMMAND_END.prof_start)/(1000000. NULL). clReleaseMemObject(rand).B01-02632560-294 The OpenCL Programming Book 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: count_all = 0. clGetEventProfilingInfo(ev_mt_end. /* Get execution time info */ clGetEventProfilingInfo(ev_mt_end. CL_PROFILING_COMMAND_END. CL_PROFILING_COMMAND_END. (prof_copy_end . &prof_start. clReleaseMemObject(count). clReleaseKernel(kernel_mt).
int shift0. __local uint *st. __local uint *state) { 011: 012: 013: 014: 015: 016: 017: 018:} 019: 020:/* Update state */ 021:static void update_state(__local const mt_struct *mts. shiftB. uint maskB.nn. the write to * st[k] by each work-item occurs after read from st[k+1] and st[k+m] */ int n = 17. __local const mt_struct *mts.ww. i++) state[i] &= mts->wmask. uint uuu = mts->umask. 239 . return 0. i < mts->nn. int mm. lll = mts->lmask. uint aaa. shift1. uint aa = mts->aaa.lmask. shiftC.19: Device-side optimized for NVIDIA GPU 001:typedef struct mt_struct_s { 002: 003: 004: 005: 006: 008: 009:/* Initialize state using a seed */ 010:static void sgenrand_mt(uint seed. int wlid) { 022: 023: 024: 025: 026: 027: 028: 029: 030: if (wlid < 9) { /* Accessing indices k+1 and k+m would normally have dependency issues. uint wmask. x.umask.rr. free(result). int k. 007:} mt_struct . } for (i=0.B01-02632560-294 The OpenCL Programming Book 181: 182: 183: 184:} free(kernel_src_str). seed = (1812433253 * (seed ^ (seed >> 30))) + i + 1. int i. maskC. for (i=0. * but since the operations within a warp is synchronized.lim. i < mts->nn. List 6. i++) { state[i] = seed. m = 8.
x ^= (x << mts->shiftC) & mts->maskC. int num_rand. if (i == n-1) m = num_rand%nn. n. j. wlid). No problem as long as the read operation * for each work-item within a work-group is finished before writing */ k = wlid. i < n. int i. st[k] = st[k+m] ^ (x>>1) ^ (x&1U ? aa : 0U). x = (st[k]&uuu)|(st[k+1]&lll):static inline void gen(__global uint *out. n = (num_rand+(nn-1)) / nn. i++) { int m = nn. int wlid) { 051: 052: 053: 054: 055: 056: 057: 058: 059: 060: 061: 062: 063: 064: 065: if (wlid < m) { /* tempering performed within 1 warp */ int j = wlid. } if (wlid < 7) { /* Same reasoning as above. x ^= x >> mts->shift0. update_state(mts. 240 . x = (st[k]&uuu)|(st[k+1]&lll). st[n-1] = st[m-1] ^ (x>>1) ^ (x&1U ? aa : 0U). nn = mts->nn. x ^= (x << mts->shiftB) & mts->maskB. __local uint *state. k = wlid + 9. state. for (i=0. uint x = state[j]. st[k] = st[k+m-n] ^ (x>>1) ^ (x&1U ? aa : 0U). } } if (wlid == 0) { x = (st[n-1]&uuu)|(st[0]&lll). const __local mt_struct *mts.
generator_id ++) mts = mts + warp_id. /* Store state in local memory */ uint num_param_per_warp. generator_id < end. out[i*nn + j] = x.aaa.int num_rand. int wid = get_group_id(0). int num_generator. /* Local ID within the warp */ 241 . mts->mm = mts_g[generator: { if (wlid == 0) { /* Copy MT parameters to local memory */ mts->aaa = mts_g[generator_id]. int workitem_per_warp = 32. int lid = get_local_id(0). 072:__kernel void genrand(__global uint *out. __local mt_struct *mts){ int warp_per_compute_unit = 4. __local uint *state = state_mem + warp_id*17. __local uint *state_mem.B01-02632560-294 The OpenCL Programming Book 066: 067: 068: 069: 070:} 071: } } x ^= x >> mts->shift1. int warp_id = wid * warp_per_compute_unit + lid / workitem_per_warp. end. if (end > num_generator) end = num_generator. /* Loop for each MT parameter within this work-group */ for (generator_id = num_param_per_warp*warp_id.mm. int generator_id. end = num_param_per_warp*warp_id + num_param_per_warp.__global mt_struct *mts_g. int wlid = lid % workitem_per_warp.
__global uint *rand. end = begin + num_rand_per_compute_unit. int count = 0. mts->ww = mts_g[generator_id]. int num_rand_per_compute_unit. mts. 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: /* Reduce the end boundary index it is greater than the number of random numbers to generate*/ /* Indices to be processed in this work-group */ begin = gid * num_rand_per_compute_unit. 242 . mts->shift0 = mts_g[generator_id]. mts->maskC = mts_g[generator_id]. /* Initialize random numbers */ gen(out + generator_id*num_rand.shift0. wlid).lmask.shift1. mts->shift1 = mts_g[generator_id].maskB. mts->shiftC = mts_g[generator_id]. mts->umask = mts_g[generator_id]. int lid = get_local_id(0). mts->lmask = mts_g[generator_id]. (__local uint*)state.shiftB. int num_compute_unit.ww.shiftC. mts. sgenrand_mt(0x33ff*generator_id.rr. (__local uint*)state). mts->wmask = mts_g[generator_id].B01-02632560-294 The OpenCL Programming Book 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117:} 118: } } mts->nn = mts_g[generator_id].maskC. num_rand.wmask.nn. mts->maskB = mts_g[generator_id]. /* Generate random numbers */ 119:/* Count the number of points within the circle */ 120:__kernel void calc_pi(__global uint *out. begin.umask. end. mts->shiftB = mts_g[generator_id]. int i. int num_rand_all. __local uint *count_per_wi) { int gid = get_group_id(0). mts->rr = mts_g[generator_id].
/* Process 128 elements at a time */ for (i=begin. y. /* Distance from the origin */ if (len < 1) { /* sqrt(len) < 1 = len < 1 */ count++. y. /* x coordinate */ y = ((float)(rand[i]&0xffff))/65535.0f. } } /* Process the remaining elements */ if ((i + lid) < end) { float x. // Compute the reference address corresponding to the local ID rand += lid. i+=128) { float x. x = ((float)(rand[i]>>16))/65535. i<end-128.0f. /* y coordinate */ len = (x*x + y*y). /* Wait until all work-items are finished */ 243 . /* Distance from the origin*/ if (len < 1) { /* sqrt(len) < 1 = len < 1 */ count++. /* y coordinate */ len = (x*x + y*y). x = ((float)(rand[i]>>16))/65535.B01-02632560-294 The OpenCL Programming Book 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: if (end > num_rand_all) end = num_rand_all. len.0f. } } count_per_wi[lid] = count. len.0f. /* Sum the counters from each work-item */ barrier(CLK_LOCAL_MEM_FENCE). /* x coordinate */ y = ((float)(rand[i]&0xffff))/65535.
for (i=0. i++) { count += count_per_wi[i]. } 244 . i < 128. /* Sum the counters */ } out[gid] = count.B01-02632560-294 The OpenCL Programming Book 169: 170: 171: 172: 173: 174: 175: 176:} if (lid == 0) { int count = 0.
. 948. 245 .. Reston.nvidia. it is common for the device to not run an OS. In AFIPS Conference Proceedings vol. 10:. 13: At present. but this will require calls to multiple CUDA-specific library functions. 483-485.ibm. (2) Because of the limited memory.html 9: The kernel can be executed without using the <<<>>> constructor. 12: Some reasons for this requirement are (1) Each processor on the device is often only capable of running small programs. pp.M.top500.org/wiki/Parallel_computing 2: Flynn. IEEE Trans.com/object/cuda_home.com/en-us/articles/optimizing-software-applications-for-numa/ 6: Amdahl. The OpenCL implementation should be chosen wisely depending on the platform.. Validity of the single-processor approach to achieving large scale computing capabilities. This is actually beneficial. Some Computer Organizations and Their Effectiveness.com/design/pentium/datashts/242016. due to limited accessible memory. Va. 1972. 8:. Comput.wikipedia. This should be kept in mind when programming a platform with multiple devices from different chip vendors. 1967.com/developerworks/power/cell/index.. Apr. 18-20). Chapter 2 7: NVIDIA uses the term "GPGPU computing" when referring to performing general-purpose computations through the graphics API. AFIPS Press.intel. pp.. The term "GPU computing" is used to refer to performing computation using CUDA or OpenCL. and an OpenCL runtime library by another company. N. M. 30 (Atlantic City.html 11: The devices that can be used depend on the OpenCL implementation by that company.. 3: TOP500 Supercomputer Sites.org 4: Intel MultiProcessor Specification. This text will use the term "GPGPU" to refer to any general-purpose computation performed on the GPU.B01-02632560-294 The OpenCL Programming Book Notes Chapter 1 1: Wikipedia. C-21. as it allows the processors to concentrate on just the computations. Vol. 5:. G. it is not possible to use an OpenCL compiler by one company.
this only allows the kernel to read from the specified address space. Chapter 6 18: 19:. each kernel would have to be compiled independently.3. the host is only allowed access to either the global memory or the constant memory on the device. but it is most probable that this would be the case. If the "CL_MEM_READ_ONLY" is specified.com/compute/cuda/2_3/toolkit/docs/NVIDIA_CUDA_Progra mming_Guide_2. Chapter 5 16: The OpenCL specification does not state that the local memory will correspond to the scratch-pad memory. Victor Podlozhnyuk.nvidia. each containing corresponding number of DC parameters. 17: At the time of this writing (Dec 2009). as one only need to know that three variables are declared with the names "mts128". "mts512". but the image objects are not supported. 15: Otherwise. the Mac OS X OpenCL returns CL_TRUE.pdf 20: The "mts. Also. and does not imply that the buffer would be created in the constant memory. Also.download.B01-02632560-294 The OpenCL Programming Book Chapter 4 14: The flag passed in the 2nd argument only specifies how the kernel-side can access the memory space. "mts256". for those experienced in CUDA.h" is not explained here. as it corresponds to the shared memory. Parallel Mersenne Twister 246 . note that the OpenCL local memory does not correspond with the CUDA local memory.
|
https://www.scribd.com/document/51894199/OpenCL-Programming
|
CC-MAIN-2017-39
|
en
|
refinedweb
|
. Once a cell, face, or edge becomes a parent it is no longer active. FlatManif.
A "coarse mesh" in deal.II is a triangulation object that consists only of cells that are not refined, i.e., a mesh in which no cell is a child of another cell. This is generally how triangulations are first constructed in deal.II, for example using (most of) the functions in namespace GridGenerator, the functions in class GridIn, or directly using the function Triangulation::create_triangulation(). One can of course do computations on such meshes, but most of the time (see, for example, almost any of the tutorial programs) one first refines the coarse mesh globally (using Triangulation::refine_global()), or adaptively (in that case first computing a refinement criterion, then one of the functions in namespace GridRefinement, and finally calling Triangulation::execute_coarsening_and_refinement()). The mesh is then no longer a "coarse mesh", but a "refined mesh".
In some contexts, we also use the phrase "the coarse mesh of a triangulation", and by that mean that set of cells that the triangulation started out with, i.e., from which all the currently active cells of the triangulation have been obtained by mesh refinement. (Some of the coarse mesh cells may of course also be active if they have never been refined.)
Triangulation objects store cells in levels: in particular, all cells of a coarse mesh are on level zero. Their children (if we executed
Triangulation::refine_global(1) on a coarse mesh) would then be at level one, etc. The coarse mesh of a triangulation (in the sense of the previous paragraph) then consists of exactly the level-zero cells of a triangulation. (Whether they are active (i.e., have no children) or have been refined is not important for this definition.)
Most of the triangulation classes in deal.II store the entire coarse mesh along with at least some of the refined cells. (Both the Triangulation and parallel::shared::Triangulation classes actually store all cells of the entire mesh, whereas some other classes such as parallel::distributed::Triangulation only store some of the active cells on each process in a parallel computation.) In those cases, one can query the triangulation for all coarse mesh cells. Other triangulation classes (e.g., parallel::fullydistributed::Triangulation) only store a part of the coarse mesh. See also the concept of coarse cell ids for that case.
Most of the triangulation classes in deal.II, notably Triangulation, parallel::shared::Triangulation, and parallel::distributed::Triangulation, store the entire coarse mesh of a triangulation on each process of a parallel computation. On the other hand, this is not the case for other classes, notably for parallel::fullydistributed::Triangulation, which is designed for cases where even the coarse mesh is too large to be stored on each process and needs to be partitioned.
In those cases, it is often necessary in algorithms to reference a coarse mesh cell uniquely. Because the triangulation object on the current process does not actually store the entire coarse mesh, one needs to have a globally unique identifier for each coarse mesh cell that is independent of the index within level zero of the triangulation stored locally. This globally unique ID is called the "coarse cell ID". It can be accessed via the function call
where
triangulation is the triangulation to which the iterator
coarse_cell pointing to a cell at level zero belongs. Here,
coarse_cell->index() returns the index of that cell within its refinement level (see TriaAccessor::index()). This is a number between zero and the number of coarse mesh cells stored on the current process in a parallel computation; it uniquely identifies a cell on that parallel process, but different parallel processes may use that index for different cells located at different coordinates.
For those classes that store all coarse mesh cells on each process, the Triangulation::coarse_cell_index_to_coarse_cell_id() simply returns a permutation of the possible argument values. In the simplest cases, such as for a sequential or a parallel shared triangulation, the function will in fact simply return the value of the argument. For others, such as parallel::distributed::Triangulation, the ordering of coarse cell IDs is not the same as the ordering of coarse cell indices. Finally, for classes such as parallel::fullydistributed::Triangulation, the function returns the globally unique ID, which is from a larger set of possible indices than the indices of the coarse cells actually stored on the current process.
Colorization is the process of marking certain parts of a Triangulation with different labels. The use of the word color comes from cartography, where countries on a map are made visually distinct from each other by assigning them different colors. Using the same term coloring is common in mathematics, even though we assign integers and not hues to different regions. deal.II refers to two processes as coloring:
colorize. This argument controls whether or not the different parts of the boundary will be assigned different boundary indicators. Some functions also assign different material indicators as well., AffineConstraints, ...).
dimand
spacedim
Many classes and functions in deal.II have two template parameters,
dim and
spacedim. An example is the basic Triangulation class:
In all of these contexts where you see
dim and
spacedim referenced, these arguments have the following meaning:
dim denotes the dimensionality of the mesh. For example, a mesh that consists of line segments is one-dimensional and consequently corresponds to
dim==1. A mesh consisting of quadrilaterals then has
dim==2 and a mesh of hexahedra has
dim==3.
spacedimdenotes the dimensionality of the space in which such a mesh lives. Generally, one-dimensional meshes live in a one-dimensional space, and similarly for two-dimensional and three-dimensional meshes that subdivide two- and three-dimensional domains. Consequently, the
spacedimtemplate argument has a default equal to
dim. But this need not be the case: For example, we may want to solve an equation for sediment transport on the surface of the Earth. In this case, the domain is the two-dimensional surface of the Earth (
dim==2) that lives in a three-dimensional coordinate system (
spacedim==3).
More generally, deal.II can be used to solve partial differential equations on manifolds that are embedded in higher dimensional space. In other words, these two template arguments need to satisfy
dim <= spacedim, though in many applications one simply has
dim == spacedim.
Following the convention in geometry, we say that the "codimension" is defined as
spacedim-dim. In other words, a triangulation consisting of quadrilaterals whose coordinates are three-dimensional (for which we would then use a
Triangulation<2,3> object) has "codimension one".
Examples of uses where these two arguments are not the same are shown in step-34, step-38, step-54.
The term "degree of freedom" (often abbreviated as "DoF") problem moving or distorting a mesh by a relatively large amount.
If the appropriate flag is given upon creation of a triangulation, the function Triangulation::create_triangulation, which is called by the various functions in GridGenerator and GridIn (but can also be called from user code, see step-14 and the example at the end of step-49), function GridTools::fix_up_distorted_child_cells can, in some cases, fix distorted cells on refined meshes by moving around the vertices of a distorted child cell that has an undistorted.
"Generalized support points" are, as the name suggests, a generalization of support points. The latter are used to describe that a finite element simply interpolates values at individual points (the "support points"). If we call these points \(\hat{\mathbf{x}}_i\) (where the hat indicates that these points are defined on the reference cell \(\hat{K}\)), then one typically defines shape functions \(\varphi_j(\mathbf{x})\) in such a way that the nodal functionals \(\Psi_i[\cdot]\) simply evaluate the function at the support point, i.e., that \(\Psi_i[\varphi]=\varphi(\hat{\mathbf{x}}_i)\), and the basis is chosen so that \(\Psi_i[\varphi_j]=\delta_{ij}\) where \(\delta_{ij}\) is the Kronecker delta function. This leads to the common Lagrange elements.
(In the vector valued case, the only other piece of information besides the support points \(\hat{\mathbf{x}}_i\) that one needs to provide is the vector component \(c(i)\) the \(i\)th node functional corresponds, so that \(\Psi_i[\varphi]=\varphi(\hat{\mathbf{x}}_i)_{c(i)}\).)
On the other hand, there are other kinds of elements that are not defined this way. For example, for the lowest order Raviart-Thomas element (see the FE_RaviartThomas class), the node functional evaluates not individual components of a vector-valued finite element function with
dim components, but the normal component of this vector: \(\Psi_i[\varphi] = \varphi(\hat{\mathbf{x}}_i) \cdot \mathbf{n}_i \), where the \(\mathbf{n}_i\) are the normal vectors to the face of the cell on which \(\hat{\mathbf{x}}_i\) is located. In other words, the node functional is a linear combination of the components of \(\varphi\) when evaluated at \(\hat{\mathbf{x}}_i\). Similar things happen for the BDM, ABF, and Nedelec elements (see the FE_BDM, FE_ABF, FE_Nedelec classes).
In these cases, the element does not have support points because it is not purely interpolatory; however, some kind of interpolation is still involved when defining shape functions as the node functionals still require point evaluations at special points \(\hat{\mathbf{x}}_i\). In these cases, we call the points generalized support points.
Finally, there are elements that still do not fit into this scheme. For example, some hierarchical basis functions (see, for example the FE_Q_Hierarchical element) are defined so that the node functionals are moments of finite element functions, \(\Psi_i[\varphi] = \int_{\hat{K}} \varphi(\hat{\mathbf{x}}) {\hat{x}_1}^{p_1(i)} {\hat{x}_2}^{p_2(i)} \) in 2d, and similarly for 3d, where the \(p_d(i)\) are the order of the moment described by shape function \(i\). Some other elements use moments over edges or faces. In all of these cases, node functionals are not defined through interpolation at all, and these elements then have neither support points, nor generalized support points.
The "geometry paper" is a paper by L. Heltai, W. Bangerth, M. Kronbichler, and A. Mola, titled "Using exact geometry information in finite element computations", that describes how deal.II describes the geometry of domains. In particular, it discusses the algorithmic foundations on which the Manifold class is based, and what kind of information it needs to provide for mesh refinement, the computation of normal vectors, and the many other places where geometry enters into finite element computations.
The paper is currently available on arXiv at . The full reference for this paper is as follows: and the parallel::shared::Triangulation classes. primary value somewhere else – thus, the name "ghost". This is also the case for the parallel::distributed::Vector class.
On the other hand, in Trilinos (and consequently in TrilinosWrappers::MPI::Vector), a ghosted vector is simply a view of the parallel vector where the element distributions overlap. The 'ghosted' Trilinos vector in itself has no idea of which entries are ghosted and which are locally owned. In fact, a ghosted vector may not even store all of the elements a non-ghosted vector would store on the current processor. Consequently, for Trilinos vectors, there is no notion of an 'owner' of vector elements in the way we have it in the primary::flat. In practice, the material id of a cell is typically used to identify which cells belong to a particular part of the domain, e.g., when you have different materials (steel, concrete, wood) that are all part of the same domain. One would then usually query the material id associated with a cell during assembly of the bilinear form, and use it to determine (e.g., by table lookup, or a sequence of if-else statements) what the correct material coefficients would be for that cell.
This material_id may be set upon construction of a triangulation (through the CellData data structure), or later through use of cell iterators. For a typical use of this functionality, see the step-28 tutorial program. The functions of the GridGenerator namespace typically set the material ID of all cells to zero. When reading a triangulation through the GridIn class, different input file formats have different conventions, but typically either explicitly specify the material id, or if they don't, then GridIn simply sets them to zero. Because the material of a cell is intended to pertain to a particular region of the domain, material ids are inherited by child cells from their element as a triple \((K,P,\Psi)\) where
This definition of what a finite element is has several advantages, concerning analysis as well as implementation. For the analysis, it means that conformity with certain spaces (FiniteElementData::Conformity), e.g. continuity, is up to the node functionals. In deal.II, it helps simplifying the implementation of more complex elements like FE_RaviartThomas considerably.
Examples for node functionals are values in support points and moments with respect to Legendre polynomials. Examples:
The construction of finite elements as outlined above allows writing code that describes a finite element simply by providing a polynomial space (without having to give it any particular basis – whatever is convenient is entirely sufficient) and the nodal functionals. This is used, for example in the FiniteElement::convert_generalized_support_point_values_to_dof_values() function. 100,000,000::get_unit_support_points(), such that the function FiniteElement:.
The "Z order" of cells describes an order in which cells are traversed.
By default, if you write a loop over all cells in deal.II, the cells will be traversed in an order where coarser cells (i.e., cells that were obtained from coarse mesh cells with fewer refinement steps) come before cells that are finer (i.e., cells that were obtained with more refinement steps). Within each refinement level, cells are traversed in an order that has something to do with the order in which they were created; in essence, however, this order is best of thought of as "unspecified": you will visit each cell on a given refinement level exactly once, in some order, but you should not make any assumptions about this order.
Because the order in which cells are created factors into the order of cells, it can happen that the order in which you traverse cells is different for two identical meshes. For example, think of a 1d (coarse) mesh with two cells: If you first refine the first of these cells and then the other, then you will traverse the four cells on refinement level 1 in a different order than if you had first refined the second coarse cell and then the first coarse cell.
This order is entirely practical for almost all applications because in most cases, it does not actually matter in which order one traverses cells. Furthermore, it allows using data structures that lead to particularly low cache miss frequencies and are therefore efficient for high performance computing applications.
On the other hand, there are cases where one would want to traverse cells in a particular, specified and reproducible order that only depends on the mesh itself, not its creation history or any other seemingly arbitrary design decisions. The "Z order" is one way to achieve this goal.
To explain the concept of the Z order, consider the following sequence of meshes (with each cell numbered using the "level.index" notation, where "level" is the number of refinements necessary to get from a coarse mesh cell to a particular cell, and "index" the index of this cell within a particular refinement level):
Note how the cells on level 2 are ordered in the order in which they were created. (Which is not always the case: if cells had been removed in between, then newly created cells would have filled in the holes so created.)
The "natural" order in which deal.II traverses cells would then be 0.0 -> 1.0 -> 1.1 -> 1.2 -> 1.3 -> 2.0 -> 2.1 -> 2.2 -> 2.3 -> 2.4 -> 2.5 -> 2.6 -> 2.7. (If you want to traverse only over the active cells, then omit all cells from this list that have children.) This can be thought of as the "lexicographic" order on the pairs of numbers "level.index", but because the index within each level is not well defined, this is not a particularly useful notion. Alternatively, one can also think of it as one possible breadth-first traversal of the tree that corresponds to this mesh and that represents the parent-child relationship between cells:
On the other hand, the Z order corresponds to a particular depth-first traversal of the tree. Namely: start with a cell, and if it has children then iterate over these cell's children; this rule is recursively applied as long as a child has children.
For the given mesh above, this yields the following order: 0.0 -> 1.0 -> 2.4 -> 2.5 -> 2.6 -> 2.7 -> 1.1 -> 1.2 -> 1.3 -> 1.4 -> 2.0 -> 2.1 -> 2.2 -> 2.3. (Again, if you only care about active cells, then remove 0.0, 1.0, and 1.3 from this list.) Because the order of children of a cell is well defined (as opposed to the order of cells within each level), this "hierarchical" traversal makes sense and is, in particular, independent of the history of a triangulation.
In practice, it is easily implemented using a recursive function:
This function is then called as follows:
Finally, as an explanation of the term "Z" order: if you draw a line through all cells in the order in which they appear in this hierarchical fashion, then it will look like a left-right inverted Z on each refined cell. Indeed, the curve so defined can be thought of a space-filling curve and is also sometimes called "Morton ordering", see .
|
https://dealii.org/developer/doxygen/deal.II/DEALGlossary.html
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
Composable Resources
In this tutorial, we're going to walkthrough.
For additional support, see the Playground Manual
Resources Owning Resources.
Resources Owning Resources: An Example
// The KittyVerse contract defines two types of NFTs. // One is a KittyHat, which represents a special hat, and // the second is the Kitty resource, which can own Kitty Hats. // // You can put the hats on the cats and then call a hat function // that tips the hat and prints a fun message. // // This is a simple example of how Cadence supports // extensibility for smart contracts, but the language will soon // support even more powerful versions of this. pub contract KittyVerse { // KittyHat is a special resource type that represents a hat pub resource KittyHat { pub let id: Int pub let name: String init(id: Int, name: String) { self.id = id self.name = name } // An example of a function someone might put in their hat resource pub fun tipHat(): String { if self.name == "Cowboy Hat" { return "Howdy Y'all" } else if self.name == "Top Hat" { return "Greetings, fellow aristocats!" } return "Hello" } } // Create a new hat pub fun createHat(id: Int, name: String): @KittyHat { return <-create KittyHat(id: id, name: name) } pub resource Kitty { pub let id: Int // place where the Kitty hats are stored pub let items: @{String: KittyHat} init(newID: Int) { self.id = newID self.items <- {} } destroy() { destroy self.items } } pub fun createKitty(): @Kitty { return <-create Kitty(newID: 1) } }
These definitions show how a Kitty resource could own hats.
The hats are stored in a variable in the Kitty resource.
// place where the Kitty hats are stored pub:
import KittyVerse from 0x01 // This transaction creates a new kitty, creates two new hats and // puts the hats on the cat. Then it stores the kitty in account storage. transaction { prepare(acct: AuthAccount) { // Create the Kitty object let kitty <- KittyVerse.createKitty() // Create the KittyHat objects let hat1 <- KittyVerse.createHat(id: 1, name: "Cowboy Hat") let hat2 <- KittyVerse.createHat(id: 2, name: "Top Hat") // Put the hat on the cat! let oldCowboyHat <- kitty.items["Cowboy Hat"] <- hat1 destroy oldCowboyHat let oldTopHat <- kitty.items["Top Hat"] <- hat2 destroy oldTopHat log("The cat has the hats") // Store the Kitty in storage acct.save<@KittyVerse.Kitty>(<-kitty, to: /storage/Kitty) } }
You should see an output that looks something like:
import KittyVerse from 0x01 // This transaction moves a kitty out of storage, // takes the cowboy hat off of the kitty, // calls its tip hat function, and then moves it back into storage. transaction { prepare(acct: AuthAccount) { // Move the Kitty out of storage, which also moves its hat along with it let kitty <- acct.load<@KittyVerse.Kitty>(from: /storage/Kitty)! // Take the cowboy hat off the Kitty let cowboyHat <- kitty.items.remove(key: "Cowboy Hat")! // Tip the cowboy hat log(cowboyHat.tipHat()) destroy cowboyHat // Tip the top hat that is on the Kitty log(kitty.items["Top Hat"]?.tipHat()) // Move the Kitty to storage, which // also moves its hat along with it. acct.save<@KittyVerse.Kitty>(<-kitty, to: /storage/Kitty) } }
You should see something like this output:
> "Howdy Y'all" > "Greetings, fellow aristocats!"
Whenever the Kitty is moved, its hats are implicitly moved along with it. This is because the hats are owned by the Kitty.
The Future is Meow! Extensibility is coming!!
|
https://docs.onflow.org/tutorial/cadence/07-resources-compose/
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
Fungible Tokens
In this tutorial, we're going to deploy, store, and transfer fungible tokens.
The tutorial will be asking you to take various actions to interact with this code.
Some of the most popular contract classes on blockchains today are fungible tokens. These contracts create homogeneous tokens that can be transferred to other users and spent as currency (e.g., ERC-20 on Ethereum).
Usually, a central ledger keeps track of a user's token balances. With Cadence, we use a new resource paradigm to implement fungible tokens and avoid using a central ledger.
Flow Network Token
In Flow, the native network token will be implemented as a normal fungible token smart contract using a smart contract similar to the one in this tutorial. There will be special contracts and hooks that allow it be used for transaction execution payments and staking, but besides that, developers and users will be able to treat it and use it just like any other token in the network!
We're going to take you through these steps to get comfortable with the fungible token:
- Deploy the fungible token contract to account
0x01
- Create a fungible token object and store it in your account storage.
- Create a reference to your tokens that others can use to send you tokens.
- Set up another account the same way.
- Transfer tokens from one account to another.
- Use a script to read the accounts' balances.
Before proceeding with this tutorial, we recommend following the instructions in Getting Started and Hello, World! to learn the basics of the language and the playground.
Fungible Tokens on the Flow Emulator
Open the account
0x01 tab to see the file named
FungibleToken.cdc.
FungibleToken.cdc should contain the full code for the
fungible token, which provides the core functionality to store fungible tokens
in your account and transfer to and accept tokens from other users.
The concepts involved in implementing a fungible token in Cadence can be hard to grasp at first. For an in-depth explanation of this functionality and code, continue reading the next section.
Or, if you'd like to go immediately into deploying it and using it in the playground, you can skip to the Interacting with the Fungible Token section of this tutorial.
Fungible Tokens: An In-Depth Exploration
How Flow implements fungible tokens is different from other programming languages. As a result:
- Ownership is decentralized and does not rely on a central ledger
- Bugs and exploits present less risk for users and less opportunity for attackers
- There is no risk of integer underflow or overflow
- Assets cannot be duplicated, and it is very hard for them to be lost, stolen, or destroyed
- Code can be composable
- Rules can be immutable
- Code is not unintentionally made public
Decentralizing Ownership
Instead of using a central ledger system, Flow ties ownership to each account via a new paradigm for asset ownership. The example below showcases how Solidity implements fungible tokens, with only the code for storage and transferring tokens shown for brevity.
contract ERC20 { mapping (address => uint256) private _balances; function _transfer(address sender, address recipient, uint256 amount) { // ensure the sender has a valid balance require(_balances[sender] >= amount); // subtract the amount from the senders ledger balance _balances[sender] = _balances[sender] - amount; // add the amount to the recipient’s ledger balance _balances[recipient] = _balances[recipient] + amount } }
As you can see, Solidity uses a central ledger system for its fungible tokens. There is one contract that manages the state of the tokens and every time that a user wants to do anything with their tokens, they have to interact with the central ERC20 contract, calling its functions to update their balance. This contract handles access control for all functionality, implements all of its own correctness checks, and enforces rules for all of its users.
Instead of using a central ledger system, Flow utilizes a few different concepts to provide better safety, security, and clarity for smart contract developers and users. In this section, we'll show how Flow's resources, interfaces, and other features are employed via a fungible token example.
Intuiting Ownership with Resources
An important concept in Cadence is Resources, which are linear types. A resource is a composite type that has its own defined fields and functions, similar to a struct. The difference is that resource objects have special rules that keep them from being copied or lost. Resources are a new paradigm for asset ownership. Instead of representing token ownership in a central ledger smart contract, each account owns a resource object in their account storage that records the number of tokens they own. This way, when users want to transact with each other, they can do so peer-to-peer without having to interact with a central token contract. To transfer tokens to each other, they call a
transfer function on their own resource object and other users' resources, instead of a central
transfer function.
This approach simplifies access control because instead of a central contract having to check the sender of a function call, most function calls happen on resource objects stored in users' account, and each user controls who is able to call the functions on resources in their account. This concept, called Capability-based security, will be explained more in a later section.
This approach also helps protect against potential bugs. In a Solidity contract with all the logic contained in a central contract, an exploit is likely to affect all users who are involved in the contract. In Cadence, if there is a bug in the resource logic, an attacker would have to exploit the bug in each token holders account individually, which is much more complicated and time-consuming than it is in a central ledger system.
Below is an example of a resource for a fungible token vault. Every user who owns these tokens would have this resource stored in their account. It is important to remember that each account stores only a copy of the
Vault resource, and not a copy of the entire
FungibleToken contract. The
FungibleToken contract only needs to be stored in the initial account that manages the token definitions.
pub resource Vault: Provider, Receiver { // Balance of a user's Vault // we use unsigned integers for balances because they do not require the // concept of a negative number pub var balance: UFix64 init(balance: UFix64) { self.balance = balance } pub fun withdraw(amount: UFix64): @Vault { self.balance = self.balance - amount return <-create Vault(balance: amount) } pub fun deposit(from: @Vault) { self.balance = self.balance + from.balance destroy from } }
This piece of code is for educational purposes and is not comprehensive. However, it still showcases how a resource for a token works. Each token resource object has a balance and associated functions (e.g.,
deposit,
withdraw, etc). When a user wants to use these tokens, they instantiate a zero-balance copy of this resource in their account storage. The language requires that the initialization function
init, which is only run once, must initialize all member variables.
// Balance of a user's Vault // we use unsigned fixed-point integers for balances because they do not require the // concept of a negative number and allow for more clear precision pub var balance: UFix64 init(balance: UFix64) { self.balance = balance }
Then, the deposit function can be available for any account to transfer tokens to.
pub fun deposit(from: @Vault) { self.balance = self.balance + from.balance destroy from }
When an account wants to send tokens to a different account, the sending account calls their own withdraw function first, which subtracts tokens from their resource’s balance and temporarily creates a new resource object that holds this balance. The sending account then calls the recipient account’s deposit function, which literally moves the resource instance to the other account, adds it to their balance, and then destroys the used resource. The resource needs to be destroyed because Cadence enforces strict rules around resource interactions. A resource can never be left hanging in a piece of code. It either needs to be explicitly destroyed or stored in an account's storage.
When interacting with resources, you will use the
@ symbol and a special “move operator”
<-.
pub fun withdraw(amount: UInt64): @Vault {
This
@ symbol is required when specifying a resource type for a field, an argument, or a return value. The move operator
<- makes it clear that when a resource is used in an assignment, parameter, or return value, it is moved to a new location and the old location is invalidated. This ensures that the resource only ever exists in one location at a time.
If a resource is moved out of an account's storage, it either needs to be moved to an account’s storage or explicitly destroyed.
destroy from
This line ensures that resources, which often represent real value, do not get lost because of a coding error.
You’ll notice that the arithmetic operations aren't explicitly protected.
self.balance = self.balance - amount
In Solidity, this could be a risk for integer overflow or underflow, but Cadence has built-in overflow and underflow protection, so it is not a risk. We are also using unsigned integers in this example, so the vault`s balance cannot go below 0.
Additionally, the requirement that an account contains a copy of the token’s resource type in its storage ensures that funds cannot be lost by being sent to the wrong address. If an address doesn’t have the correct resource type imported, the transaction will revert, ensuring that transactions sent to the wrong address are not lost.
The line in
withdraw that creates a new
Vault has the parameter name
balance specified in the function call.
return <-create Vault(balance: amount)
This is another feature that Cadence has to improve the clarity of code. All function calls are required to specify the names of the arguments they are sending unless the developer has specifically overridden it.
Ensuring Security in Public: Capability Security
Another important feature in Cadence is its utilization of Capability Security. This feature ensures that, while the withdraw function is public, no one except the intended user and those they approve of can withdraw tokens from their vault.
Cadences security model ensures that objects stored in an account's storage can only be accessed by the account that owns them. If a user wants to give another user access to their stored objects, they can publish a reference, which is like an "API" that allows others to call specified functions on their objects.
An account only has access to the fields and methods of an object in a different account if they own a reference to that object that explicitly allows them to access those fields and methods. Only the owner of an object can create a reference for it. Therefore, when a user creates a Vault in their account, they only publish references to the deposit function and the balance. The withdraw function can remain hidden as a function that only the owner can call.
As you can hopefully see, this removes the need to check
msg.sender for access control purposes, because this functionality is handled by the protocol and type checker. If you aren't the owner of an object or don't have a valid reference to it that was created by the owner, you cannot access the object at all!
Using Interfaces to Secure Implementations
The next important concept in Cadence is design-by-contract, which uses preconditions and postconditions to document and programmatically assert the change in state caused by a piece of a program. These conditions are specified in interfaces that enforce rules about how types are defined and behave. They can be stored on-chain in an immutable fashion so that certain pieces of code can import and implement them to ensure that they meet certain standards.
Here is an example of how interfaces for the
Vault resource we defined above would look.
// Interface that enforces the requirements for withdrawing // tokens from the implementing type // pub resource interface Provider { pub fun withdraw(amount: UFix64): @Vault { post { result.balance == amount: "Withdrawal amount must be the same as the balance of the withdrawn Vault" } } } // Interface that enforces the requirements for depositing // tokens into the implementing type // pub resource interface Receiver { pub fun deposit(from: @Vault) { pre { from.balance > UFix64(0): "Deposit balance must be positive" } } }
In our example, the
Vault resource would implement both of these interfaces. The interfaces ensure that specific fields and functions are present in the resource implementation and that those functions meet certain conditions before and/or after execution. These interfaces can be stored on-chain and imported into other contracts or resources so that these requirements are enforced by an immutable source of truth that is not susceptible to human error.
You can also see that functions and fields have the
pub keyword next to them. We have explicitly defined these fields as public because all fields and functions in Cadence are private by default, meaning that the local scope can only access them. Users have to make parts of their owned types explicitly public. This helps prevent types from having unintentionally public code.
Interacting with the Fungible Token in the Flow Playground
Now that you have read about how the Fungible Token works, we can deploy it to your account and send some transactions to interact with it.
Make sure that you have opened the Fungible Token templates in the playground
by following the link at the top of this page. You should have Account
0x01
open and should see the code below.
pub contract FungibleToken { // Total supply of all tokens in existence. pub var totalSupply: UFix64 // Provider // // Interface that enforces the requirements for withdrawing // tokens from the implementing type. // // We don't enforce requirements on self.balance here because // it leaves open the possibility of creating custom providers // that don't necessarily need their own balance. // pub resource interface Provider { // withdraw // // Function that subtracts tokens from the owner's Vault // and returns a Vault resource (@Vault) with the removed tokens. // // The function's access level is public, but this isn't a problem // because even the public functions are not fully public at first. // anyone in the network can call them, but only if the owner grants // them access by publishing a resource that exposes the withdraw // function. // pub fun withdraw(amount: UFix64): @Vault { post { // `result` refers to the return value of the function result.balance == UFix64(amount): "Withdrawal amount must be the same as the balance of the withdrawn Vault" } } } // Receiver // // Interface that enforces the requirements for depositing // tokens into the implementing type. // // We don't include a condition that checks the balance because // we want to give users the ability to make custom Receivers that // can do custom things with the tokens, like split them up and // send them to different places. // pub resource interface Receiver { // deposit // // Function that can be called to deposit tokens // into the implementing resource type // pub fun deposit(from: @Vault) { pre { from.balance > UFix64(0): "Deposit balance must be positive" } } } // Balance // // Interface that specifies a public `balance` field for the vault // pub resource interface Balance { pub var balance: UFix64 } // Vault // // Each user stores an instance of only the Vault in their storage // The functions in the Vault and governed by the pre and post conditions // in the interfaces when they are called. // The checks happen at runtime whenever a function is called. // // Resources can only be created in the context of the contract that they // are defined in, so there is no way for a malicious user to create Vaults // out of thin air. A special Minter resource needs to be defined to mint // new tokens. // pub resource Vault: Provider, Receiver, Balance { // keeps track of the total balance of the account's tokens pub var balance: UFix64 // initialize the balance at resource creation time init(balance: UFix64) { self.balance = balance } // withdraw // // Function that takes an integer amount as an argument // and withdraws that amount from the Vault. // // It creates a new temporary Vault that is used to hold // the money that is being transferred. It returns the newly // created Vault to the context that called so it can be deposited // elsewhere. // pub fun withdraw(amount: UFix64): @Vault { self.balance = self.balance - amount return <-create Vault(balance: amount) } // deposit // // Function that takes a Vault object as an argument and adds // its balance to the balance of the owners Vault. // // It is allowed to destroy the sent Vault because the Vault // was a temporary holder of the tokens. The Vault's balance has // been consumed and therefore can be destroyed. pub fun deposit(from: @Vault) { self.balance = self.balance + from.balance destroy from } } // createEmptyVault // // Function that creates a new Vault with a balance of zero // and returns it to the calling context. A user must call this function // and store the returned Vault in their storage in order to allow their // account to be able to receive deposits of this token type. // pub fun createEmptyVault(): @Vault { return <-create Vault(balance: UFix64(0)) } // VaultMinter // // Resource object that an admin can control to mint new tokens pub resource VaultMinter { // init function for the contract. All fields in the contract must // be initialized at deployment. This is just an example of what // an implementation could do in the init function. The numbers are arbitrary. init() { self.totalSupply = UFix64(30) //) // Create a new VaultMinter resource and store it in account storage self.account.save(<-create VaultMinter(), to: /storage/MainMinter) } }
Click the
Deploy button at the bottom right of the editor to deploy the code.
This deployment stores the contract for the fungible token in your active account (account
0x01) so that it can be imported into transactions.
A contract's
init function runs at contract creation, and never again afterwards. In our example, this function stores an instance of the
Vault object with an initial balance of 30, and stores the
VaultMinter object that you can use to mint new tokens.
//)
This line saves the new
@Vault object to storage.
Account storage is indexed with paths, which consist of a domain and identifier.
/domain/identifier. Only three domains are allowed for paths:
storage: The place where all objects are stored. Only accessible by the owner of the account.
private: Stores links, otherwise known as capabilities, to objects in storage. Only accessible by the owner of the account
public: Stores links to objects in storage: Accessible by anyone in the network.
Contracts have access to the private
AuthAccount object of the account it is stored in, using
self.account. This object has methods that can modify storage in many ways. See the glossary documentation for a list of all the methods it can call.
In this line, we call the
save method to store an object in storage, specifying
@Vault as the type of the value we are storing. The first argument is the value to store, and the second argument is the path where the value is being stored. For
save the path has to be in the
/storage domain.
We also store the
VaultMinter object to
/storage/ in the next line in the same way:
self.account.save(<-create VaultMinter(), to: /storage/MainMinter)
You should also see that the
FungibleToken.Vault and
FungibleToken.VaultMinter resource objects are stored in the account storage. This will be shown in the Resources box at the bottom of the screen.
You are now ready to run transactions that use the fungible tokens!
Create, Store, and Publish Capabilities and References to a Vault
References are like pointers in other languages. They are a link to an object in an account's storage and can be used to read fields or call functions on the object they reference. They cannot move or modify the object directly.
There are many different situations in which you would create a reference to your fungible token vault. You might want a simple way to call methods on your
Vault from anywhere in a transaction. You could also send a resource that only includes a reference to the withdraw function in the
Vault so that others can transfer tokens for you. There could also be a function that takes a reference to a
Vault as an argument, makes a single function call on the reference, then finishes and destroys the reference. This scenario will probably be where references are most often used. We already use this pattern in the
Vault resource in the
mintTokens function, shown here:
// function takes a reference to any resource that implements the
Receiver interface and uses the reference to call the
deposit function of that resource.
Let's create references to your
Vault so that a separate account can send tokens to you.
Open the transaction named
Transaction1.cdc.
Transaction1.cdc should contain the following code for creating a reference to the stored Vault:
import FungibleToken from 0x01 // This transaction creates a capability // that is linked to the account's token vault. // The capability is restricted to the fields in the `Receiver` interface, // so it can only be used to deposit funds into the account. transaction { prepare(acct: AuthAccount) { //) log("Public Receiver reference created!") }" } }
In order to use references, we have to first create a capability for an object, which is a link to that object in storage that cannot be used to read fields or call functions. A reference can then be created from a capability, and references cannot be stored. They need to be lost at the end of a transaction execution. This restriction is to prevent reentrancy attacks which are attacks where a malicious user calls into the same function over and over again before the original execution has finished. Only allowing one reference at a time for an object prevents these attacks for objects in storage.
To create a capability, we use the
link function.
//)
link creates a new capability that is kept at the path in the first argument, targeting the
target in the second argument. The type restriction for the link is specified in the
<>. We use
&FungibleToken.Vault{FungibleToken.Receiver, FungibleToken.Balance} to say that the link can be any resource as long as it implements and is cast as the Receiver interface. This is the common format for describing references. You first have a
& followed by the concrete type, then the interface in curly braces to ensure that it is a reference that implements that interface and only includes the fields specified in that interface.
We put the capability in
/public/MainReceiver because we want it to be publicly accessible. The
public domain of an account is accessible to anyone in the network via an account's
PublicAccount object, which is fetched by using the
getAccount(address) function.
Next is the
post phase of the transaction." }
The
post phase is for ensuring that certain conditions are met after the transaction has been executed. Here, we are getting the capability from its public path and calling its
check function to ensure that the capability contains a valid link to a valid object in storage.
You might also notice that we are using a
! symbol. This is to use the force-unwrap operator. When reading values from storage or creating capabilities, There is always the risk that the locations may be empty, so any function that interacts with them could potentially end up doing nothing if there isn't anything in that location. Optionals are types that can represent the absence of a value. Optionals have two cases: either there is a value of the specified type, or there is nothing. An optional type is declared using the
? suffix. Therefore, the possibility that the values are
nil must be handled. The force-unwrap operator
! allows us to get the value from the optional if it contains a value. If the value is
nil, then the execution of the program aborts.
Select account
0x01 as the only signer.
Click the
Send button to submit the transaction.
This transaction creates a new public reference to your
Vault and checks that it was created correctly.
Transfer Tokens to Another User
Now, we are going to run a transaction that sends 10 tokens to account
0x02. We will do this by calling the
withdraw function on account
0x01's Vault, which creates a temporary Vault object for moving the tokens, then deposit those tokens into account
0x02's account by calling their
deposit function.
Here we encounter another safety feature that Cadence introduces. Owning tokens requires you to have a
Vault object stored in your account, so if anyone tries to send tokens to an account who isn't prepared to receive them, the transaction will fail. This way, Cadence protects the user if they accidentally enter the account address incorrectly when sending tokens.
Account
0x02 has not been set up to receive tokens, so we will do that now:
Open the transaction
Transaction2.cdc.
Select account
0x02 as the only signer.
Click the
Send button to set up account
0x02 so that it can receive tokens.
import FungibleToken from 0x01 // This transaction configures an account to store and receive tokens defined by // the FungibleToken contract. transaction { prepare(acct: AuthAccount) { // Create a new empty Vault object let vaultA <- FungibleToken.createEmptyVault() // Store the vault in the account storage acct.save<@FungibleToken.Vault>(<-vaultA, to: /storage/MainVault) log("Empty Vault stored") // Create a public Receiver capability to the Vault let ReceiverRef = acct.link<&FungibleToken.Vault{FungibleToken.Receiver, FungibleToken.Balance}>(/public/MainReceiver, target: /storage/MainVault) log("References created") } post { // Check that the capabilities were created correctly getAccount(0x02).getCapability(/public/MainReceiver)! .check<&FungibleToken.Vault{FungibleToken.Receiver}>(): "Vault Receiver Reference was not created correctly" } }
Here we perform the same actions that account
0x01 did to set up its
Vault, but all in one transaction. Account
0x02 is ready to start building its fortune! As you can see, when we created the Vault for account
0x02, we had to create one with a balance of zero by calling the
createEmptyVault() function. Resource creation is restricted to the contract where it is defined, so in this way, the Fungible Token smart contract can ensure that nobody is able to create new tokens out of thin air.
As part of the initial deployment process for the FungibleToken contract, account
0x01 created a
VaultMinter object. By using this object, the account that owns it can mint new tokens. Right now, account
0x01 owns it, so it has sole power to mint new tokens. We could have had a
mintTokens function defined in the contract, but then we would have to check the sender of the function call to make sure that they are authorized.
As we explained before, the resource model plus capability security handles this access control for us as a built in language construct instead of having to be defined in the code. If account
0x01 wanted to authorize another account to mint tokens, they could either move the
VaultMinter object to the other account, or give the other account a private capability to the single
VaultMinter. Or, if they didn't want minting to be possible after deployment, they would simply mint all the tokens at contract initialization and not even include the
VaultMinter in the contract.
In the next transaction, account
0x01 will mint 30 new tokens and deposit them into account
0x02's newly created Vault.
Select only account
0x01 as a signer and send
Transaction3.cdc to mint 30 tokens for account
0x02.
Transaction3.cdc should contain the code below.
import FungibleToken from 0x01 // This transaction mints tokens and deposits them into account 2's vault transaction { // Local variable for storing the reference to the minter resource let mintingRef: &FungibleToken.VaultMinter // Local variable for storing the reference to the Vault of // the account that will receive the newly minted tokens var receiverRef: &FungibleToken.Vault{FungibleToken.Receiver} prepare(acct: AuthAccount) { // Borrow a reference to the stored, private minter resource self.mintingRef = acct.borrow<&FungibleToken.VaultMinter> (from: /storage/MainMinter) ?? panic("Could not borrow a reference to the minter") // Get the public account object for account 0x02 let recipient = getAccount(0x02) // Get the public receiver capability let cap = recipient.getCapability(/public/MainReceiver)! // Borrow a reference from the capability self.receiverRef = cap.borrow<&FungibleToken.Vault{FungibleToken.Receiver}>() ?? panic("Could not borrow a reference to the receiver") } execute { // Mint 30 tokens and deposit them into the recipient's Vault self.mintingRef.mintTokens(amount: UFix64(30), recipient: self.receiverRef) log("30 tokens minted and deposited to account 0x02") } }
This is the first example of a transaction where we utilize local transaction variables that span different stages in the transaction. We declare the
mintingRef and
receiverRef variables outside of the prepare stage but must initialize them in prepare. We can then use them in later stages in the transaction.
In addition to borrowing references from capabilities, you'll see in this transaction that you can also borrow a reference directly from an object in storage.
// Borrow a reference to the stored, private minter resource self.mintingRef = acct.borrow<&FungibleToken.VaultMinter> (from: /storage/MainMinter) ?? panic("Could not borrow a reference to the minter")
Here, we specify the borrow as a
VaultMinter reference and have the reference point to
/storage/MainMinter. The reference is borrowed as an optional so we use the nil-coalescing operator (
??) to make sure the value isn't nil. If the value is nil, the transaction will revert and print the error message.
You can use the
getAccount() built-in function to get any account's public account object. The public account object lets you get capabilities from the
public domain of an account, where public capabilities are stored.
We use the
getCapability function to get the public capability from a public path, then use the
borrow function on the capability to get the reference from it, typed as a
Vault{Receiver}.
// Get the public receiver capability let cap = recipient.getCapability(/public/MainReceiver)! // Borrow a reference from the capability self.receiverRef = cap.borrow<&FungibleToken.Vault{FungibleToken.Receiver}>() ?? panic("Could not borrow a reference to the receiver")
In the execute phase, we simply use the reference to mint 30 tokens and deposit them into the
Vault of account
0x02.
Check Account Balances
Now, both account
0x01 and account
0x02 should have a
Vault object in their storage that has a balance of 30 tokens. They both should also have a
Receiver capability stored in their
/public/ domains that links to their stored
Vault.
An account cannot receive any token type unless it is specifically configured to accept those tokens. As a result, it is difficult to send tokens to the wrong address accidentally. But, if you make a mistake setting up the
Vault in the new account, you won't be able to send tokens to it.
Let's run a script to make sure we have our vaults set up correctly.
You can use scripts to access an account's public state. Scripts aren't signed by any account and cannot modify state.
In this example, we will query the balance of each account's vault. The following will print out the balance of each account in the emulator.
Open the script named
Script1.cdc in the scripts pane.
Script1.cdc should contain the following code:
import FungibleToken from 0x01 // This script reads the Vault balances of two accounts. a reference to the acct1 receiver") let acct2ReceiverRef = acct2.getCapability(/public/MainReceiver)! .borrow<&FungibleToken.Vault{FungibleToken.Balance}>() ?? panic("Could not borrow a reference to the acct2 receiver") // Read and log balance fields log("Account 1 Balance") log(acct1ReceiverRef.balance) log("Account 2 Balance") log(acct2ReceiverRef.balance) }
Execute
Script1.cdc by clicking the Execute button.
This should ensure the following:
- Account
0x01's balance is 30
- Account
0x02's balance is 30
If correct, you should see the following lines:
"Account 1 Balance" 30 "Account 2 Balance" 30 Result > "void"
If there is an error, this probably means that you missed a step earlier and might need to rerun some of the previous transactions.
For help restarting the emulator from the beginning of this tutorial, see the Playground Manual
Now that we have two accounts, each with a
Vault, we can see how they transfer tokens to each other!
Open the transaction named
Transaction4.cdc.
Select account
0x02 as a signer and send the transaction.
Transaction4.cdc should contain the following code for sending tokens to another user:
import FungibleToken from 0x01 // This transaction is a template for a transaction that // could be used by anyone to send tokens to another account // that owns a Vault transaction { // Temporary Vault object that holds the balance that is being transferred var temporaryVault: @FungibleToken.Vault prepare(acct: AuthAccount) { // withdraw tokens from your vault by borrowing a reference to it // and calling the withdraw function with that reference let vaultRef = acct.borrow<&FungibleToken.Vault>(from: /storage/MainVault) ?? panic("Could not borrow a reference to the owner's vault") self.temporaryVault <- vaultRef.withdraw(amount: UFix64(10)) } execute { // get the recipient's public account object let recipient = getAccount(0x01) // get the recipient's Receiver reference to their Vault // by borrowing the reference from the public capability let receiverRef = recipient.getCapability(/public/MainReceiver)! .borrow<&FungibleToken.Vault{FungibleToken.Receiver}>() ?? panic("Could not borrow a reference to the receiver") // deposit your tokens to their Vault receiverRef.deposit(from: <-self.temporaryVault) log("Transfer succeeded!") } }
In this example, the signer withdraws tokens from their
Vault, which creates and returns a temporary
Vault resource object with
balance=10 that is used for transferring the tokens. In the execute phase. the transaction moves that resource to another user's
Vault using their
deposit method. The temporary
Vault is destroyed after its balance is added to the recipient's
Vault.
You might be wondering why we have to use two function calls to complete a token transfer when it is possible to do it in one. This is because of the way resources work in Cadence. In a ledger-based model, you would just call transfer, which just updates the ledger, but in Cadence, the location of the tokens matters, and therefore most token transfer situations will not just be a direct account-to-account transfer. Most of the time, tokens will be used for a different purpose first, like purchasing something, and that requires the
Vault to be separately sent and verified before being deposited to the storage of an account. Separating the two also allows us to take advantage of being able to statically verify which parts of accounts can be modified in the
prepare section of a transaction, which will help users have peace of mind when getting fed transactions to sign from an app.
Execute
Script1.cdc again.
If correct, you should see the following lines indicating that account
0x01's balance is 40 and account
0x02's balance is 20:
"Account 1 Balance" 40 "Account 2 Balance" 20 Result > "void"
You now know how a basic fungible token is used in Cadence and Flow!
From here, you could try to extend the functionality of fungible tokens by making:
- A faucet for these tokens
- An escrow that can be deposited to (but only withdrawn when the balance reaches a certain point)
- A function to the resource that mints new tokens!
Non-Fungible Tokens on Flow
Now that you have an understanding of how fungible tokens work on Flow, you're ready to play with non-fungible tokens!
|
https://docs.onflow.org/tutorial/cadence/03-fungible-tokens/
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
The npm package react-isomorphic-render receives a total of 356 downloads a week. As such, we scored react-isomorphic-render popularity level to be Limited.
Based on project statistics from the GitHub repository for the npm package react-isomorphic-render, we found that it has been starred 180 times, and that 0 other projects on the ecosystem are dependent on it.
Downloads are calculated as moving averages for a period of the last 12 months, excluding weekends and known missing data points.
Snyk detected that the latest version of react-isomorphic-render react-isomorphic-render is missing a security policy.
# Install the Snyk CLI and test your project
npm i snyk && snyk test react-isomorphic-render
Further analysis of the maintenance status of react-isomorphic-render based on released npm versions cadence, the repository activity, and other data points determined that its maintenance is Inactive.
An important project maintenance signal to consider for react-isomorphic-render react-isomorphic-render is missing a Code of Conduct.
We detected a total of 168 direct & transitive dependencies for react-isomorphic-render. See the full dependency tree of react-isomorphic-render
react-isomorphic-render has more than a single and default latest tag published for the npm package. This means, there may be other tags available for this package, such as next to indicate future releases, or stable to indicate stable releases.
Server Side Rendering for
React + React-router v3 + Redux stack.
<title/>and
<meta/>, programmatic redirects, 100% correct handling of HTTP Cookies, etc
The original concept of the web was one of a network of "resources" interconnected with "hyperlinks": a user could query a "resource" by a "Universal Resource Link" (URL) and then travel to any of the connected "resources" just by navigating the corresponding hyperlinks, and then it would all repeat recursively therefore interconnecting each and every "resource" into a giant interconnected web (hence the name). The "resources" were meant to be "documents", like reports, articles, papers, news, books, etc.
The web wasn't meant at all for "applications". At first javascript was only used to bring some naive interactivity to static "documents", like following the cursor with a sprinkle, or adding christmas snow to a page, or applying some effect to a picture upon mouseover. Initially javascript was never meant to be a means of operating on the page's "content". It was just for "presentation" ("view"), not the "content".
Ajax wasn't originally meant for "content" too: it was just for tiny utility things like hitting a "Like" button without needlessly refreshing the whole freaking page, but it was then too turned into a machinery for fetching a page's "content".
And so the Web became broken. And to completely fix that and make the Web 100% pure again total Server Side Rendering for each dynamic website is the only way to go. This is still a purely esthetical argument and nobody would really care (except purists and perfectionists) if it didn't come to being able to be indexed by Google...
Search engine crawlers like Google bot won't wait for a page to make its Ajax calls to an API server for data: they would simply abort all asynchronous javascript and index the page as is. Don't mistake it for web crawlers not being able to execute javascript — they're perfectly fine with doing that (watch out though for using the latest and greatest and always use polyfills for the older browsers since web crawlers may be using those under the hood).
So the only thing preventing a dynamic website from being indexed by a crawler is Ajax, not javascript. This therefore brings two solutions: one is to perform everything (routing, data fetching, rendering) on the server side and the other is to perform routing and data fetching on the server side leaving rendering to the client's web browser. Both these approaches work with web crawlers. And this is what this library provides.
While the first approach is more elegant and pure, currently it is a very CPU intensive task to render a moderately complex React page using
ReactDOM.renderToString() (takes about 100 milliseconds of blocking CPU single core time for complex pages having more than 1000 components, as of 2016). Facebook doesn't use Server Side Rendering itself so optimizing this part of the React library is not a priority for them. So until this (if ever possible) Server Side Rendering performance issue is fixed I prefer the second approach: performing routing and page preloading on the server side while leaving page rendering to the client. This is achieved by using
render: false flag (described much further in this document).
The final argument in favour of Server Side Rendering is that even if a website doesn't need search engine indexing it would still benefit from employing Server Side Rendering because that would save that additional HTTP roundtrip from the web browser to the API server for fetching the page's data. And no matter how fast the API server is, latency is unbeatable being about 100ms. So, by performing routing and page preloading on the server side one can speed up website loading by about 100ms. Not that it mattered that much for non-perfectionists but still why not do it when it's so simple to implement.
(see webpack-react-redux-isomorphic-render-example or webapp as references)
$ npm install react-isomorphic-render --save
Start by creating a settings file (it configures both client side and server side)
export default { // React-router v3 routes routes: require('./src/client/routes'), // Redux reducers // (they will be combined into the // root reducer via `combineReducers()`) reducer: require('./src/client/redux/reducers') }
export { default as pageOne } from './pageOneReducer' export { default as pageTwo } from './pageTwoReducer' ...
Then call
render() in the main client-side javascript file.
import { render } from 'react-isomorphic-render' import settings from './react-isomorphic-render' // Render the page in web browser render(settings)
And the
index.html would look like this:
<html> <head> <title>react-isomorphic-render</title> </head> <body> <div id="react"></div> <script src="/bundle.js"></script> </body> </html>
Where
bundle.js is the
./src/client/application.js file built with Webpack (or you could use any other javascript bundler).
Now,
index.html and
bundle.js files must be served over HTTP. If you're using Webpack then place
index.html to Webpack's
configuration.output.path folder and run
webpack-dev-server: it will serve
index.html from disk and
bundle.js from memory.
Now go to
localhost:8080. It should respond with the contents of the
index.html file. Client-side rendering should work now. The whole setup can be deployed as-is being uploaded to a cloud and served statically (which is very cheap).
Adding Server Side Rendering to the setup is quite simple though requiring a running Node.js process therefore the website is no longer just statics served from the cloud but is both statics and a Node.js rendering process running somewhere (say, in a Docker container).
index.html will be generated on-the-fly by page rendering server for each incoming HTTP request, so the
index.html file may be deleted as it's of no use now.
import webpageServer from 'react-isomorphic-render/server' import settings from './react-isomorphic-render' // Create webpage rendering server const server = webpageServer(settings, { // These are the URLs of the "static" javascript and CSS files // which are injected in the resulting Html webpage // as <script src="..."/> and <link rel="style" href="..."/>. // (this is for the main application JS and CSS bundles only, // for injecting 3rd party JS and CSS use `html` settings instead: //) assets() { return { javascript: '', style: '' } } }) // Start webpage rendering server on port 3000 // (`server.listen(port, [host], [callback])`) server.listen(3000, function(error) { if (error) { throw error } console.log(`Webpage rendering server is listening at`) })
Now disable javascript in Chrome DevTools, go to
localhost:3000 and the server should respond with a server-side-rendered page.
The
server variable in the example above is just a Koa application, so alternatively it could be started like this:
import http from 'http' // import https from 'https' import webpageServer from 'react-isomorphic-render/server' const server = webpageServer(settings, {...}) http.createServer(server.callback()).listen(80, (error) => ...) // https.createServer(options, server.callback()).listen(443, (error) => ...)
In the examples above "static" files (assets) are served by
webpack-dev-server on
localhost:8080. But it's for local development only. For production these "static" files must be served by someone else, be it a dedicated proxy server like NginX, a simple homemade Node.js application or (recommended) a cloud-based solution like Amazon S3.
Also, a real-world website most likely has some kind of an API, which, again, could be either a dedicated API server (e.g. written in Golang), a simple Node.js application or a modern "serverless" API like Amazon Lambda hosted in the cloud.
The following 3 sections illustrate each one of these 3 approaches.
This section illustrates the "simple homemade Node.js application" approach. It's not the approach I'd use for a real-world website but it's the simplest one so it's for illustration purposes only.
So, a Node.js process is already running for page rendering, so it could also be employed to perform other tasks like serving "static" files (
webpack-dev-server is not running in production) or hosting a REST API.
import webpageServer from 'react-isomorphic-render/server' import settings from './react-isomorphic-render' import path from 'path' // `npm install koa-static koa-mount --save` import statics from 'koa-static' import mount from 'koa-mount' // Create webpage rendering server const server = webpageServer(settings, { assets: ..., // (optional) // This parameter is specified here for the example purpose only. // Any custom Koa middlewares go here. // They are `.use()`d before page rendering middleware. middleware: [ // Serves "static files" on `/assets` URL path from the `../build` folder // (the Webpack `configuration.output.path` folder). mount('/assets', statics(path.join(__dirname, '../build'), { // Cache assets in the web browser for 1 year maxAge: 365 * 24 * 60 * 60 })), // Hosts REST API on `/api` URL path. mount('/api', async (ctx, next) => { ctx.type = 'application/json' ctx.body = '{"data":[1,2,3]}' }) ] }) // Start webpage rendering server on port 3000 ...
The old-school way is to set up a "proxy server" like NginX dispatching all incoming HTTP requests: serving "static" files, redirecting to the API server for
/api calls, etc.
server { # Web server listens on port 80 listen 80; # Serving "static" files (assets) location /assets/ { root "/filesystem/path/to/static/files"; } # By default everything goes to the page rendering service location / { proxy_pass; } # Redirect "/api" requests to API service location /api { rewrite ^/api/?(.*) /$1 break; proxy_pass; } }
Or, alternatively, a quick Node.js proxy server could be made up for development purposes using http-proxy library
const path = require('path') const express = require('express') const httpProxy = require('http-proxy') // Use Express or Koa, for example const app = express() const proxy = httpProxy.createProxyServer({}) // Serve static files app.use('/assets', express.static(path.join(__dirname, '../build'))) // Proxy `/api` calls to the API service app.use('/api', function(request, response) { proxy.web(request, response, { target: '' }) }) // Proxy all other HTTP requests to webpage rendering service app.use(function(request, response) { proxy.web(request, response, { target: '' }) }) // Web server listens on port `80` app.listen(80)
Finally, the modern way is not using any "proxy servers" at all. Instead everything is distributed and decentralized. Webpack-built assets are uploaded to the cloud (e.g. Amazon S3) and webpack configuration option
.output.publicPath is set to something like (your CDN URL) so now serving "static" files is not your job – your only job is to upload them to the cloud after Webpack build finishes. API is dealt with in a similar way: CORS headers are set up to allow querying directly from a web browser by an absolute URL and the API is either hosted as a standalone API server or run "serverless"ly, say, on Amazon Lambda, and is queried by an absolute URL, like.
This concludes the introductory part of the README and the rest is the description of the various (useful) tools which come prepackaged with this library.
If a Redux action creator returns an object with a
promise (function) and
events (array) then this action is assumed asynchronous.
type = events[0]is dispatched
promisefunction gets called and returns a
Promise
Promisesucceeds then an event of
type = events[1]is dispatched having
resultproperty set to the
Promiseresult
Promisefails then an event of
type = events[2]is dispatched having
errorproperty set to the
Promiseerror
Example:
function asynchronousAction() { return { promise: () => Promise.resolve({ success: true }), events: ['PROMISE_PENDING', 'PROMISE_SUCCESS', 'PROMISE_ERROR'] } }
This is a handy way of dealing with "asynchronous actions" in Redux, e.g. HTTP requests for a server-side HTTP REST API (see the "HTTP utility" section below).
When you find yourself copy-pasting those
_PENDING,
_SUCCESS and
_ERROR event names from one action creator to another then take a look at
asynchronousActionEventNaming setting described in the All
react-isomorphic-render.js settings section of the "advanced" readme: it lets a developer just supply a "base"
event name and then it generates the three lifecycle event names from that "base"
event significantly reducing boilerplate.
For convenience, the argument of the
promise function parameter of "asynchronous actions" described above is always the built-in
http utility having methods
get,
head,
put,
patch,
delete, each returning a
Promise and taking three arguments: the
url of the HTTP request,
parameters object, and an
options object. It can be used to easily query HTTP REST API endpoints in Redux action creators.
Using ES6
async/await:
function fetchFriends(personId, gender) { return { promise: async (http) => await http.get(`/api/person/${personId}/friends`, { gender }), events: ['GET_FRIENDS_PENDING', 'GET_FRIENDS_SUCCESS', 'GET_FRIENDS_FAILURE'] } }
Or using plain
Promises (for those who prefer)
function fetchFriends(personId, gender) { return { promise: (http) => http.get(`/api/person/${personId}/friends`, { gender }), events: ['GET_FRIENDS_PENDING', 'GET_FRIENDS_SUCCESS', 'GET_FRIENDS_FAILURE'] } }
The possible
options (the third argument of all
http methods) are
headers— HTTP Headers JSON object
authentication— set to
falseto disable sending the authentication token as part of the HTTP request, set to a String to pass it as an
Authorization: Bearer ${token}token (no need to set the token explicitly for every
httpmethod call, it is supposed to be set globally, see below)
progress(percent, event)— is used for tracking HTTP request progress (e.g. file upload)
onResponseHeaders(headers)– for examining HTTP response headers (e.g. Amazon S3 file upload)
In order for
http utility calls to send an authentication token as part of an HTTP request (the
Authorization: Bearer ${token} HTTP header) the
authentication.accessToken() function must be specified in
react-isomorphic-render.js.
{ authentication: { accessToken(getCookie, { store, path, url }) { // (make sure the access token is not leaked to a third party) return getCookie('accessToken') return localStorage.getItem('accessToken') return store.getState().authentication.accessToken } } }
All URLs queried via
http utility must be relative ones (e.g.
/api/users/list). In order to transform these relative URLs into absolute ones there are two approaches.
The first approach is for people using a proxy server (minority). In this case all client-side HTTP requests will still query relative URLs which are gonna hit the proxy server and the proxy server will route them to their proper destination. And the server side is gonna query the proxy server directly (there is no notion of "relative URLs" on the server side) therefore the proxy
host and
port need to be configured in webpage rendering service options.
const server = webpageServer(settings, { proxy: { host: '192.168.0.1', port: 3000, // (enable for HTTPS protocol) // secure: true } })
The second approach is for everyone else (majority). In this case all URLs are transformed from relative ones into absolute ones by the
http.url(path) function parameter configured in
react-isomorphic-render.js.
{ http: { url: path => `{path}` } }
The
http utility will also upload files if they're passed as part of
parameters (example below). Any of these types of file
parameters are accepted:
Fileparameter it will be a single file upload.
FileListparameter with a single
Fileinside it would be treated as a single
File.
FileListparameter with multiple
Files inside multiple file upload will be performed.
<input type="file"/>DOM element parameter its
.fileswill be taken as a
FileListparameter.
Progress can be metered by passing
progress option as part of the
options argument.
// React component class ItemPage extends React.Component { render() { return ( <div> ... <input type="file" onChange={this.onFileSelected}/> </div> ) } // Make sure to `.bind()` this handler onFileSelected(event) { const file = event.target.files[0] // Could also pass just `event.target.files` as `file` dispatch(uploadItemPhoto(itemId, file)) // Reset the selected file // so that onChange would trigger again // even with the same file. event.target.value = null } } // Redux action creator function uploadItemPhoto(itemId, file) { return { promise: http => http.post( '/item/photo', { itemId, file }, { progress(percent) { console.log(percent) } } ), events: ['UPLOAD_ITEM_PHOTO_PENDING', 'UPLOAD_ITEM_PHOTO_SUCCESS', 'UPLOAD_ITEM_PHOTO_FAILURE'] } }
By default, when using
http utility all JSON responses get parsed for javascript
Dates which are then automatically converted from
Strings to
Dates. This is convenient, and also safe because such date
Strings have to be in a very specific ISO format in order to get parsed (
year-month-dayThours:minutes:seconds[timezone]), but if someone still prefers to disable this feature and have their
Stringified
Dates back then there's the
parseDates: false flag in the configuration to opt-out of this feature.
For page preloading consider using
@preload() helper to load the neccessary data before the page is rendered.
import { connect } from 'react-redux' import { Title, preload } from 'react-isomorphic-render' // fetches the list of users from the server function fetchUsers() { return { promise: http => http.get('/api/users'), events: ['GET_USERS_PENDING', 'GET_USERS_SUCCESS', 'GET_USERS_FAILURE'] } } @preload(({ dispatch }) => dispatch(fetchUsers)) @connect( state => ({ users: state.users.users }), // `bindActionCreators()` for Redux action creators { fetchUsers } ) export default class Page extends Component { render() { const { users, fetchUsers } = this.props return ( <div> <Title>Users</Title> <ul>{ users.map(user => <li>{ user.name }</li>) }</ul> <button onClick={ fetchUsers }>Refresh</button> </div> ) } }
In the example above
@preload() helper is called to preload a web page before it is displayed, i.e. before the page is rendered (both on server side and on client side).
@preload() decorator takes a function which must return a
Promise:
@preload(function({ dispatch, getState, location, parameters, server }) { return Promise.resolve() })
Alternatively,
async/await syntax may be used:
@preload(async ({ dispatch, getState, location, parameters, server }) => { await fetchWhatever(parameters.id) })
When
dispatch is called with a special "asynchronous" action (having
promise and
events properties, as discussed above) then such a
dispatch() call will return a
Promise, that's why in the example above it's written simply as:
@preload(({ dispatch }) => dispatch(fetchUsers))
Note:
transform-decorators-legacy Babel plugin is needed at the moment to make decorators work in Babel:
npm install babel-plugin-transform-decorators-legacy --save
{ "presets": [ ... ], "plugins": [ "transform-decorators-legacy" ] }
On the client side, in order for
@preload to work all
<Link/>s imported from
react-router must be instead imported from
react-isomorphic-render. Upon a click on a
<Link/> first it waits for the next page to preload, and then, when the next page is fully loaded, it is displayed to the user and the URL in the address bar is updated.
@preload() also works for Back/Forward web browser buttons navigation. If one
@preload() is in progress and another
@preload() starts (e.g. Back/Forward browser buttons) the first
@preload() will be cancelled if
bluebird
Promises are used in the project and also if
bluebird is configured for
Promise cancellation (this is an advanced feature and is not required for operation).
@preload() can be disabled for certain "Back" navigation cases by passing
instantBack property to a
<Link/> (e.g. for links on search results pages).
To run
@preload() only on client side pass the second
{ client: true } options argument to it
@preload(({ dispatch }) => dispatch(loadContent()), { client: true })
For example, a web application could be hosted entirely statically in a cloud like Amazon S3 and fetch data using a separately hosted API like Amazon Lambda. This kind of setup is quite popular due to being simple and cheap. Yes, it's not a true isomorphic approach because the user is given a blank page first and then some
main.js script fetches the page data in the browser. But, as being said earlier, this kind of setup is rediculously simple to build and cheap to maintain so why not. Yes, Google won't index such websites, but if searchability is not a requirement (yet) then it's the way to go (e.g. "MVP"s).
Specifying
{ client: true } option for each
@preload() would result in a lot of copy-pasta so there's a special configuration option for that:
{ preload: { client: true } }.
@preload()indicator
Sometimes preloading a page can take some time to finish so one may want to (and actually should) add some kind of a "spinner" to inform the user that the application isn't frozen and the navigation process needs some more time to finish. This can be achieved by adding a Redux reducer listening to these three Redux events:
import { PRELOAD_STARTED, PRELOAD_FINISHED, PRELOAD_FAILED } from 'react-isomorphic-render' export default function(state = {}, action = {}) { switch (action.type) { case PRELOAD_STARTED : return { ...state, pending: true, error: false } case PRELOAD_FINISHED : return { ...state, pending: false } case PRELOAD_FAILED : return { ...state, pending: false, error: action.error } default : return state } }
And a "spinner" component would look like
import React, { Component } from 'react' import { connect } from 'react-redux' import { ActivityIndicator } from 'react-responsive-ui' @connect(state => ({ pending: state.preload.pending })) export default class Preload extends Component { render() { const { pending } = this.props return ( <div className={ `preloading ${pending ? 'preloading--shown' : ''}` }> <ActivityIndicator className="preloading__spinner"/> </div> ); } }
.preloading { position: fixed; top : 0; left : 0; right : 0; bottom : 0; background-color: rgba(0, 0, 0, 0.1); z-index: 0; opacity: 0; transition: opacity 100ms ease-out, z-index 100ms step-end; } .preloading--shown { z-index: 1; opacity: 1; transition: opacity 600ms ease-out 500ms, z-index 0ms step-start; cursor: wait; } .preloading__spinner { position: absolute; left: calc(50% - 2rem); top: calc(50% - 2rem); width: 4rem; height: 4rem; color: white; }
To set a custom HTTP response status code for a specific route set the
status property of that
<Route/>.
export default ( <Route path="/" component={Layout}> <IndexRoute component={Home}/> <Route path="blog" component={Blog}/> <Route path="about" component={About}/> <Route path="*" component={PageNotFound} status={404}/> </Route> )
This package uses react-helmet under the hood.
import { Title, Meta } from 'react-isomorphic-render' // Webpage title will be replaced with this one <Title>Home</Title> // Adds additional <meta/> tags to the webpage <head/> <Meta> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/> <meta property="og:title" content="International Bodybuilders Club"/> <meta property="og:description" content="This page explains how to do some simple push ups"/> <meta property="og:image" content=""/> <meta property="og:locale" content="ru_RU"/> </Meta>
Once one starts writing a lot of
http calls in Redux actions it becomes obvious that there's a lot of copy-pasting involved. To reduce those tremendous amounts of copy-pasta an "asynchronous action handler" may be used:
import { action, createHandler, stateConnector, eventName } from 'react-isomorphic-render' // (`./react-isomorphic-render-async.js` settings file is described below) import settings from './react-isomorphic-render-async' const handler = createHandler(settings) // Post comment Redux "action creator" export const postComment = action({ namespace: 'BLOG_POST', event: 'POST_COMMENT', // `action()` must return a `Promise`. // Can be an `async` function // (`async` functions always return a `Promise`). // `http` argument is automatically appended by this library // while the `userId`, `blogPostId` and `commentText` arguments // must be passed to this action when calling it. action(userId, blogPostId, commentText, http) { return http.post(`/blog/posts/${blogPostId}/comment`, { userId: userId, text: commentText }) } }, handler) // Get comments Redux "action creator" export const getComments = action({ namespace: 'BLOG_POST', event: 'GET_COMMENTS', // `action()` must return a `Promise`. // Can be an `async` function // (`async` functions always return a `Promise`). // `http` argument is automatically appended by this library // while the `blogPostId` argument // must be passed to this action when calling it. action(blogPostId, http) { return http.get(`/blog/posts/${blogPostId}/comments`) }, // The fetched comments will be placed // into the `comments` Redux state property. result: 'comments' // Or write it as a reducer: // result: (state, result) => ({ ...state, comments: result }) }, handler) // A developer can additionally handle any other custom events handler.handle(eventName('BLOG_POST', 'CUSTOM_EVENT'), (state, action) => ({ ...state, customProperty: action.result })) // This is for the Redux `@connect()` helper below. // Each property name specified here or // as a `result` parameter of an `action()` definition // will be made available inside Redux'es // `@connect(state => ({ ...connector(state.reducerName) }))`. // This is just to reduce boilerplate when `@connect()`ing // React Components to Redux state. // Alternatively, each required property from Redux state // can be specified manually inside `@connect()` mapper. handler.addStateProperties('customProperty') // A little helper for Redux `@connect()` // which reduces boilerplate when `@connect()`ing // React Components to Redux state. // `@connect(state => ({ ...connector(state.reducerName) }))` // Will add all (known) state properties from // Redux state to the React Component `props`. export const connector = stateConnector(handler) // This is the Redux reducer which now // handles the asynchronous actions defined above // (and also the `handler.handle()` events). // Export it as part of the "root" reducer. export default handler.reducer()
// The "root" reducer composed of various reducers. export { default as blogPost } from './blogPost' ...
The React Component would look like this
import React, { Component } from 'react' import { connect } from 'react-redux' import { preload } from 'react-isomorphic-render' import { connector, getComments, postComment } from './redux/blogPost' // Preload comments before showing the page // (see "Page preloading" section of this document) @preload(({ dispatch, getState, parameters }) => { // `parameters` are the URL parameters populated by `react-router`: // `<Route path="/blog/:blogPostId"/>`. return dispatch(getComments(parameters.blogPostId)) }) // See `react-redux` documentation on `@connect()` decorator @connect((state) => ({ userId: state.user.id, // `...connector()` will populate the Redux `props` // with the (known) `state.blogPost` properties: // * `postCommentPending` // * `postCommentError` // * `getCommentsPending` // * `getCommentsError` // * `comments` // * `customProperty` ...connector(state.blogPost) }), { postComment }) export default class BlogPostPage extends Component { render() { const { getCommentsPending, getCommentsError, comments } = this.props if (getCommentsError) { return <div>Error while loading comments</div> } return ( <div> <ul> { comments.map(comment => <li>{comment}</li>) } </ul> {this.renderPostCommentForm()} </div> ) } renderPostCommentForm() { // `params` are the URL parameters populated by `react-router`: // `<Route path="/blog/:blogPostId"/>`. const { userId, params, postComment, postCommentPending, postCommentError } = this.props if (postCommentPending) { return <div>Posting comment...</div> } if (postCommentError) { return <div>Error while posting comment</div> } return ( <button onClick={() => postComment(userId, params.blogPostId, 'text')}> Post comment </button> ) } }
And the additional configuration would be:
import asyncSettings from './react-isomorphic-render-async' export default { // All the settings as before ...asyncSettings }
import { underscoredToCamelCase } from 'react-isomorphic-render' export default { // When supplying `event` instead of `events` // as part of an asynchronous Redux action // this will generate `events` from `event` // using this function. asynchronousActionEventNaming: event => ([ `${event}_PENDING`, `${event}_SUCCESS`, `${event}_ERROR` ]), // When using "asynchronous action handlers" feature // this function will generate a Redux state property name from an event name. // E.g. event `GET_USERS_ERROR` => state.`getUsersError`. asynchronousActionHandlerStatePropertyNaming: underscoredToCamelCase, }
Notice the extraction of these two configuration parameters (
asynchronousActionEventNaming and
asynchronousActionHandlerStatePropertyNaming) into a separate file
react-isomorphic-render-async.js: this is done to break circular dependency on
./react-isomorphic-render.js file because the
routes parameter inside
./react-isomorphic-render.js is the
react-router
./routes.js file which
imports React page components which in turn
import action creators which in turn would import
./react-isomorphic-render.js hence the circular (recursive) dependency (same goes for the
reducer parameter inside
./react-isomorphic-render.js).
For synchronous actions it's the same as for asynchronous ones (as described above):
import { action, createHandler, stateConnector } from 'react-isomorphic-render' // (`./react-isomorphic-render-async.js` settings file is described above) import settings from './react-isomorphic-render-async' const handler = createHandler(settings) // Displays a notification. // // The Redux "action" creator is gonna be: // // function(message) { // return { // type: 'NOTIFICATIONS:NOTIFY', // message // } // } // // And the corresponding reducer is gonna be: // // case 'NOTIFICATIONS:NOTIFY': // return { // ...state, // message: action.message // } // export const notify = action({ namespace : 'NOTIFICATIONS', event : 'NOTIFY', payload : message => ({ message }), result : (state, action) => ({ ...state, message: action.message }) }, handler) // Or, it could be simplified even further: // // export const notify = action({ // namespace : 'NOTIFICATIONS', // event : 'NOTIFY', // result : 'message' // }, // handler) // // Much cleaner. // A little helper for Redux `@connect()` export const connector = stateConnector(handler) // This is the Redux reducer which now // handles the actions defined above. export default handler.reducer()
This library performs the following locale detection steps for each webpage rendering HTTP request:
localequery parameter (if it's an HTTP GET request)
localecookie
Accept-LanguageHTTP header
The resulting locales array is passed as
preferredLocales argument into
localize() function parameter of the webpage rendering server which then should return
{ locale, messages } object in order for
locale and
messages to be available as part of the
props passed to the
wrapper component which can then pass those to
<IntlProvider/> in case of using
react-intl for internationalization.
import React, { Component } from 'react' import { Provider } from 'react-redux' import { IntlProvider } from 'react-intl' import { AppContainer } from 'react-hot-loader' export default function Wrapper(props) { const { store, locale, messages, children } = props return ( <AppContainer> <Provider store={store}> <IntlProvider locale={locale ? get_language_from_locale(locale) : 'en'} messages={messages}> {children} </IntlProvider> </Provider> </AppContainer> ) }
import React from 'react' // `withRouter` is available in `react-router@3.0`. // // For `2.x` versions just use `this.context.router` property: // static contextTypes = { router: PropTypes.func.isRequired } // import { withRouter } from 'react-router' // Using `babel-plugin-transform-decorators-legacy` // @withRouter export default class Component extends React.Component { render() { const { router } = this.props return <div>{ JSON.stringify(router.location) }</div> } }
These two helper Redux actions change the current location (both on client and server).
import { goto, redirect } from 'react-isomorphic-render' import { connect } from 'react-redux' // Usage example // (`goto` navigates to a URL while adding a new entry in browsing history, // `redirect` does the same replacing the current entry in browsing history) @connect(state = {}, { goto, redirect }) class Page extends Component { handleClick(event) { const { goto, redirect } = this.props goto('/items/1?color=red') // redirect('/somewhere') } }
A sidenote: these two functions aren't supposed to be used inside
onEnter and
onChange
react-router hooks. Instead use the
replace argument supplied to these functions by
react-router when they are called (
replace works the same way as
redirect).
Alternatively, if the current location needs to be changed while still staying at the same page (e.g. a checkbox has been ticked and the corresponding URL query parameter must be added), then use
pushLocation(location, history) or
replaceLocation(location, history).
import { pushLocation, replaceLocation } from 'react-isomorphic-render' import { withRouter } from 'react-router' @withRouter class Page extends Component { onSearch(query) { const { router } = this.props pushLocation({ pathname: router.location.pathname, query: { query } }, router) } }
React Server Side Rendering is quite slow, so I prefer setting
render: false flag to move all React rendering to the web browser. This approach has virtually no complications. There are still numerous (effective) approaches to speeding up React Server Side Rendering like leveraging component markup caching and swapping the default React renderer with a much faster stripped down custom one. Read more.
For each page being rendered stats are reported if
stats() parameter function is passed as part of the rendering service settings.
{ ... stats({ url, route, time: { initialize, preload, render, total } }) { if (total > 1000) { // in milliseconds db.query('insert into server_side_rendering_stats ...') } } }
The arguments for the
stats() function are:
url— the requested URL (without the
protocol://host:portpart)
route—
react-routerroute string (e.g.
/user/:userId/post/:postId)
time.initialize— server side
initialize()function execution time (if defined)
time.preload— page preload time
time.render— page React rendering time
time.total— total time spent preloading and rendering the page
Rendering a complex React page (having more than 1000 components) takes about 100ms (
time.render). This is quite slow but that's how React Server Side Rendering currently is.
Besides simply logging individual long-taking page renders one could also set up an overall Server Side Rendering performance monitoring using, for example, StatsD
{ ... stats({ url, route, time: { initialize, preload, render, total } }) { statsd.increment('count') statsd.timing('initialize', initialize) statsd.timing('preload', preload) statsd.timing('render', render) statsd.timing('total', total) if (total > 1000) { // in milliseconds db.query('insert into server_side_rendering_stats ...') } } }
Where the metrics collected are
count— rendered pages count
initialize— server side
initialize()function execution time (if defined)
preload— page preload time
render— page React rendering time
time- total time spent preloading and rendering the page
Speaking of StatsD itself, one could either install the conventional StatsD + Graphite bundle or, for example, use something like Telegraf + InfluxDB + Grafana.
Telegraf starter example:
# Install Telegraf (macOS). brew install telegraf # Generate Telegraf config. telegraf -input-filter statsd -output-filter file config > telegraf.conf # Run Telegraf. telegraf -config telegraf.conf # Request a webpage and see rendering stats being output to the terminal.
Webpack's Hot Module Replacement (aka Hot Reload) works for React components and Redux reducers and Redux action creators (it just doesn't work for page
@preload()s).
HMR setup for Redux reducers is as simple as adding
store.hotReload() (as shown below). For enabling HMR on React Components (and Redux action creators) I would suggest the new react-hot-loader 3 (which is still in beta, so install it like
npm install react-hot-loader@3.0.0-beta.6 --save):
import settings from './react-isomorphic-render' render(settings).then(({ store, rerender }) => { if (module.hot) { module.hot.accept('./react-isomorphic-render', () => { rerender() // Update reducer (for Webpack 2 ES6) store.hotReload(settings.reducer) // Update reducer (for Webpack 1) // store.hotReload(require('./react-isomorphic-render').reducer) }) } })
import React from 'react' import { Provider } from 'react-redux' // `react-hot-loader@3`'s `<AppContainer/>` import { AppContainer } from 'react-hot-loader' export default function Wrapper({ store, children }) { return ( <AppContainer> <Provider store={ store }> { children } </Provider> </AppContainer> ) }
{ "presets": [ "react", // For Webpack 2 ES6: ["es2015", { modules: false }], // For Webpack 1: // "es2015", "stage-2" ], "plugins": [ // `react-hot-loader@3` Babel plugin "react-hot-loader/babel" ] }
export default { entry: { main: [ // This line is required for `react-hot-loader@3` 'react-hot-loader/patch', 'webpack-hot-middleware/client?', 'webpack/hot/only-dev-server', './src/application.js' ] }, plugins: [ new webpack.HotModuleReplacementPlugin(), ... ], ... }
P.S.: Currently it says
Warning: [react-router] You cannot change <Router routes>; it will be ignored in the browser console. I'm just ignoring this for now, maybe I'll find a proper fix later. Currently I'm using this hacky workaround in
./src/client/application.js:
/** * Warning from React Router, caused by react-hot-loader. * The warning can be safely ignored, so filter it from the console. * Otherwise you'll see it every time something changes. * See */ if (module.hot) { const isString = a => typeof a === 'string'; const orgError = console.error; // eslint-disable-line no-console console.error = (...args) => { // eslint-disable-line no-console if (args && args.length === 1 && isString(args[0]) && args[0].indexOf('You cannot change <Router routes>;') > -1) { // React route changed } else { // Log the error as normally orgError.apply(console, args); } }; }
websocket() helper sets up a WebSocket connection.
import { render, websocket } from 'react-isomorphic-render' render(settings).then(({ store, protectedCookie }) => { websocket({ host: 'localhost', port: 80, // secure: true, store, token: protectedCookie }) })
If
token parameter is specified then it will be sent as part of every message (providing support for user authentication).
WebSocket will autoreconnect (with "exponential backoff") emitting
open event every time it does.
After the
websocket() call a global
websocket variable is created exposing the following methods:
listen(eventName, function(event, store))
onOpen(function(event, store))– is called on
openevent
onClose(function(event, store))– is called on
closeevent
onError(function(event, store))– is called on
errorevent (
closeevent always follows the corresponding
errorevent)
onMessage(function(message, store))
send(message)
The
store argument can be used to
dispatch() Redux "actions".
websocket.onMessage((message, store) => { if (message.command) { switch (message.command) { case 'initialized': store.dispatch(connected()) return console.log('Realtime service connected', message) case 'notification': return alert(message.text) default: return console.log('Unknown message type', message) } } }) websocket.onOpen((event, store) => { websocket.send({ command: 'initialize' }) }) websocket.onClose((event, store) => { store.dispatch(disconnected()) })
The global
websocket object also exposes the
socket property which is the underlying
robust-websocket object (for advanced use cases).
As for the server-side counterpart I can recommend using
uWebSockets
import WebSocket from 'uws' const server = new WebSocket.Server({ port: 8888 }) const userConnections = {} server.on('connection', (socket) => { console.log('Incoming WebSocket connection') socket.sendMessage = (message) => socket.send(JSON.stringify(message)) socket.on('close', async () => { console.log('Client disconnected') if (socket.userId) { userConnections[socket.userId].remove(socket) } }) socket.on('message', async (message) => { try { message = JSON.parse(message) } catch (error) { return console.error(error) } try { switch (message.command) { case 'initialize': // If a user connected (not a guest) // then store `userId` for push notifications. // Using an authentication token here // instead of simply taking `userId` out of the `message` // because the input can't be trusted (could be a hacker). if (message.userAuthenticationToken) { // (make sure `socket.userId` is a `String`) // The token could be a JWT token (jwt.io) // and `authenticateUserByToken` function could // check the token's authenticity (by verifying its signature) // and then extract `userId` out of the token payload. socket.userId = authenticateUserByToken(message.userAuthenticationToken) if (!userConnections[socket.userId]) { userConnections[socket.userId] = [] } userConnections[socket.userId].push(socket) } return socket.sendMessage({ command: 'initialized', data: ... }) default: return socket.sendMessage({ status: 404, error: `Unknown command: ${message.command}` }) } } catch (error) { console.error(error) } }) }) server.on('error', (error) => { console.error(error) }) // Also an HTTP server is started and a REST API endpoint is exposed // which can be used for pushing notifications to clients via WebSocket. // The HTTP server must only be accessible from the inside // (i.e. not listening on an external IP address, not proxied to) // otherwise an attacker could push any notifications to all users. // Therefore, only WebSocket connections should be proxied (e.g. using NginX). httpServer().handle('POST', '/notification', ({ to, text }) => { if (userConnections[to]) { for (const socket of userConnections[to]) { socket.sendMessage({ command: 'notification', text }) } } })
Feature: upon receiving a
message (on the client side) having a
type property defined such a
message is
dispatch()ed as a Redux "action" (this can be disabled via
autoDispatch option). For example, if
{ type: 'PRIVATE_MESSAGE', content: 'Testing', from: 123 } is received on a websocket connection then it is automatically
dispatch()ed as a Redux "action". Therefore, the above example could be rewritten as
// Server side (REST API endpoint) socket.sendMessage({ type: 'DISPLAY_NOTIFICATION', text }) // Client side (Redux reducer) function reducer(state, action) { switch (action.type) { case 'DISPLAY_NOTIFICATION': return { ...state, notifications: state.notifications.concat([action.text]) } default: return state } }
In those rare cases when website's content doesn't change at all (or changes very rarely, e.g. a blog) it may be beneficial to host a statically generated version of such a website on a CDN as opposed to hosting a full-blown Node.js application just for the purpose of real-time webpage rendering. In such cases one may choose to generate a static version of the website by snapshotting it on a local machine and then host it in a cloud at virtually zero cost.
First run the website in production (it can be run locally, for example).
Then run the following Node.js script which is gonna snapshot the currently running website and put it in a folder which can be then hosted anywhere.
# If the website will be hosted on Amazon S3 npm install s3 --save
// The following code hasn't been tested so create an issue in case of a bug import path from 'path' import { snapshot, upload, S3Uploader, copy, download } from 'react-isomorphic-render/static-site-generator' import configuration from '../configuration' // Index page is added by default let pages = [ '/about', { url: '/unauthenticated', status: 401 }, { url: '/unauthorized', status: 403 }, { url: '/not-found', status: 404 }, { url: '/error', status: 500 } ] async function run() { const { status, content } = JSON.parse(await download(``)) if (status !== 200) { throw new Error('Couldn\'t load items') } const items = JSON.parse(content) pages = pages.concat(items.map(item => `/items/${item.id}`)) const output = path.resolve(__dirname, '../static-site') // Snapshot the website await snapshot ({ host: configuration.host, port: configuration.port, pages, output }) // Copy assets (built by Webpack) await copy(path.resolve(__dirname, '../build/assets'), path.resolve(output, 'assets')) // Upload the website to Amazon S3 await upload(output, S3Uploader ({ bucket, accessKeyId, secretAccessKey, region })) } run().catch((error) => { console.error(error) process.exit(1) })
If you're using Webpack then make sure you either build your server-side code with Webpack too (so that asset
require() calls (images, styles, fonts, etc) inside React components work, see universal-webpack) or use something like webpack-isomorphic-tools.
At some point in time this README became huge so I extracted some less relevant parts of it into README-ADVANCED (including the list of all possible settings and options). If you're a first timer then just skip that one.
|
https://snyk.io/advisor/npm-package/react-isomorphic-render
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
The faint smile on your face turns into an expression of panic the moment you check your e-mail. “Oh, my God! The CEO has just forwarded an e-mail to Kiran, a union leader, instead of Kiran, the CFO.” But you manage to save the day. The recipient is on leave, and you delete the mail from his inward queue.
Your HR chief asks you to check your e-mail. When you do so, you can’t help but smile. The CEO has just declared a holiday for his birthday! But the smile doesn’t last long. The HR chief asks you to find out who sent that e-mail, as it surely wasn’t the CEO. You are reminded of the line routinely printed by banks on their statements: “This is a computer-generated statement and does not require a signature!”
Increasingly, your financial dealings are online. The statements are being sent by e-mail. To minimise the chances of the wrong person viewing confidential information, the statements are password protected. However, the passwords aren’t very strong. They protect against casual snooping, which is fine for most of us. But you do need to put some effort into figuring out the password for each statement. It’s not easy for you and your colleagues to do so.
There has to be a better way to manage all these scenarios.
Public key infrastructure
Public key-based algorithms have been around for about as long as I have been in the software field. Ubuntu owes its existence to the money made from the sale of Thawte, which issues digital certificates.
PGP (Pretty Good Privacy) came into existence in the early 1990s and GPG (GNU Privacy Guard) that conformed to the OpenPGP standard was available by the end of the 90s.
I have used a public key only to start an SSH session on a remote computer without having to give a password. But I have relied on GPG whenever I installed packages from a Fedora repository. Keeping the private key safe is a critical part of these security processes. The fear that the signing key may have been compromised resulted in the closure of the Fedora repositories for a noticeable period of time.
One reason for the lack of applications using OpenPGP may be that it is hard to get started with them. It is important to realise that this technique is based on people trusting each other and not on a third-party certificate. Would I trust the keys more if the issuing company had been audited by, say, PWC? A transaction between two parties does not need a certificate from a third party.
Before getting into programming using GPG, let us consider the steps involved in using the public key infrastructure with an e-mail client, Evolution. We choose Evolution as it comes with GPG support. Many e-mail clients now support OpenPGP — for example, Sylpheed. Thunderbird requires the Enigmail plug-in, which, unfortunately, was not compatible with the x64 application I was using. The default security mechanism of Thunderbird is S/MIME. Visit this forum topic for more details.
GPG and e-mail
The first step is to create your own pair of keys for your e-mail account, user@example.com. It is simple. Just give the following command:
gpg --gen-key
You will be asked a few questions and if in doubt, just use the defaults. It is better if you give a passphrase to protect your private key, especially if others may have access to the system you are using.
You will need to send your public key to your collaborators. So, export it as a text file and e-mail it:
gpg -a --export user@example.com > my_public_key.asc
Your friends can call you to verify that the fingerprint of the key is valid. You can find out the fingerprint by the following command:
gpg --fingerprint
You can now sign and send an e-mail to your friends. In Evolution, choose the option ‘Security’ on the menu bar. Select the ‘PGP Sign’ check box.
When you get the public key from your friends and collaborators, you will need to import it. This step is also simple:
gpg --import his_public_key.asc
GPG expects each key to be signed by a trusted entity before it is regarded as valid. So, you will need to sign the key you have just imported as follows—assuming that your friend’s e-mail address is friend@example.com:
gpg --sign-key friend@example.com
Now, you can encrypt the e-mail you are sending to your friend. When composing an e-mail, choose the ‘Security’ option from the menu bar and select the ‘PGP Encrypt’ check box. You can encrypt and sign the e-mail by selecting both the sign and the encrypt check boxes.
If you have received an encrypted and signed e-mail from your friend, Evolution will display it as usual, except that there will be a message at the bottom of the e-mail informing you that it had a valid signature and was encrypted.
If you forward the encrypted mail to someone else, including your friend, the recipient will not be able to decode the mail. This is very useful when sending e-mails to a relation who loves to gossip and has an uncontrollable mailing list! A side effect is that unless you copy an encrypted mail to yourself, you can’t see what you sent.
If you do not have the public key of a recipient and you give the request to encrypt the mail, Evolution will give you an error. However, if both the Kirans—the union leader and the CFO in our opening paragraph—had a public key in the key ring, encryption is not going to prevent you from making a mistake.
An example of an application
Programs can make mistakes—and they do so consistently. They do not normally make silly mistakes unless, of course, programmed to do so.
Suppose you want to send salary slips to all your employees, and want each employee to view only his or her salary details. Every employee, on joining, can create a key pair and register the individual public key with the company. The admin staff need not manage these keys securely! In fact, they can freely distribute the public key to anyone who needs it — for example, the bank where a salary account is opened.
Python has a module called
pygpgme, which is a wrapper for the
gpgme, GPG Made Easy, library. It is installed on Fedora, as
yum needs it. It lacks one small thing—documentation!
The
gpgme library is documented, but seems to lack any tutorials or articles on how to get started with it.
The solution in such cases is to download the source. You can actually ignore the source code and search for the test cases. That can act as an excellent starting point.
Encrypting/decrypting a file
For your application, you need to be able to encrypt a file. So, try the following code:
import gpgme infile = open(‘salary_slip.txt’) outfile = open(‘salary_slip.asc’,’w’) ctx = gpgme.Context() ctx.armor = True recipient_key = ctx.get_key(‘friend@example.com’) ctx.encrypt_sign([recipient_key], gpgme.ENCRYPT_ALWAYS_TRUST, infile, outfile) outfile.close() infile.close()
The code is pretty straightforward. Open the two files and obtain the GPG context. The ‘armor’ option creates an ASCII file rather than a binary one. Obtain the key by using the recipient’s e-mail address, then encrypt and sign the file by passing a list of the keys. The second option informs you that the keys should be trusted. You will be prompted for the passphrase while signing in, if you have specified one while creating your key.
The code for decrypting a file is even simpler:
import gpgme infile = open(‘salary_slip2.asc’) outfile = open(‘salary_slip.out’,’w’) ctx = gpgme.Context() sigs = ctx.decrypt_verify(infile, outfile) outfile.close() infile.close()
gpgme will raise an exception in case decryption fails or the signature is not valid. The ‘decrypt and verify’ method will return a list of signatures. You may want to get some more information about the signatures.
Since there is only one key in your case, try the following code:
You get the key by using the fingerprint and then print the information you may need.
Let’s suppose you just wanted to sign a text:
import gpgme infile = open(‘salary_slip.txt’) outfile = open(‘salary_slip_signed.asc’,’w’) ctx = gpgme.Context() ctx.armor = True ctx.sign(infile, outfile, gpgme.SIG_MODE_CLEAR) outfile.close() infile.close()
You have chosen the clear sign mode so that the text is readable and the signature identifiable.
This will be enough for the moment. You can read the code in the tests subdirectory of the pygpgme source to learn more.
Mime and PGP
You are now in a position to combine encryption with the e-mail module so that the hard part is done by the application, and the user can access secure information very conveniently. The format for a Mime-encrypted message is described in.
Start with the various modules that need to be imported:
import smtplib import gpgme from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from StringIO import StringIO
StringIO is a file-like class for manipulating a string buffer. It is, essentially, a memory file.
You will need to create a multi-part Mime formatted message with the attachment you wish to e-mail (see docs.python.org/library/email-examples.html for more details). Assume that you are attaching a PDF file:
def create_message(filename): outer = MIMEMultipart() fp = open(filename, ‘rb’) msg = MIMEBase(‘application’, ‘pdf’) msg.set_payload(fp.read()) fp.close() encoders.encode_base64(msg) msg.add_header(‘Content-Disposition’, ‘attachment’, filename=filename) outer.attach(msg) return outer.as_string()
You will next encrypt the message:
def encrypt_payload(in_msg, out_msg): ctx = gpgme.Context() ctx.armor = True recipient_key = ctx.get_key(‘friend@example.com’) ctx.encrypt([recipient_key], gpgme.ENCRYPT_ALWAYS_TRUST, in_msg, out_msg)
Now, you will need to create another multi-part Mime message that has the encrypted content as the payload. The Mime body must consist of exactly two parts, the first with the content type “application/pgp-encrypted”. This part contains the control information. The second part contains the encrypted content as an octet-stream.
def mime_pgp_message(fp): outer = MIMEMultipart(_subtype=’encrypted’,protocol=’application/pgp-encrypted’) outer['Subject'] = 'Attached Encrypted - 5' outer['To'] = 'friend@example.com' outer['From'] = 'user@example.com' msg = MIMEBase('application', 'pgp-encrypted') outer.attach(msg) enc_part = MIMEBase('application','octet-stream', name='encrypted.asc') fp.seek(0) enc_part.set_payload(fp.read()) outer.attach(enc_part) return outer.as_string()
Now, you are ready to send the message:
def send_message(sender, recipients, composed): s = smtplib.SMTP() s.connect() s.sendmail(sender, recipients, composed) s.close()
You would be calling the above routines as follows:
in_msg = StringIO(create_message(‘Open.pdf’)) out_msg = StringIO() encrypt_payload(in_msg, out_msg) composed = mime_pgp_message(out_msg) send_message(‘user@example.com’, [‘friend@example.com’], composed)
Unfortunately, signing the document introduces one more level of complexity. Before encrypting the message, you would need to sign it. For this, too, a multi-part message with two parts in the body, is required. So, the steps would be:
- Create the Mime message
- PGP Sign the Mime message
- Create a multi-part Mime message with protocol application/pgp-signature
- PGP encrypt the signed Mime message
- Create a multi-part Mime message with protocol application/pgp-encrypted
- Send the message
Final words
This article turned o ut to be much harder to write than I expected, as I could not find any tutorials or simple documentation on using gpgme or Mime/PGP-encrypted, whether for Python or any other language. In case anyone knows of any, I would love to hear about it.
It is a pity that banks force us to change our passwords every few months. We also need to ensure that our passwords are not the same at all sites. Nor the same as the ones used on the previous few occasions. In short, keeping track of passwords is one horrendous problem. Desktop tools that help use the appropriate password for each application or website are a solution for this problem.
A public key environment would, unambiguously, shift the task of preventing any leakage of passwords from the host sites to the user only. The critical advantage is that we need to protect only one private password. Last but not least, it will save us from making hundreds of enemies because we used our Gmail password at a social networking site, involuntarily inflicting our friends with the “I want to be your friend” spam.
|
https://www.opensourceforu.com/2009/03/secure-communication/
|
CC-MAIN-2020-45
|
en
|
refinedweb
|
Visual Studio Productivity Tips
In this episode, Robert is joined by Allison Bucholtz-Au, who shows us how IntelliSense cuts down the number of keystrokes required to write code in Visual Studio. Even if you have been using IntelliSense for years, you are sure to see a thing or two you didn't it could do.
She is my fav now. She is just great, smile and teach.. like that
niiiiiiiiiiice !
hmmm, so any clue that intellisense may be related contextually by the namespace and the API, say denoted by signatures of procedures, functions, parameter lists, types - anything that can be seen by reflection, including names just created. So not done by 'guessing', unless you consider the modern take on AI assisted coding.
|
https://channel9.msdn.com/Shows/Visual-Studio-Toolbox/More-Code-Less-Typing?WT.mc_id=DX_MVP4025064
|
CC-MAIN-2019-43
|
en
|
refinedweb
|
In this tutorial I will show you how to create and work with Java Interfaces. As always I will demonstrate a practical example of Java interface.
What is Java Interface?
As many other Java concepts, Interfaces are derived from real-world scenarios with the main purpose to use an object by strict rules. For example, if you want to turn on the washing machine to wash your clothes you need to press the start button. This button is the interface between you and the electronics inside the washing machine. Java interfaces have same behaviour: they set strict rules on how to interact with objects. To find more about Java objects read this tutorial.
The Java interface represents a group of methods with empty bodies. Well, it is not mandatory to have a whole list of methods inside an interface – they can be 0 or more… but, no matter the number of methods, they all should be empty.
Create an Interface
Using the example with the washing machine, lets create an Interface called
WashingMachine with one method
startButtonPressed()
public interface WashingMachine { public void startButtonPressed(); }
That’s all you need to define an interface. Note the usage of the keyword
interface. The method
startButtonPressed()has no body. It just ends with ; Of course you can also use methods with return types and parameters like:
public int changeSpeed(int speed);
How to Implement an Interface
Now we will create a class that implements our interface. To continue with the example we will create a washing machine of specific make that has the start button.
public class SamsungWashingMachine implements WashingMachine { @Override public void startButtonPressed() { System.out.println("The Samsung washing machine is now running."); } }
We use the
implements keyword in the class declaration. We need to implement the startButtonPressed method (give it some functionality) or otherwise our class will not compile.
Please note, you can implement more than one interface in one class. You just need to separate the interface names with commas in the class declaration like this:
public class SamsungWashingMachine implements WashinMachine, Serializable, Comparable<WashinMachine> { ... }
Test your Interface
Now lets create a small program to test our interface and the implementation
public class Test { public static void main(String[] args) { WashinMachine samsungWashinMachine = new SamsungWashingMachine(); samsungWashinMachine.startButtonPressed(); } }
and the output of the program will be :
The Samsung washing machine is now running.
Use Interfaces to Declare Specific Object Characteristics
There is another common usage of interfaces in Java – to tell an object has specific use or characteristics.
Lets give one more real-world example. You are a survival in the woods. You find different object and put them in your backpack for later use. When you rest you go through the found objects and eat the once that are eatable.
First, lets define an interface called
FoundObject with no methods at all. Those are all the objects we found in the woods:
public interface FoundObject { }
now we define a second interface called
Eatable. We will use it just to denote if the object is eatable or not
public interface Eatable { public void eat(); }
With the following three classes we will define the objects we find in the woods – apples, raspberries and stones
public class Apple implements FoundObject, Eatable { private String name; public Apple(String name) { this.name = name; } @Override public void eat() { System.out.println("Yummy! you eat some " + this.name); } }
public class Raspberry implements FoundObject, Eatable { private String name; public Raspberry(String name) { this.name = name; } @Override public void eat() { System.out.println("Yummy! you eat some " + this.name); } }
public class Stone implements FoundObject { private String name; public Stone(String name) { this.name = name; } }
Now lets write the survival program. We will collect found objects in our backpack (array) and try to eat them
public class WoodsSurvival { public static void main(String[] args) { // create an array of type FoundObject FoundObject backpack [] = new FoundObject[3]; // create the objects we found in the woods FoundObject apple = new Apple("apple"); FoundObject stone = new Stone("stone"); FoundObject raspberry = new Raspberry("raspberry"); // add the found objects to the backpack backpack[0] = apple; backpack[1] = stone; backpack[2] = raspberry; // iterate over the found objects for (int i=0; i<backpack.length; i++) { FoundObject currentObject = backpack[i]; // check if object is eatable if (currentObject instanceof Eatable) { // cast the object to eatable and execute eat method ((Eatable) currentObject).eat(); } } } }
The output of the program is:
Yummy! you eat some apple Yummy! you eat some raspberry
The code explained
First we create the interface
FoundObject with the sole purpose to denote the objects of specific type, so we can put them in the same array. We create the
Eatable interface to mark which objects can be eaten.
When we create the three objects (apple, raspberry and stone) we put
implements FoundObject in the class declaration for all of them, and the one we can eat also implement the
Eatable interface.
In
WoodsSurvival class we first create an array of type
FoundObject. The three object we create later are also of type
FoundObject so we can put them in the same array. Follow this article to learn more about Java arrays.
When we iterate the array we check if the current object is of type
Eatable. We do this with the help of
instanceof keyford.
instanceof returns true if two objects are of the same type. In our case apples and raspberries will return true when checked with
instanceof Eatable, because both implement the
Eatable interface. To be able to execute the
eat() method we need to explicitly typecast the object to
Eatable first. We achieve this with following line of code:
((Eatable) currentObject).eat();
We can not execute the eat method of a stone object, because it is not of type
Eatable.
Disclaimer
The code example above can be written in more fashionable way using abstract classes, Collections and inheritance. Some of those are more advanced topics and are explained in next tutorials. This is a beginner tutorial that intents to explain java interfaces only.
Thanks!
Its a good start. thanks for your post…
|
https://javatutorial.net/java-interface-example
|
CC-MAIN-2019-43
|
en
|
refinedweb
|
This site works best with JavaScript enabled. Please enable JavaScript to get the best experience from this site.
Quote from Fluffgar
For some reason I can access World Options in game but when I go into Options the button to edit global options is not there.
Quote from Fluffgar
I'm using Magic Launcher. Here's what my setup looks like:
Quote from ottoguy2
Could you upoad the GuiApi patch source?
Think I will be on here often? Haha no.
Quote from terra_ff6
The GUI-API patch doesn't work for me, when I go to options minecraft crashes.
Quote from Dastot
After finally finding Nature Overhaul again after so long, I tried to readd it, noticing I needed the MOAPI I downloaded it and th e GUIAPI Patch. Before adding the patch I tried it, I got the same as I do after adding it...
--- java.lang.NoClassDefFoundError: moapi/ModOption
--- Caused by: java.lang.ClassNotFoundException: moapi.ModOption
Quote from WyrdOne
These errors indicate the MOAPI is not loaded into your jar file. You have to copy all the files in the client version of MOAPI into your jar file, including the moapi folder, it needs to stay in the folder inside the jar file.
Quote from roblox2852
So if this has been updated. when will Nature Overhaul be updated? I REALLY want that mod! I never got to try it before it went out of date D:
Quote from WyrdOne
Nature Overhaul was updated by another person, however there are bugs they have not been able to work out. It's looking like the original author is coming back soon and hopefully we will be collaborating with him to get the mods updated and keep them up to date.
Quote from WatcherInTheShadows
This one still operational?
I ask because I need a version with a compatibility patch with guiapi.
The original author's update does not have one at the moment.
Quote from WyrdOne
My version is still there for download, and should still work fine for version 1.2.5.
Regular users please go to the Installation section
Developers please go to the Developers section
Installation:
If you came here because a mod you want to use requires this API be installed, then follow these installation instructions for the client:
Install older versions:
Windows: <your user folder>\AppData\Roaming\.minecraft\bin\ or
<your user folder>\Application Data\.minecraft\bin\
Mac: Home -> Library -> Application Support -> Minecraft -> bin
Linux: ~/.minecraft/bin/
2. Open the minecraft.jar file in WinRAR or 7zip (do not extract it)
3. Extract the contents of the ModOptionsAPI ZIP file.
4. Copy the files into your minecraft.jar
Note: Select the files AND folder "moapi" and drop them in,
do not open the folder "moapi" and copy those files separately,
it will make minecraft crash.
5. Delete META-INF folder IF it exists in the minecraft.jar
6. Install your other mods per their instructions.
7. Run Minecraft
Compatibility:
Usage
These options affect every world/server you are on (depending on how the mod is designed) and can be overridden by local options.
Local Options (server/world)
These options affect ONLY the world you are on, or the server. If they are set to GLOBAL they will use the value set in the global options. Otherwise, they override the global values.
If the option is not available in singleplayer, or multiplayer, the mod creator has choosen to disable it locally.
Finally, to put a value back to GLOBAL, right click it.
Mods using this API:
MOAPI is included in the Ultimate API Mod Pack.
Developers
If you are a developer who wants to use this API, then read on.
NOTE: The package name was changed from moapi/moapi.gui in version 1.4.2 to moapi/moapi.client in version 1.5. These changes were made to allow a server version. There is now also a moapi.server package.
Examples and source files are located on Github.
The Mod Option API (MOAPI) is designed to make it easier for users to change options for the mods they have loaded. It hooks into the option screens and gives the user a list of the mods that use the API and whichever options those mods expose. The user won't need to worry about editing config files directly anymore.
Older versions:
1.5.1 version
1.5 version
Client (1.4.6) version
Client (1.4.4) version
Client (1.4.2) version
Client (1.3.2) version
1.3.1 Client version
1.2.5 Client version
Even older versions can be found in the original author's thread.
Using this API:
Inside your "mod_*" file you need to do the following:
import moapi.*;
To create your options you need to do the following:
// Sets up an option entry for "Mod Name", mod options will be added underneath it.
options = ModOptionsAPI.addMod(options);
Then to add your options:
// Adds a toggle named "Enable Mod" and sets it's default value to false.
options.addBooleanOption("Enable Mod").setValue(false);
To get the option value, just check it with the following:
// Gets the value of the "Enable Mod" toggle, a boolean.
options.getBooleanValue("Enable Mod")
There are also slider options, text options, but boolean toggle options are pretty simple to use.
Screenshots (Just for the no pics, no clicks folks):
If anyone has trouble getting this mod to work, let me know and I will do what I can to figure out what is going on.
Permission is granted to include this mod into mod packs, just make sure to link back here.
What other mod(s) do you have loaded? If another mod replaced one of the class files, it would possibly have that effect.
Try moving MOAPI to after Nature Overhaul, I noticed he included some of the MOAPI files in his download, which may be causing conflicts.
I have included the guiapi-patch source file in the developer version for those that need it to make the mod work with other mods or mod collections. (please do link back to this topic as well as the original authors, since this has the updated mod)
Think I will be on here often? Haha no.
What mods are you loading? Do you have a crash report?
ModLoader 1.2.5
mod_4096Fix v4 for 1.2.5
mod_Armor 1.2.5
mod_BossCraft BossCraft 1.4.5
mod_BuildCraftCore 3.1.5
mod_BuildCraftBuilders 3.1.5
mod_BuildCraftEnergy 3.1.5
mod_BuildCraftFactory 3.1.5
mod_BuildCraftTransport 3.1.5
mod_BuildCraftSilicon 3.1.5
mod_CodeChickenCore 0.5.2
mod_CraftingTableIII (Beta1.5, MC1.2.5)
mod_mocreatures v3.6.1 (MC 1.2.5)
mod_IDResolver 1.2.5 - Update 0
mod_InvTweaks 1.41b (1.2.4)
mod_MinecraftForge 3.1.3.105
mod_ModLoaderMp 1.2.5v1
mod_lectern 1.2.5
mod_tome 1.2.5
mod_xpbook 1.2.5
mod_Zeppelin 1.2.5.0.30
mod_NotEnoughItems 1.2.2
mod_Railcraft 5.2.1
mod_RedPowerControl 2.0pr5b1
mod_RedPowerCore 2.0pr5b1
mod_RedPowerLighting 2.0pr5b1
mod_RedPowerLogic 2.0pr5b1
mod_chocobo 1.6.9
mod_RedPowerMachine 2.0pr5b1
mod_MineAndBlade Battlegear - 0.1.6.1 [1.2.5]
mod_Somnia v24 [1.2.5]
mod_ReiMinimap v3.0_06 [1.2.5]
mod_RedPowerWiring 2.0pr5b1
mod_RedPowerWorld 2.0pr5b1
mod_ChefCraftory 1.2.5
mod_FarmCraftory 1.2.5
mod_FishCraftory 1.2.5
mod_FruitCraftory 1.2.5
mod_GUICraftory 1.2.5
mod_SeasonCraftory 1.2.5
mod_Shelf 1.2.5
mod_stevescarts 1.2.0
mod_Timber 1.2.4
mod_TwilightForest 1.9.0
mod_HeroesGuild 1.3.0
mod_EE 1.4.4.0
Minecraft has crashed!
----------------------
Minecraft has stopped running because it encountered a problem.
--- BEGIN ERROR REPORT 81f1d9e3 --------
Generated 15/05/12 8:18 PM
Minecraft: Minecraft 1.2.5
OS: Windows 7 (x86) version 6.1
Java: 1.7.0_04, Oracle Corporation
VM: Java HotSpot(TM) Client VM (mixed mode), Oracle Corporation
LWJGL: 2.4.2
OpenGL: GeForce 9600 GT/PCIe/SSE2 version 3.3.0, NVIDIA Corporation
java.lang.NoClassDefFoundError: moapi/ModOption
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Unknown Source)
at java.lang.Class.getDeclaredFields(Unknown Source)
at ModLoader.setupProperties(ModLoader.java:1763)
at ModLoader.addMod(ModLoader.java:293)
at ModLoader.readFromModFolder(ModLoader.java:1276)
at ModLoader.init(ModLoader.java:887)(Unknown Source)
Caused by: java.lang.ClassNotFoundException: moapi.ModOption)
... 13 more
--- END ERROR REPORT 8c36e47e ----------
These errors indicate the MOAPI is not loaded into your jar file. You have to copy all the files in the client version of MOAPI into your jar file, including the moapi folder, it needs to stay in the folder inside the jar file.
Nature Overhaul was updated by another person, however there are bugs they have not been able to work out. It's looking like the original author is coming back soon and hopefully we will be collaborating with him to get the mods updated and keep them up to date.
I ask because I need a version with a compatibility patch with guiapi.
The original author's update does not have one at the moment.
Awesome.
Thank you very much sir.
|
https://www.minecraftforum.net/forums/mapping-and-modding-java-edition/minecraft-mods/1282862-1-6-2-moapi-modoptionsapi
|
CC-MAIN-2019-43
|
en
|
refinedweb
|
After installing the Felgo SDK like described in Felgo Installation, create a new project with File/New. Choose the Empty Felgo 2 Project like it is shown in the image below.
Now specify a project location, build targets (Kits) and project details.
Note: The App identifier can only contain uppercase or lowercase letter, numbers or periods to succeed to the next step. See the license information in the publishing documentation for more information about the identifier.
Afterwards, the main.qml file is opened which contains the GameWindow and Scene components which is the basis for every resolution-independent Felgo game.
The Qt Creator IDE is a powerful development environment available for all desktop systems including Windows, Mac and Linux. For a full documentation of Qt Creator see the Qt Creator Manual.
On the left sidebar the main edit modes are available:
The integrated help is the primary source for documentation about the Felgo Games. There are 2 ways to use the integrated help of Qt Creator:
Ctrl+7
F1. This will automatically search the integrated help and open the help window. This is the suggested work-flow as it is quicker than searching the web or the index manually, because you are directly navigated to the documentation of the component, method or property.
To get out most of Qt Creator, the following shortcuts are very useful:
It is also convenient to split the Projects-View on the left side into a Projects-View PLUS an Open Documents-View. Just select the Split button next to the Close button of the Projects-View and then change Projects to Open Documents..
In this section we will cover the mere basics of QML and will create a custom button and place it in a screen-resolution-independent Scene.
First of all, clear the content of the main.qml, we will add our own code.
The most basic Felgo application consists of a GameWindow and a Scene, like this:
import Felgo 3.0 // for accessing the Felgo gaming components import QtQuick 2.0 // for accessing all default QML elements GameWindow { Scene { } }
We are now adding a simple button with the following source code:
import Felgo 3.0 // for accessing the Felgo gaming components import QtQuick 2.0 // for accessing all default QML elements GameWindow { Rectangle { // background rectangle filling whole screen with black color color: "black" anchors.fill: parent } Scene { Rectangle { color: "lightgrey" x: 100 y: 50 width: 100 height: 40 Text { text: "Press me" color: "black" anchors.centerIn: parent } } } }
Just press the green run button on the bottom left of Qt Creator and the application will launch!
The code example shows some of the QML characteristics:
Let's go one step further and make the button click-able and let it follow user touches. There exists a component that handles touch or mouse input: MouseArea.
Let's assume the text of the Text element should change to
Pressed when the user clicks the button, the color should turn green and the button should follow the mouse. Sounds complicated? Well it's as easy as
that:
Rectangle { id: button color: "lightgrey" x: 100 y: 50 width: 100 height: 40 Text { id: buttonText text: "Press me" color: "black" anchors.centerIn: parent } MouseArea { id: buttonMouseArea anchors.fill: parent // make the touchable area as big as the button drag.target: button // this forwards the dragging to the button onPressed: { // change the properties button.color = "blue" buttonText.text = "Pressed" } onReleased: { // reset to initial property values button.color = "lightgrey" buttonText.text = "Press me" } } }
You can see that references to other components are handled with the
id property. Items are accessible with this id from the whole qml file and thus it must be unique, otherwise an error is reported.
We can now extend this example to count how often the button was pressed and display the amount in another text element, and show an image after it got pressed at least 6 times. Therefore we need to define an own property
pressCount and are using a great feature of QML called property propagation: When a property changes its value, it can send a signal to notify others of this change. You can listen to that change by adding a
on<PropertyName>Changed signal handler like the following:
Rectangle { id: button color: "lightgrey" x: 100 y: 50 width: 100 height: 40 onXChanged: console.debug("x changed to", x) }
The great thing is, you can put arbitrary complex JavaScript expressions into the signal handlers, which allows listening to state changes and thus fast, readable and very little code in your games. In addition, changes of properties are detected automatically if you put them inside an expression. This may sound complex at first, but let us have a look at the solution for the above example:
Scene { id: scene property int pressCount: 0 // initialize with 0, increase in onPressed Text { text: "PressCount: " + scene.pressCount // this will automatically update when pressCount changes color: "#ffffff" // white color, open up color picker with Ctrl+Alt+Space } Image { // position the image at the right center anchors { right: parent.right verticalCenter: parent.verticalCenter } source: "felgo-logo.png" visible: scene.pressCount>5 // only display when pressCount is bigger than 5 } MouseArea { onPressed: { // change the properties button.color = "blue" buttonText.text = "Pressed" scene.pressCount++ // increase pressCount by 1 } } }
So the image will only be visible when the button was pressed at least 6 times, and the text will automatically change whenever the
pressCount property gets changed. This is the result how it will look like:
There are many more items available in QML, but the above mentioned are the most important. For a list of most useful QML components see here. In addition to these QML items, you can use the Felgo Games which are specialized for 2D games.
In the next guide, we examine the most important Felgo Games and will create a simple game using physics, particle effects and audio across all platforms. Follow the link to Entity Based Game Design
Voted #1 for:
|
https://felgo.com/doc/felgo-qml-and-qtcreator-usage/
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
I am having difficulties getting Slide Transitions to work. Is their any example code available?
Slide Transitions
Dear Chrons,
I’m sorry, we don’t have any examples for Slide Transition yet.
I will write and publish it today or tomorrow.
Dear Chrons,
Probably you had a problems with slide transition effects because it was possible only read and change slide effects. Please try 1.6.5 hot fix. Now you can define new effects even if slide didn’t have it before.
Thanks that solved that problem; however is the same true for shape entry effects? I am having difficulties getting them to work as well.
Dear Chrons,
For the shape entry effects you should define new Shape.AnimationSettings.EntryEffect at first.
After that effect will be created and you will have possibility to change other properties.
If you set EntryEffect to None then effect will be deleted and other properties will be unavailable again.
I am still not getting the shape entry effects to work. Do you have any example code?
Thanks.
Dear Chrons,
I’m sorry, it was my fault. I used wrong default values for creating internal animation records.
Please check 1.6.6 hot fix.
For example you have some PictureFrame (pf) on a slide:
// At first you should define new entry effect
pf.AnimationSettings.EntryEffect = ShapeEntryEffect.FlyFromBottom;
// Set number of slides where shape will be animated. It’s a new property.
pf.AnimationSettings.AnimationSlideCount = 1;
// Set advance mode. For example on mouse click
pf.AnimationSettings.AdvanceMode = ShapeAdvanceMode.AdvanceOnClick;
pf.AnimationSettings.AdvanceTime = 0;
// And set animation order
pf.AnimationSettings.AnimationOrder = 1;
Hello once again...
Thanks for that hot fix, it works great. Although I have one more problem I hope that you can address. In the example above you used
pf.AnimationSettings.AdvanceMode = ShapeAdvanceMode.AdvanceOnClick;
I can not find anything like SlideAdvanceMode.AdvanceOnTime to set (an instance of a slide).AnimationSettings.AdvanceMode equal to. Am I just not looking in the right spot?
I am sure I am becoming a bother by now but thanks in advance.
Dear Chrons,
Slide can have both advance modes in one time. Please use something like this:
// Set advance on time mode active
slide.SlideShowTransition.AdvanceOnTime = true;
// Set advance time to 10 seconds
slide.SlideShowTransition.AdvanceTime = 10.0;
I think that I may have found a bug.
I am trying to set a slides background to a patter style with the following code.<?xml:namespace prefix = o
Slide slide2 = GetSlideByPosition(pres, 2);
slide2.FollowMasterBackground = false;
slide2.Background.FillFormat.ForeColor = Color.Red;
slide2.Background.FillFormat.BackColor = Color.Green;
slide2.Background.FillFormat.Type = FillType.Pattern;
slide2.Background.FillFormat.PatternStyle = PatternStyle.Divot;
What happens is that slide 2 get the Divot style background; however the backcolor is always Dark Blue and the ForeColor is which ever I set last, in my example code above "Green" would be the ForeColor. But if I restructured my code like so:
slide2.Background.FillFormat.BackColor = Color.Green;
slide2.Background.FillFormat.ForeColor = Color.Red;
Red would be the ForeColor.
Thanks.
Dear Chrons,
It’s not a bug.
After changing FillFormat.Type other properties are reset to the default values.
Alexey,
Even when I change my code to the following the background is the color that is set last for example:
Slide slide2 = GetSlideByPosition(pres, 2);
slide2.FollowMasterBackground = false;
slide2.Background.FillFormat.Type = FillType.Pattern;
slide2.Background.FillFormat.PatternStyle = PatternStyle.Divot;
slide2.Background.FillFormat.BackColor = Color.Yellow;
slide2.Background.FillFormat.ForeColor = Color.Red;
Yields a slide with the Divot pattern, a Red fore ground and a dark Blue background.
The code in the follow example:
Slide slide2 = GetSlideByPosition(pres, 2);
slide2.FollowMasterBackground = false;
slide2.Background.FillFormat.Type = FillType.Pattern;
slide2.Background.FillFormat.PatternStyle = PatternStyle.Divot;
slide2.Background.FillFormat.ForeColor = Color.Red;
slide2.Background.FillFormat.BackColor = Color.Yellow;
Yields a slide with the Divot pattern, a Yellow foreground and a Dark Blue background.
Why do I always end up with a Dark Blue background?
Thanks for your help,
Chrons<?xml:namespace prefix = o ns = “urn:schemas-microsoft-com:office:office” /><o:p></o:p>
Dear Chrons,
Please check 1.6.8 hot fix:
|
https://forum.aspose.com/t/slide-transitions/110679
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
paintEvent is not painting complete objects
I am trying this piece of code below:
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QLabel>
#include <QPainter>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
void paintEvent(QPaintEvent *e); void operation(); void drawLabel(); int flag = 0; int startX, startY; QString labelText;
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *e)
{
QPainter *painter = new QPainter(this);
if(flag == 1)
{
painter->setPen(QPen(Qt::black, 1));
painter->drawLine(startX, startY, startX+30, startY);
painter->drawLine(startX+50, startY, startX+80, startY);
drawLabel();
}
}
void Widget::drawLabel()
{
QLabel *label = new QLabel(this);
label->setStyleSheet("border: 1px solid black");
label->setGeometry(startX+30, startY-10, 20, 20);
label->setText(labelText);
label->show();
}
void Widget::operation()
{
int found = 1;
if(found) { labelText = "2"; startX = 20; startY = 50; flag = 1; update(); labelText = "3"; startX = 100; startY = 50; flag = 1; update(); }
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.operation();
w.show();
return a.exec();
}
I want to draw a label between two lines side by side, but when I run the above code label with labelText 3, between two lines is visible. labelText 2, between two lines is not painted. I don,t understand why? Can anybody help me to solve this?
- raven-worx Moderators last edited by raven-worx
@NIXIN
you are doing multiple mistakes in your code.
- you are creating widgets on every paintEvent call! This is very bad design.
- in your Widget::operation() you update your data and call update() to immediately set the data again and call update() again. You should know that update() schedules a paint-event, where multiple calls to update() still result in a single paint-event (in the next event loop iteration). So it doesn't repaint immediately. There is a repaint() method for this, but as i said you already have a bad design by creating widgets on every paintEvent call.
You should draw the text using QPainter instead creating a QLabel every time. But still the label text "2" would never be rendered, since you immediately overwrite it afterwards.
can you provide a small piece of code, how to do it?
- raven-worx Moderators last edited by raven-worx
void Widget::paintEvent(QPaintEvent *e) { QPainter painter(this); // do create the painter on the stack .... drawLabel( p ); } void Widget::drawLabel(QPainter & p) { QRect rect(startX+30, startY-10, 20, 20); p.setPen( QPen::QPen(Qt::black, 1.0, Qt::SolidLine) ); p.setBrush( Qtt::NoBrush ); p.drawRect( rect ); p.drawText( rect, Qt::AlignCenter, labelText ); }
But as i said, this only draws the last label text set. You should store your data (position, label text,...) in a list (and call update() once). And draw each using drawLabel() for example.
That's fine, what I want to know is how to not delete the drawing from previous paintevent,
because as per your statement:
" But still the label text "2" would never be rendered, since you immediately overwrite it afterwards."
I want to keep the drawing for both:
if(found)
{
labelText = "2";
startX = 20;
startY = 50;
flag = 1;
update();
labelText = "3"; startX = 100; startY = 50; flag = 1; update();
}
- raven-worx Moderators last edited by
@NIXIN
as i said store your data (e.g. struct) in a list and draw each item separately while iterating over the list in the paintEvent()
Can you please provide a small code
- raven-worx Moderators last edited by
@NIXIN
come on thats not that hard...
struct Data { Data(QString t, int x, int y, int f) : labelText(t), startX(x), startY(y), flag(f) { } QString labelText;; int startX;; int startY; int flag; } QList<Data> dataList; ... void Widget::operation() { int found = 1; if(found) { dataList.clear(); dataList << Data("2", 20, 50, 1); dataList << Data("3", 100, 50, 1); update(); } } void Widget::paintEvent(QPaintEvent *e) { QPainter painter(this); // do create the painter on the stack .... foreach( Data d, dataList ) drawLabel( p, data ); } void Widget::drawLabel(QPainter & p, const Data & d) { QRect rect(d.startX+30, d.startY-10, 20, 20); p.setPen( QPen::QPen(Qt::black, 1.0, Qt::SolidLine) ); p.setBrush( Qt::NoBrush ); p.drawRect( rect ); p.drawText( rect, Qt::AlignCenter, d.labelText ); }
- Jan-Willem last edited by
Perhaps this might be also useful?
- VRonin Qt Champions 2018 last edited by
How about composing the widget instead of painting it.
Put two QFrame with a HLine style and a label in a QVBoxLayout. So much easier!
- Jan-Willem last edited by
@VRonin Depends on what he wants to achieve.
Is it a widget, than I agree with you.
Is it some CAD-drawing (looks like a diagram symbol to me), then I would prefer drawing.
For the latter the Graphics View Framework would be more practical though.
|
https://forum.qt.io/topic/70911/paintevent-is-not-painting-complete-objects/11
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
In this short lesson, I'll show you how to improve your game with Flurry analytics and how to integrate it in your game in less than 5 minutes. Flurry is one of the Qt Plugins we provide for iOS & Android and is the leading 3rd party product for mobile app and game analytics.
In the next sections you will learn what you can do with Flurry and how this helps you:
Track: How long your users stay in your app.
Benefit: Measure if your app updates increase the time spent by the users of your app, so if your update was successful.
Implementation: This is done automatically by the Felgo Flurry plugin for you.
Track: How your player retention increases with new app updates.
Benefit: Helps to measure if your app updates make your users return more often.
Implementation: Again, this is done automatically by our Flurry plugin for you.
Track: What users do in your app.
Benefit: Helps to optimize the flow of your app and identify if some of your screens are not used by your users. It also helps to focus on the screens where your users spend the most time with. It also helps you to understand how many users take a certain action in your game, like buying a level from the previous lesson about level store. ;)
This is also super-helpful for balancing, as it unveils when users stop playing your game because it may be too hard. If you see a big percentage of players stop at a particular level, you could then make that one easier so players stay in your game longer.
Implementation: Use logEvent() or logTimedEvent() to measure how long screens are shown or how often an action is performed.
Track: Demographics who is using your product: i.e. what gender or age your users have, from which country they are from and what other applications the users have installed.
Benefit: Helps you to target marketing for a specific user group to efficiently acquire new users.
Implementation: Flurry automatically detects the country and interests of your users and estimates the gender and age. If you have the age and gender available in your app (for example if your user connected with the Felgo Facebook plugin), you can manually provide this data for higher accuracy.
Track: Most efficient marketing channels.
Benefit: Helps you to focus on the marketing campaigns and ads that bring the most valuable users who stay in your app longest or spend the most.
Implementation: The Flurry plugin automatically tracks this for you after you set up your marketing campaigns in Flurry's web dashboard.
You can add the Flurry plugin to your project in less than 5 minutes! Here is how: Go to the Flurry website, create an account and a new app. Use the created apiKey for the next step.
In your QML app now add the Flurry item and add the import Felgo 3.0 on top of your main qml file. This example shows tracking how often a button is clicked:
import Felgo 3.0 GameWindow { Scene { Flurry { id: flurry // you get licenseKeys for your games for free with a Felgo license () licenseKey: "<generate-a-licensekey>" apiKey: "My_Felgo_App" } SimpleButton { onClicked: flurry.logEvent("Button1.Clicked") } } }
That's it from QML, pretty easy right?
Now it's time to test the analytics tracking. The Flurry plugin is supported on iOS and Android. If you did not install these platforms for you Qt installation yet, start with the Deployment Guide first.
Now follow the Flurry integration guide to add the plugin to the project.
If you purchased a Felgo license already, you can generate a licenseKey with the Flurry plugin here. Otherwise, change the app identifier to
com.felgo.plugins.FlurrySample. See here where to change the app identifier for iOS or Android.
Congrats! You can now see your tracked events in the Flurry web dashboard and start to improve your game. :)
In this lesson you have learned how to use the Flurry plugin to improve your app after you have published it in the stores. You know now which parts of your app you should focus on to improve and how to make your users stay longer in the app.
This is the last lesson in this crash course series. I hope you found this crash course valuable and now have a better understanding how Felgo can help you to make your next blockbuster game.
Did you like this learning series?
Would you like to receive more lessons like the previous ones? Are you interest in a particular topic for the next lesson? Then please let me know and send me an email to support@felgo.com.
Cheers, Chris from Felgo
Voted #1 for:
|
https://felgo.com/doc/lesson-9/
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
Introduction
In this article, we’ll look at how to unit test components built with Angular 2. Components are the centerpiece of Angular 2. They are the nucleus around which the rest of the framework is built. We’ll explore what a component is, why it is important, and how to test it.,
- You have Node >= v4 and NPM >= v3 installed while knowing how to run NPM scripts, and
- Have a setup capable of unit testing Angular 2 applications. If you need an explanation on how to do so, see the article Setting Up Angular 2 with Webpack. The structure used in this tutorial is available at this GitHub repository.
The Sample Project
Throughout this tutorial we will be creating a very simple application. Our application will allow users to provide an array of questions that will generate a form. Despite its simplicity, this will give us insight both into creating components as well as some other features of Angular 2, such as
NgModule and the forms package.
The final output will look similar to the following:
Before we dive into testing, let’s look at what components are and why they’re important for developing an Angular 2 application.
What are Components?
Many of the manufactured products we use every day were built using components. Let’s take a car for an example. It’s comprised of a few systems — braking, drive train, and engine — which are integrated together. These systems are then broken down into subsystems, which are broken into further subsystems until we get down to the nuts and bolts.
In software development, our programs are no different — they are just a set of systems, composed together to create a larger system. The term “component” is really just analogous term for system. Think of a blog post:
- Blog post
- Header
- Title
- By line
- Date
- Body
- Footer
- Categories
Each of the levels in the above list is really just a component. We can create a title component, by-line component, and date component. We then compose them together to create the header component. The header component, along with the body, footer, and comments components make up the whole blog post.
Why Use Components?
The larger an application gets, the more complexity it incurs and the more there is to manage. Components help us build web applications by providing the following advantages:
- Separation of concerns — developing the tags section of a blog post doesn’t necessarily need to be concerned with the details of developing the date display,
- Easier to manage — having small, focused components makes understanding what and where code exists, and
- Easier to unit test — testing our applications becomes component-based, making it easier to verify that, at each hierarchical level, our code is doing what we intended it to do.
The Components of Our System
Before developing a component we’ll need to identify what components our system has. We need to provide various ways of presenting a question:
- Single-line text,
- Multi-line text,
- Radio buttons, and
- Select list.
This will be our question component. We’ll be creating a dynamic form component which will act as the parent of the question component. The parent component of the form will be a top-level application component.
So we will end up with the following component structure:
- Application
- Form
- Question
Having a form component gives us the ability to expand our application in case we would want to add another aspect to our site, such as a results section.
Test-driven Development
We’ll be using test-driven development as we build our sample application. If you are unfamiliar with the term, take a look at the “Test-Driven Development” section of Setting Up Angular 2 with Webpack.
Generating a Dynamic Form
We are going to start by generating the form.
First, add a directory named
components to the
src directory which should be at the root-level of your project. In that directory, add another directory named
dynamic-form. Create two files in the
dynamic-form directory:
dynamic-form.component.ts and
dynamic-form.component.spec.ts.
dynamic-form.component.spec.ts file is going to contain all the tests needed to unit test the component’s code, which will live in
dynamic-form.component.ts. You may be wondering what “
spec” means. In short, specs are test files which, as we’ll see when we write our tests, read in a more natural way.
We’ll start by adding code to the spec file:
import { TestBed } from '@angular/core/testing'; import { FormGroup, ReactiveFormsModule } from '@angular/forms'; import { DynamicFormComponent } from './dynamic-form.component';
Our first step is to import dependencies. We have two sources we’re importing from —
@angular/core/testing and
./add.component. This import syntax is ES2015-specified.
The first source is from the Angular 2 core library. We’re pulling in the
TestBed class from it .
TestBed is the main entry to all of Angular’s testing interface. It will let us create our components, so they can be used to run unit tests.
We also pull in the
FormGroup and
ReactiveFormsModule classes.
FormGroup will just be used to test the type of a variable. The
ReactivesFormModule is a single-access point to many of the functions, classes, and attributes we need from Angular’s forms library. If you haven’t installed Angular’s forms library, go to your console and input the following:
npm i -S @angular/forms
The
./dynamic-form.component import source is our own file, which we will create in a moment. It’ll contain our
DynamicFormComponent class, which we will import here for use in our tests.
describe('Component: DynamicFormComponent', () => { let component: DynamicFormComponent;
Next, we’ll use Jasmine’s
describe function to tell Jasmine that we want to run a suite of tests. Then we’ll declare a variable,
component, which will eventually hold the reference to our
DynamicFormComponent.
This is the first spot where you may be seeing TypeScript in action. Not only are we using the ES2015
let keyword, but we’re also declaring that the type of
component will be an
DynamicFormComponent. All TypeScript type declarations look like this. If you see
a: B it just means the variable
a is of type
B.
beforeEach(() => { TestBed.configureTestingModule({ declarations: [DynamicFormComponent], imports: [ReactiveFormsModule] }); const fixture = TestBed.createComponent(DynamicFormComponent); component = fixture.componentInstance; });
Now, we’re getting more into using Angular. First, we use the
beforeEach function from Jasmine which tells the testing framework to run the function passed to it before each test.
We then set up our testing module using
TestBed.configureTestingModule. Our testing module needs access to the form classes, methods, and attributes that the
ReactiveFormsModule pulls in, so we import that in to our testing module configuration. We also need Angular to see our
DynamicFormComponent, so we declare that it will be used in our testing module.
Note that we could also have specified any part of
NgModuleMetadata, as you can see in the official documentation for more information.
Once we’ve set up our testing module, we’ll use
TestBed.createComponent to create our component. The
createComponent method actually returns a
ComponentFixture. Our component actually lives at the fixture’s
componentInstance attribute. So, we’ll set our
component variable to
fixture.componentInstance.
it('should have a defined component', () => { expect(component).toBeDefined(); });
First, we’ll add a simple test to see if our component was created. We use the Jasmine-provided
it function to define a spec. The first parameter of
it is a text description of what the spec will be testing — in this case we have a defined component. The second parameter is a function that will run the test.
We then use Jasmine’s
expect function to define our expectation. The expectations read just as they are written. In this spec, we expect that the
component will be defined.
If we wanted to test that it wasn’t defined, we could just write:
expect(component).not.toBeDefined();
To run our test, fire up your favorite terminal, navigate to your project and run
npm run test:headless
This will run the test through PhantomJS. To understand what
headless or PhantomJS is, take a look at the Unit Testing Dependencies section of Setting Up Angular 2 with Webpack.
Running it at this point will result in an error since we haven’t defined our
SingleLineComponent yet. Let’s do that:
import { Component } from '@angular/core';
In
single-line.component.ts we first pull in Angular’s
Component decorator which allows us to declare a class as a reusable component.
@Component({ selector: 'dynamic-form', template: '' }) export class DynamicFormComponent { }
We then use that component class to declare the most basic version of our component. We declare it’s selector as
dynamic-form which means that any parent component that would use it would put
<dynamic-form></dynamic-form> into its HTML template. For now, we declare an empty template, which we will fill in later.
If you’ve set your code up correctly, when you run your test, you should see output similar to:
Congratulations, you’ve created and tested your first Angular 2 component.
Our form will take in an array of questions and turn them into a form. In order to to create the form, we will need a common data model to define questions.
To do this, under the
src directory create a
models directory. In that directory, add a file name
question.model.ts. In that file, add the following code:
export interface Question { controlType: string; id: string; label: string; options: Array<any>; required: boolean; type?: string; value?: any; }
Create another file under
models named
index.ts and in that file put the following:
export * from './question.model';
This way, we will have a single point of access to our models, instead of pulling in each model file separately.
In our spec file, we’ll add another spec to test that when the
DynamicFormComponent initializes, it will create a
FormGroup for the list of passed in
questions array.
A
FormGroup is a container for
FormControls. When any of the
FormControls in a
FormGroup have an invalid state, the whole
FormGroup is also invalid.
In
dynamic-form.component.spec.ts, after the spec we wrote before, add the following:
it('should create a FormGroup comprised of FormControls', () => { component.ngOnInit(); expect(component.formGroup instanceof FormGroup).toBe(true); });
This test will simply call the
ngOnInit method of our component class . Once that method completes, we just test that the
formGroup attribute of the class is an instance of a
FormGroup.
With TDD we write just enough to application code to satisfy the test, so let’s do that. The new
dynamic-form.component.ts becomes:
import { Component, Input, OnInit } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { Question } from '../../models'; @Component({ selector: 'dynamic-form', template: '' }) export class DynamicFormComponent implements OnInit { @Input() questions:Array<Question>; formGroup: FormGroup; ngOnInit() { this.formGroup = this.generateForm(this.questions); } private generateForm(questions: Array<Question>): FormGroup { return new FormGroup({}); } }
A lot has changed here. First off, we are importing two more dependencies from Angular’s core library —
Input and
OnInit.
Input is a decorator that lets Angular know that an attribute of our class is a data-bound input property. This means that the value comes from a parent component. If a parent component was to use the following markup:
<dynamic-form [questions]="myQuestions"></dynamic-form>
The value that
DynamicFormComponent would have for
questions would be the value of the parent component’s
myQuestions attribute.
OnInit is a life-cycle hook. It is actually a class interface which we implement by adding a public
ngOnInit method in our class. Angular will run this method after our component’s data-bound inputs have been checked for the first time, but before any of the child components have been checked.
In the case of the
DynamicFormComponent, the
ngOnInit method is where we convert the passed-in questions into a
FormGroup full of
FormControls. To pass the test, we create an empty
FormGroup.
When you run the test, you should see green again. The next thing we need to test is that each of the questions is converted into a
FormControl. To do that, we’ll add another test:
it('should create a FormControl for each question', () => { component.questions = [ { controlType: 'text', id: 'first', label: 'My First', required: false }, { controlType: 'text', id: 'second', label: 'Second!', required: true } ]; component.ngOnInit(); expect(Object.keys(component.formGroup.controls)).toEqual([ 'first', 'second' ]); });
We set the array of questions passed in to the component. Next, we call
ngOnInit on the component. Finally, we pull the keys of the
questions attribute to get the controls that are part of the
FormGroup. We’ll set the keys for the set of
FormControls to the
id property of each question.
In
dynamic-form.component.ts, we need to update our imports from
@angular/forms to be:
import { FormControl, FormGroup, Validators } from '@angular/forms';
We’ll use
FormControl and
Validators in the updated application code. The rest of the application code to satisfy this is:
ngOnInit() { this.formGroup = this.generateForm(this.questions || []); } private generateForm(questions: Array<Question>): FormGroup { const formControls = questions.reduce(this.generateControl, {}); return new FormGroup(formControls); } private generateControl(controls: any, question: Question) { if (question.required) { controls[question.id] = new FormControl(question.value || '', Validators.required); } else { controls[question.id] = new FormControl(question.value || ''); } return controls; }
First, we updated the call to
generateForm to use an empty array if a questions value is not provided. If we didn’t do this our first test would fail.
Next, we updated
generateForm to use the
Array.r educe method to create an object of
FormControls. If you need more information on how
reduce works, take a look here.
The method the
reduce method uses is
generateControl. This function takes the controls object and the current question and creates the control with or without a required validator depending on if the question is required.
We then pass that
formControls object as the argument to our
FormGroup instantiation, which will set the
controls attribute of the
FormGroup to the
formControls object.
If everything is set up correctly, you should see green again.
We’ve now generated the different
FormControls needed to create the form, and now need a component to handle generating individual questions on the DOM.
Dynamically Generating Questions
We need two items to properly generate each question — the question itself and its
FormControl. The component structure of Angular allows us to attach values as properties to DOM objects. The component for displaying questions will be a
DynamicQuestionComponent with a selector of
dynamic-question. It will have a
form attribute and a
question attribute. It can be used as follows:
<dynamic-question [form]="form" [question]="question"></dynamic-question>
Our dynamic question component will only have one non-
Input attribute —
isValid, which will check if our control is valid. We will be able to use this method in the component DOM to output an error if the user has not entered a value in for a required field. We pass in the form instead of the control because Angular requires the parent
FormGroup to be referenced with the child
FormControl.
First, create a folder
dynamic-question under
src/components. Add 3 files:
dynamic-question.component.html,
dynamic-question.component.ts, and
dynamic-question.component.spec.ts.
Open up
dynamic-question.component.spec.ts and add the following imports:
import { TestBed } from '@angular/core/testing'; import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; import { Question } from '../../models'; import { DynamicQuestionComponent } from './dynamic-question.component';
Notice that the Angular testing imports are the same as the spec for creating the form. We also import the
DynamicQuestionComponent instead of the
DynamicFormComponent.
describe('Component: DynamicQuestionComponent', () => { let component: DynamicQuestionComponent; beforeEach(() => { TestBed.configureTestingModule({ declarations: [DynamicQuestionComponent], imports: [ReactiveFormsModule] }); const fixture = TestBed.createComponent(DynamicQuestionComponent); component = fixture.componentInstance; });
Again, similar to before, but substituting
DynamicQuestionComponent for
DynamicFormComponent.
it('should return true if the form control is valid', () => { const formControl = new FormControl('test'); component.control = formControl; expect(component.isValid).toBe(true); });
We’re testing that when the control is valid, the
isValid attribute returns
true.
Running the test will fail because we don’t have our component set up, so let’s do that. Just like our test, the setup will be similar to the
DynamicFormComponent.
import { Component, Input } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { Question } from '../../models'; @Component({ selector: 'dynamic-question', template: require('./dynamic-question.component.html') }) export class DynamicQuestionComponent { @Input() form: FormGroup; @Input() question: Question; get isValid(): boolean { return this.form.controls[this.question.id].valid; } }
There are some differences here. The first is that we’re only pulling in
Component and
Input from the core library. Additionally, we’re only pulling in
FormControl from the forms library.
Another difference is that the template attribute of the component is populated with
require('./dynamic-question.component.html'). This allows Webpack to pull in the HTML template file as a string and populate the
template attribute, creating a pseudo-inline template. We’ll come back and fill in the template after we’ve completed all our templates.
Additionally, we’re using the
get accessor to return the value of our control’s
valid attribute. To learn more about accessor methods, take a look at the TypeScript documentation.
Now, if we run our tests, we should be seeing green.
Filling in the HTML
We left the templates empty in our components. Let’s go back and fill them in.
Dynamic Question
The
dynamic-question.component.html file should be filled in with the following:
<div class="question" [formGroup]="form" [ngSwitch]="question.controlType"> <label [attr.for]="question.id">{{ question.label }}</label> <input class="control" [id]="question.id" [type]="question.type" * <select class="control" [id]="question.id" * <option [value]="answer.value" * {{ answer.label }} </option> </select> <textarea class="control" [id]="question.id" *</textarea> <div class="radio-group" * <span class="radio" * <input type="radio" [id]="question.id + answer.value" [value]="answer.value" [formControlName]="question.id"> <label [attr.for]="question.id + answer.value">{{ answer.label }}</label> </span> </div> <div class="error" * This question is required! </div> </div>
In this template, we learn a lot about Angular’s HTML templating system. You may have noticed all the square brackets in the template, and you may be wondering what they’re for. In Angular 2 templates, these square brackets denote an input binding. This means, for instance, that using:
[id]="question.id"
would bind the
question.id attribute to the DOM object’s
id property. In the same way, doing
[attr.for] binds to the DOM object’s
for attribute.
Another syntax form you may notice is the use of
* on some attributes. This syntax denotes a template. It basically says to use this markup as the template when the condition in quotes is met. We have couple ways its being used in the question template:
ngFor and
ngSwitchCase.
With
ngFor, we use the template for each item used in the array. For instance:
<option [value]="answer.value" * {{ answer.label }} </option>
We will loop through
question.options, assign it to the
answer variable and create an
option DOM element that uses
answer.value as the the option’s value and
answer.label as the option’s display text.
The
ngSwitchCase will use the DOM object it’s on when the value of the
[ngSwitch] binding at the top of the template equals the value in quotes. So, if the question’s
controlType is “textarea”, it would use the
textarea markup.
Angular 2 templates use the double-curly syntax for outputting variables, just like Angular 1.
Dynamic Form
We also have to create HTML for the
DynamicFormComponent. First, we need to update the component class to import the template. Change the
template attribute of
dynamic-form.component.ts to be as follows:
@Component({ selector: 'dynamic-form', template: require('./dynamic-form.component.html') })
Then, create the HTML file
dynamic-form.component.html in the
dynamic-form directory and fill in the following:
<form [formGroup]="formGroup" (ngSubmit)="submit()"> <div * <dynamic-question [form]="formGroup" [question]="question"></dynamic-question> </div> <div class="row"> <button type="submit" [disabled]="!formGroup.valid">Save</button> </div> </form> <pre *{{ payload }}</pre>
We create a form and let Angular know that we want to recognize our
DynamicFormComponent‘s
formGroup attribute as the
form‘s attribute of the same name. This helps attach validation to the
form if we want to utilize it.
Next, we just do an
ngFor loop over the
questions of our
DynamicFormComponent and create a
dynamic-questions for each one.
The parentheses around the
ngSubmit is new here. Those parentheses let us know that
ngSubmit is an event binding.
ngSubmit wraps the normal form
submit functionality, so that when our submit button fires off, the function specified for
ngSubmit will fire.
But our component class doesn’t have a
submit method. Let’s add it.
Adding Another Function and Its Test
If you were to run your unit tests at this point, you might come across some serious issues. This is because we’ve started using attributes, such as
ngFor or
formGroup, and we haven’t let Angular know that we are going to use them. To alleviate this, let’s add our bootstrapping code, where we’ll let Angular know what we’re going to use.
To make sure our tests work, we need to set up our tests to import those attributes. Let’s start with
dynamic-form.component.spec.ts.
First, we need to update our imports:
import { TestBed } from '@angular/core/testing'; import { FormGroup, ReactiveFormsModule } from '@angular/forms'; import { DynamicFormComponent } from './dynamic-form.component'; import { DynamicQuestionComponent } from '../dynamic-question/dynamic-question.component'; // ADDED
We’ve noted the line added and are now pulling in the
DynamicQuestionComponent, so that Angular knows it can be used by other components. To do this, we add
DynamicQuestionComponent to the list of
declarations in our testing module configuration.
beforeEach(() => { TestBed.configureTestingModule({ declarations: [DynamicFormComponent, DynamicQuestionComponent], imports: [ReactiveFormsModule] }); });
Finally, let’s add the submit test, after the “should create a
FormControl…” spec:
it('should set the payload to a stringified version of our form values', () => { component.questions = [ { controlType: 'text', id: 'first', label: 'My First', required: false }, { controlType: 'text', id: 'second', label: 'Second!', required: true } ]; component.ngOnInit(); component.formGroup.controls['first'].setValue('pizza'); component.submit(); expect(component.payload).toEqual(JSON.stringify({first: 'pizza', second: ''})); });
Here, we create a list of questions, initialize the component, and set
first‘s value — not
second‘s. We then call our
submit method and verify that it’s created our stringified JSON.
The application code to match this would be as follows:
submit() { this.payload = JSON.stringify(this.formGroup.value); }
Add it at the bottom of the component class.
You’ll also need to add a
payload: string declaration at the top of the class below the
formGroup declaration. You can, optionally, initialize the value to an empty string in
ngOnInit as well, but it won’t affect the test if you do not.
In the
submit method, all we do is that the
formGroup.value, which is an attribute that tracks the value of each
FormControl in a
FormGroup and run it through
JSON.stringify. We assign that to
payload and have some semblance of a submit method!
Run the tests one more time, and you’ve got it!
Making It Work in the Browser
At this point, we are unit tested and, for the most part, done. However, we need to create our overall application to get it working in the browser.
To do so, we’ll need to create an
AppComponent, create module using
NgModule that bootstraps that
AppComponent, and then bootstrap the module.
Let’s create our
AppComponent first.
App Component
Create an
app directory in
src/components and add two files,
app.component.html and
app.component.ts. In
app.component.ts, add the following code:
import { Component } from '@angular/core'; import { Question } from '../../models'; @Component({ selector: 'dynamic-form-app', template: require('./app.component.html') }) export class AppComponent { questions: Array<Question>; constructor() { this.questions = []; } }
This is pretty standard at this point, we created a basic component with a questions array. Populate this array with whatever questions you want to display in the form.
Next, in
app.component.html:
<h1>My Dynamic Form!</h1> <dynamic-form [questions]="questions"></dynamic-form>
We just use our
dynamic-form component to generate the form, and our
AppComponent is all set up.
App Module
The module system of Angular 2 is new as of RC5. If you are not familiar with the term, RC5 refers to Angular 2’s “Release Candidate 5”. Information about what’s changed for RC5 can be found on Angular 2’s changelog. It can also be added to a project by specifiying “2.0.0-rc.5” in your
package.json.
It uses the
NgModule dependency to compartmentalize a suite of functionality, such as our dynamic form, without needing to import every little dependency individually. In our tests above, when we were configuring our test modules, we were mimicking the
NgModule functionality per-component.
It consists of a TypeScript file, which we’ll add in
src with the filename
app.module.ts.
import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent, DynamicFormComponent, DynamicQuestionComponent } from './components'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent, DynamicFormComponent, DynamicQuestionComponent ], imports: [ BrowserModule, ReactiveFormsModule ] }) export class AppModule {}
We import
NgModule as well as the module containing the dependencies for handling forms and working in the browser. We also need to import all of our components.
Then, we set up our module class using the
NgModule decorator, telling it to use our
AppComponent to bootstrap the module while using the
declarations and
imports like we did in the tests, letting Angular know that we’ll need to use these dependencies within our application.
Bootstrapping the Application
The last and the easiest part is to bootstrap everything. Create a file named
bootstrap.ts under
src with the following code:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule);
We load
platformBrowserDynamic to do template processing and dependency injection. Then, we bootstrap our
AppModule.
If you go to a terminal and execute:
npm start
Your application should be available at
Continuous Testing
Nothing makes the development process feel as complete as having an continuous integration (CI) process in place. We’re going to use Semaphore as our CI service.
If you haven’t done so already, push your code to a repository on either GitHub or Bitbucket.
Once our code is committed to a repository, we can add a CI step to our Angular 2 development without much effort.
-. Using Semaphore makes testing and deploying your code continuously fast and simple.
Conclusion
In this article, we looked at the complexities of unit testing components. In the process, we developed a dynamic form component that could take in any number of questions and output a form. We created a crude submission method and saw how easy it is to integrate SemaphoreCI into our projects, taking only a few steps to get up and running. Webpack and SemaphoreCI stay out of your way and make your development process easy, keeping you focused on developing your Angular 2 applications.
If you’d like to see the final code, you can get it at this GitHub repository. Once you have the code pulled down, ensure you are seeing the correct version by running the following command from the project directory:
git checkout components
The application, though functional, leaves some room for improvement. We’re statically defining our questions, there’s a bit too much logic in the
DynamicFormComponent for turning questions into
FormControls, and our submit output goes nowhere. We’re going to improve that in the future tutorials. If you have any questions and comments, feel free to leave them in the section below.
|
https://semaphoreci.com/community/tutorials/testing-components-in-angular-2-with-jasmine
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
You can prepare two paddle images with the size of 20px*60px placed in your img folder.
Afterwards you create a Paddle.qml in the entities directory which includes a new EntityBase loading the paddle image comparable to the Ball.qml. Furthermore the Paddle can be used as player instance which means you have to add some player specific logic, such as: a playerID to identify the player or a MultiTouchArea which influences the entity using the users touch input.
import QtQuick 2.0 import Felgo 3.0 EntityBase { id: entity entityType: "paddle" // The ID of the player property int playerID : 0 // Save the score of the player property int score: 0 BoxCollider { id: boxCollider width: sprite.width height: sprite.height bodyType: Body.Static // Entity does not have width and height, therefore we center the CircleCollider in the entity. anchors.centerIn: parent // set friction between 0 and 1 fixture.friction: 0 // restitution is bounciness fixture.restitution: 1.0 } Image { id: sprite // use a inline if to decide which image should be loaded. source: playerID === 1 ? "../../assets/img/paddle_green.png" : "../../assets/img/paddle_blue.png" // this is the size compared to the scene size (480x320) - it will automatically be scaled when the window size is bigger than the scene // the image will automatically be scaled to this size anchors.centerIn: boxCollider } MultiTouchArea { // A bigger touch area should be used so the fingers of the user do not block the view width: sprite.width*4 height: sprite.height anchors.centerIn: sprite // the touch are should only be usable when a human is the player enabled: true // The target of this touch are is this paddle element // It changes the x,y position of the paddle multiTouch.target: parent // The paddle should move only into Y direction therefore block X direction multiTouch.dragAxis: MultiTouch.YAxis // limit the minimum and maximum of the touch area, because the // paddle should not move into the wall multiTouch.minimumY: level.y+level.blockHeight+sprite.height/2 multiTouch.maximumY: level.height-sprite.height/2-level.blockHeight } }
Two new player instances can be placed in the level now. Don't forget to create a player alias for each player instance you create in the level file. You may not want to place the paddles directly to the left and right wall, but you can add some deadzone. To get the right visibility you should insert the paddles in Level.qml after the background and before the ball instance.
... // this is needed so an alias can be created from the main window! property alias player1: player1 property alias player2: player2 property alias ball: ball // 3 Wall blocks for each player side. Use gameWindowAnchorItem for the correct scaling on different display sizes property int blockWidth: gameWindowAnchorItem.width/6 property int blockHeight: 10 // space from goal to paddle property int deadZone: blockWidth/2+10 ... // Player 1 is the right player Paddle { id: player1 playerID: 1 x: level.width-deadZone y: level.height/2 } // Player 2 is the left player Paddle { id: player2 playerID: 2 x: deadZone y: level.height/2 }
You should also add the player alias to the FelgoScene.qml so the players can be accessed from everywhere in the scene.
... width: 480 height: 320 property alias level: level property alias entityContainer: level property alias ball: level.ball property alias player1: level.player1 property alias player2: level.player2 ...
At the end it looks like a real game, and you already can play it with a friend, you just have to count the points on your own.
Counting on your own is exhausting and your opponent could betray you, so the next step is to add some game logic. One approach is to create a goal element which increases the player score and resets the ball. The Goal.qml in the entities directory is similar to the Wall.qml but with less Rectangles, because it isn't visible at all. It uses an additional property target which stores the target of the player who wins on collision.
import QtQuick 2.0 import Felgo 3.0 EntityBase { id: entity entityType: "goal" // player which should get a point is stored property variant target BoxCollider { id: boxCollider // the goal should not move bodyType: Body.Static fixture.onBeginContact: { target.score++ // restart the ball level.reStart() } } }
The new goal instance should be placed in your level between the ball and the first wall.
... Ball { id: ball x: gameWindowAnchorItem.width/2 y: parent.height/2 } // Right goal Goal { target: player1 height: parent.height width: deadZone anchors.left: parent.right anchors.bottom: parent.bottom } // Left goal Goal { target: player2 height: parent.height width: deadZone anchors.right: parent.left anchors.bottom: parent.bottom } // Left Player Top Wall { ...
The goals are placed outside the visible Scene to get a nicer visual effect of the ball hitting the edge.
You should also add a reset and end function to the end of the Level.qml which is used by the goal to reset the ball after hitting the edge. It uses a timer to provide some more preparation time before the ball gets respawned again.
... Timer { id: startTimer interval: 1000; onTriggered: { ball.reStart(gameWindowAnchorItem.width/2, parent.height/2) } } // Restarts the ball function reStart() { // move the ball to the middle and stop it ball.reset(gameWindowAnchorItem.width/2, parent.height/2) // restart ball after 1s startTimer.start() } // Ends the game function end() { player2.y = level.height/2 player1.y = level.height/2 ball.reset(gameWindowAnchorItem.width/2, parent.height/2) } ...
Great! The ball gets respawned after a point, but there is no display of the scores. A Heads Up Display - HUD would be the perfect thing for this task.
Voted #1 for:
|
https://felgo.com/doc/howto-pong-game-5/
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
On Sun, 2012-07-29 at 16:47 +0300, Avi Kivity wrote: > On 07/26/2012 08:40 PM, Alex Williamson wrote: > > On Thu, 2012-07-26 at 19:34 +0300, Avi Kivity wrote: > >> On 07/25/2012 08:03 PM, Alex Williamson wrote: > >> > >> > +/* > >> > + * Resource setup > >> > + */ > >> > +static void vfio_unmap_bar(VFIODevice *vdev, int nr) > >> > +{ > >> > + VFIOBAR *bar = &vdev->bars[nr]; > >> > + uint64_t size; > >> > + > >> > + if (!memory_region_size(&bar->mem)) { > >> > + return; > >> > + } > > > > This one is the "slow" mapped MemoryRegion. If there's nothing here, > > the BAR isn't populated. > > > >> > + > >> > + size = memory_region_size(&bar->mmap_mem); > >> > + if (size) { > >> > + memory_region_del_subregion(&bar->mem, &bar->mmap_mem); > >> > + munmap(bar->mmap, size); > >> > + } > > > > This is the direct mapped MemoryRegion that potentially overlays the > > "slow" mapping above for MMIO BARs of sufficient alignment. If the BAR > > includes the MSI-X vector table, this maps the region in front of the > > table > > If the region size is zero, then both memory_region_del_subregion() > (assuming the region is parented) and munmap() do nothing. So you could > call this unconditionally. I suppose parenting them is the key. I'm counting on memory_region_size of zero for an uninitialized, g_malloc0() MemoryRegion. Initializing them just to have a parent so we can unconditionally remove them here seems like it's just shifting complexity from one function to another. The majority of BARs aren't even implemented, so we'd actually be setting up a lot of dummy infrastructure for a slightly cleaner unmap function. I'll keep looking at this, but I'm not optimistic there's an overall simplification here. > >> > + > >> > + if (vdev->msix && vdev->msix->table_bar == nr) { > >> > + size = memory_region_size(&vdev->msix->mmap_mem); > >> > + if (size) { > >> > + memory_region_del_subregion(&bar->mem, > >> > &vdev->msix->mmap_mem); > >> > + munmap(vdev->msix->mmap, size); > >> > + } > >> > + } > > > > And this one potentially unmaps the overlap after the vector table if > > there's any space for one. > > > >> Are the three size checks needed? Everything should work without them > >> from the memory core point of view. > > > > I haven't tried, but I strongly suspect I shouldn't be munmap'ing > > NULL... no? > > NULL isn't the problem (well some kernels protect against mmaping NULL > to avoid kernel exploits), but it seems the kernel doesn't like a zero > length. in mm/mmap.c:do_munmap() I see: if ((len = PAGE_ALIGN(len)) == 0) return -EINVAL; Before anything scary happens, so that should be ok. It's not really worthwhile to call the munmaps unconditionally if we already have the condition tests because the subregions are unparented though. > >> > + > >> > +static void vfio_map_bar(VFIODevice *vdev, int nr, uint8_t type) > >> > +{ > >> > + VFIOBAR *bar = &vdev->bars[nr]; > >> > + unsigned size = bar->size; > >> > + char name[64]; > >> > + > >> > + sprintf(name, "VFIO %04x:%02x:%02x.%x BAR %d", vdev->host.domain, > >> > + vdev->host.bus, vdev->host.slot, vdev->host.function, nr); > >> > + > >> > + /* A "slow" read/write mapping underlies all BARs */ > >> > + memory_region_init_io(&bar->mem, &vfio_bar_ops, bar, name, size); > >> > + pci_register_bar(&vdev->pdev, nr, type, &bar->mem); > >> > >> So far all container BARs have been pure containers, without RAM or I/O > >> callbacks. It should all work, but this sets precedent and requires it > >> to work. I guess there's no problem supporting it though. > > > > KVM device assignment already makes use of this as well, if I understand > > correctly. > > Okay. > > > > >> > + > >> > + if (type & PCI_BASE_ADDRESS_SPACE_IO) { > >> > + return; /* IO space is only slow, don't expect high perf here */ > >> > + } > >> > >> What about non-x86 where IO is actually memory? I think you can drop > >> this and let the address space filtering in the listener drop it if it > >> turns out to be in IO space. > > > > They're probably saying "What's I/O port space?" ;) Yeah, there may be > > some room to do more here, but no need until we have something that can > > make use of it. > > Most likely all that is needed is to drop the test. > > > Note that these are the BAR mappings, which turn into > > MemoryRegions, so I'm not sure what the listener has to do with > > filtering these just yet. > > +static bool vfio_listener_skipped_section(MemoryRegionSection *section) > +{ > + return (section->address_space != get_system_memory() || > + !memory_region_is_ram(section->mr)); > +} > > Or the filter argument to memory_listener_register() (which you use -- > you can drop the first check above). On x86 those I/O regions will be > filtered out, on non-x86 with a properly-wired chipset emulation they'll > be passed to vfio (and kvm). Ah, I see what you're going for now. Sure, I can store/test the vfio region info flags somewhere to tell me whether vfio supports mmap of the region instead of assuming mem = mmap, io = ops. I'll re-evaluate unconditional removal after that. > >> > + > >> > + if (size & ~TARGET_PAGE_MASK) { > >> > + error_report("%s is too small to mmap, this may affect > >> > performance.\n", > >> > + name); > >> > + return; > >> > + } > >> > >> We can work a little harder and align the host space offset with the > >> guest space offset, and map it in. > > > > That's actually pretty involved, requiring shifting the device in the > > host address space and potentially adjust port and bridge apertures to > > enable room for the device. Not to mention that it assumes accessing > > dead space between device regions is no harm, no foul. True on x86 now, > > but wasn't true on HP ia64 chipsets and I suspect some other platforms. > > Are sub-4k BARs common? I expect only on older cards. Correct, mostly older devices. I don't think I've seen any "high performance" devices with this problem. > >> > + > >> > + /* > >> > + * We can't mmap areas overlapping the MSIX vector table, so we > >> > + * potentially insert a direct-mapped subregion before and after it. > >> > + */ > >> > >> This splitting is what the memory core really enjoys. You can just > >> place the MSIX page over the RAM page and let it do the cut-n-paste. > > > > Sure, but VFIO won't allow us to mmap over the MSI-X table for security > > reasons. It might be worthwhile to someday make VFIO insert an > > anonymous page over the MSI-X table to allow this, but it didn't look > > trivial for my novice mm abilities. Easy to add a flag from the VFIO > > kernel structure where we learn about this BAR if we add it in the > > future. > > I meant due it purely in qemu. Instead of an emulated region overlaid > by two assigned regions, have an assigned region overlaid by the > emulated region. The regions seen by the vfio listener will be the same. Sure, that's what KVM device assignment does, but it requires being able to mmap the whole BAR, including an MSI-X table. The VFIO kernel side can't assume userspace isn't malicious so it has to prevent this. > >> > + > >> > + > >> > +static Property vfio_pci_dev_properties[] = { > >> > + DEFINE_PROP_PCI_HOST_DEVADDR("host", VFIODevice, host), > >> > + //TODO - support passed fds... is this necessary? > >> > >> Yes. > > > > This is actually kind of complicated. Opening /dev/vfio/vfio gives us > > an instance of a container in the kernel. A group can only be attached > > to one container. So whoever calls us with passed fds needs to track > > this very carefully. This is also why I've dropped any kind of shared > > IOMMU option to give us a hint whether to try to cram everything in the > > same container (~= iommu domain). It's too easy to pass conflicting > > info to share a container for one device, but not another... yet they > > may be in the same group. I'll work on the fd passing though and try to > > come up with a reasonable model. > > I didn't really follow the container stuff so I can't comment here. But > suppose all assigned devices are done via fd passing, isn't it > sufficient to just pass the fd for the device (and keep the iommu group > fd in the managment tool)? Nope. containerfd = open(/dev/vfio/vfio) groupfd = open(/dev/vfio/$GROUPID) devicefd = ioctl(groupfd, VFIO_GROUP_GET_DEVICE_FD) The container provides access to the iommu, the group is the unit of ownership and privilege, and device cannot be accessed without iommu protection. Therefore to get to a devicefd, we first need to privilege the container by attaching a group to it, that let's us initialize the iommu, which allows us to get the device fd. At a minimum, we'd need both container and device fds, which means libvirt would be responsible for determining what type of iommu interface to initialize. Doing that makes adding another device tenuous. It's not impossible, but VFIO is design such that /dev/vfio/vfio is completely harmless on it's own, safe for mode 0666 access, just like /dev/kvm. The groupfd is the important access point, so maybe it's sufficient that libvirt could pass only that and let qemu open /dev/vfio/vfio on it's own. The only problem then is that libvirt needs to pass the same groupfd for each device that gets assigned within a group. > >> > + > >> > + > >> > +typedef struct MSIVector { > >> > + EventNotifier interrupt; /* eventfd triggered on interrupt */ > >> > + struct VFIODevice *vdev; /* back pointer to device */ > >> > + int vector; /* the vector number for this element */ > >> > + int virq; /* KVM irqchip route for Qemu bypass */ > >> > >> This calls for an abstraction (don't we have a cache where we look those > >> up?) > > > > I haven't see one, pointer? I tried to follow vhost's lead here. > > See kvm_irqchip_send_msi(). But this isn't integrated with irqfd yet. Right, the irqfd is what we're really after. > >> > + bool use; > >> > +} MSIVector; > >> > + > >> > + > >> > +typedef struct VFIOContainer { > >> > + int fd; /* /dev/vfio/vfio, empowered by the attached groups */ > >> > + struct { > >> > + /* enable abstraction to support various iommu backends */ > >> > + union { > >> > + MemoryListener listener; /* Used by type1 iommu */ > >> > + }; > >> > >> The usual was is to have a Type1VFIOContainer deriving from > >> VFIOContainer and adding a MemoryListener. > > > > Yep, that would work too. It gets a bit more complicated that way > > though because we have to know when the container is allocated what type > > it's going to be. This way we can step though possible iommu types and > > support the right one. Eventually there may be more than one type > > supported on the same platform (ex. one that enables PRI). Do-able, but > > I'm not sure it's worth it at this point. > > An alternative alternative is to put a pointer to an abstract type here, > then you can defer the decision on the concrete type later. But I agree > it's not worth it at this point. Maybe just drop the union and decide > later when a second iommu type is added. A pointer doesn't allow us to use container_of to get back to the VFIOContainer from the memory listener callback, so we'd have to create some new struct just to hold that back pointer. Alexey's proposed POWER support for VFIO already makes use of the union, so it seems like a sufficient solution for now. We'll have to re-evaluate if it's getting unwieldy after we get a few though. > >> > + void (*release)(struct VFIOContainer *); > >> > + } iommu_data; > >> > + QLIST_HEAD(, VFIOGroup) group_list; > >> > + QLIST_ENTRY(VFIOContainer) next; > >> > +} VFIOContainer; > >> > + > >> > + > >> > +#ifdef __KERNEL__ /* Internal VFIO-core/bus driver API */ > >> > >> Use the exported file, that gets rid of the __KERNEL__ bits. > > > > Oh? How do I generate that aside from just deleting lines? Thanks! > > > > make headers_install Thanks! Alex
|
https://lists.gnu.org/archive/html/qemu-devel/2012-07/msg04277.html
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
Hashable data types and why do we need those
Last Thursday we have done a short (2 hours long) video code review with veky. We haven't done any new one for while, so we had some issues with the sound. The last will be fixed for the next video and hopefully we will start doing those code reviews more regularly.
Veky starts with the review of his mission - Completely Empty. During this he explains a lot of things about hashes in Python for me, so I've decided to leave some notes in a separate blogpost.
First things fist. What is a hash? Hash is like a global index for objects in Python or integer interpretation of any Python object.
>> hash(40) <<< 40 >>> hash('cio') <<< -4632795850239615199 >>> hash((1,2,3)) <<< 2528502973977326415
Well, not any object, only immutable objects can have a hash (an exception will be shown in the and of the post). Don't worry if you don't know what is the difference between mutable and immutable objects and why mutable objects can't have hashes. I'll explain it later.
>> hash([1,2]) TypeError: unhashable type: 'list' >>> hash({‘a’: 1}) TypeError: unhashable type: 'dict'
Why do we need those indexes (hashes) in Python, especially with such restrictions? Python uses hashes in sets and in dict keys in order to quickly find values there and keep values unique. That's why a list or dict can't be an element of set or key of dict (an exception will be shown in the and of the post).
>> {[1,2]} TypeError: unhashable type: 'list' >>> {{}:1} TypeError: unhashable type: 'dict'
This is why values inside the set can't be mutable (an exception will be shown in the and of the post). Mutable means capable of change or of being changed. Here is a classical example that illustrates that the list is a mutable type:
>> a = [1,2] >>> b = a >>> b.append(3) >>> a <<< [1, 2, 3]
Which is impossible for tuple
>> a = (1,2) >>> a.append(3) AttributeError: 'tuple' object has no attribute 'append'
… because tuple is an immutable type, even if we try to trick Python
>> hash(a) <<< 3713081631934410656 >>> a = (1,2,3, []) >>> hash(a) TypeError: unhashable type: 'list' >>> {a} TypeError: unhashable type: 'list'
But Python still allows you to check if two lists are equal, right?
>> [1,2,3] == [1,2,3] <<< True >>> [1,2,3] == [1,2,2] <<< False
So why doesn't Python simply check whether two objects are equal or not before adding a new one into a set without caring about the object's mutability. First of all, it is not as fast as using hashes, and the second reason is that the mutable object can be changed after being added into a set.
Let's imagine we can add a list into set
>> a = [1,2] >>> b = [1] >>> wow = {a, b} >>> len(wow) <<< 2 >>> b.append(2) >>> a == b <<< True >>> len(wow) ???
If a and b are equal then what should be the length of the set wow? If 2, then how is it possible that the set contains not unique elements? If 1, then this is an unexpected behaviour.
That's why Python will raise an exception on line 3: wow = {a, b}
I hope we've given you a very simple explanation of hashable objects and why do we need them.
PS (StefanPochmann): Python is a very flexible language and you can define the method __hash__ for an object so it becomes hashable. In such a way we can get an answer to our previous question what will be the length of wow
>> class List(list):
def __hash__(self):
return hash(tuple(self))
>>> a = List([1,2])
>>> b = List([1])
>>> wow = {a,b}
>>> b.append(2)
>>> a == b
<<< True
>>> len(wow)
<<< 2
>>> wow
<<< {[1,2], [1,2]}
>>> len({a, b})
<<<
|
https://py.checkio.org/blog/hashable-data-types-and-why-do-we-need-those/
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
From: Caleb Epstein (caleb.epstein_at_[hidden])
Date: 2005-02-16 10:44:20
On Tue, 15 Feb 2005 23:11:49 -0500, Jason Hise <chaos_at_[hidden]> wrote:
>
> From everything I know, cin, cout, cerr, and clog are simply global
> variables that live in namespace std. Does this mean that the following
> code is dangerous?
AFAIK yes. If you have a singleton object that is being destroyed at
exit, it is possible that cin/cout/clog etc have been closed before
Log::~Log is called.
> class Log
> {
> public:
> Log ( ) { std::clog << "Log created\n"; }
> ~ Log ( ) { std::clog << "Log destroyed\n"; }
> } global_log;
>
> If so, (and I know this is presumptuous, so strictly hypothetically
> speaking) could these four standard streams benefit by becoming
> singletons? Just a thought experiment...
--
|
https://lists.boost.org/Archives/boost/2005/02/80534.php
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
Problem :
It has been a while since the last time Pak Dengklek painted the wall on his house, so he wants to repaint it. The wall consists of
NN segments, numbered from
00 to N - 1N−1. For this problem, we assume that there are
KK different colours, represented by an integer from
00 to K - 1K−1 (e.g., red is represented by
00, blue is represented by
11, and so on). Pak Dengklek wants to paint the
ii-th segment of his wall using the colour
C[i]C[i].
To paint the wall, Pak Dengklek hires a contractor company with
MM contractors, numbered from 00 to
M - 1M−1. Unfortunately for Pak Dengklek, contractors are only willing to paint the colours that they like. Specifically, the jj-th contractor only likes
A[j]A[j] colours and only wants to paint a segment to be coloured with either of the following colour: colour
B[j][0]B[j][0], colour
B[j][1]B[j][1], \ldots…, or colour
B[j][A[j] - 1]B[j][A[j]−1].
Pak Dengklek can give several instructions to the contractor company. In a single instruction, Pak Dengklek will give two parameters
xx and
yy, where
0 \le x \lt M0≤x<M and 0 \le y \le N - M0≤y≤N−M. The contractor company will instruct the
((x + l) \bmod M(x+l)modM)-th contractor to paint the
(y + ly+l)-th segment,
for 0 \le l \lt M0≤l<M. If there exists a value of
ll such that the
((x + l)
\bmod M(x+l)modM)-th does not like colour
C[y + l]C[y+l], then the instruction is invalid.
Pak Dengklek has to pay for each instruction he gives, thus he would like to know the minimum number of instructions he has to give to paint all segments with their intended colour or identify if it is impossible to do so. The same segment can be painted multiple times, but it must always be painted with its intended colour.
Task :
You have to implement
minimumInstructions function:
minimumInstructions(N, M, K, C, A, B)– This function will be called by the grader exactly once.
NN: An integer representing the number of segments.
MM: An integer representing the number of contractors.
KK: An integer representing the number of colours.
CC: An array of
NNintegers representing the intended colour of the segments.
AA: An array of
MMintegers representing the number of colours that the contractors like.
BB: An array of
MMarray of integers representing the colours that the contractors like.
- This function must return an integer representing the minimum number of instructions Pak Dengklek has to give to paint all segments with their intended colour, or -1−1 if it is impossible to do so.
Example :
In the first example,
N = 8N=8, M = 3M=3, K = 5K=5, C = [3, 3, 1, 3, 4, 4, 2, 2]C=[3,3,1,3,4,4,2,2], A = [3, 2, 2]A=[3,2,2], B = [[0, 1, 2], [2, 3], [3, 4]]B=[[0,1,2],[2,3],[3,4]]. Pak Dengklek can give the following instructions:
x = 1x=1, y = 0y=0. This is a valid instruction since the first contractor can paint the zeroth segment, the second contractor can paint the first segment, and the zeroth contractor can paint the second segment.
x = 0x=0, y = 2y=2. This is a valid instruction since the zeroth contractor can paint the second segment, the first contractor can paint the third segment, and the second contractor can paint the fourth segment.
x = 2x=2, y = 5y=5. This is a valid instruction since the second contractor can paint the fifth segment, the zeroth contractor can paint the sixth segment, and the first contractor can paint the seventh segment.
It is easy to see that Pak Dengklek cannot give less than 33 instructions to paint all segments with their intended colour, thus
minimumInstructions(8, 3, 5, [3, 3, 1, 3, 4, 4, 2, 2], [3, 2, 2], [[0, 1, 2], [2, 3], [3, 4]]) should return 33.
In the second example,
N = 5N=5, M = 4M=4, K = 4K=4, C = [1, 0, 1, 2, 2]C=[1,0,1,2,2], A = [2, 1, 1, 1]A=[2,1,1,1], B = [[0, 1], [1], [2], [3]]B=[[0,1],[1],[2],[3]]. Since the third contractor only like colour 33 and none of the segment is to be painted with colour 33, it is impossible for Pak Dengklek to give any valid instruction. Therefore,
minimumInstructions(5, 4, 4, [1, 0, 1, 2, 2], [2, 1, 1, 1], [[0, 1], [1], [2], [3]]) should return
-1−1.
Constraints :
For
0 \le k \lt K0≤k<K, let f(k)f(k) be the number of
jj such that the
jj-th contractor likes colour
kk. For example, if
f(1) = 2f(1)=2, then there are two contractors who like the colour 11.
1 \le N \le 100\,0001≤N≤100000.
1 \le M \le \min(N, 50\,000)1≤M≤min(N,50000).
1 \le K \le 100\,0001≤K≤100000.
0 \le C[i] \lt K0≤C[i]<K.
1 \le A[j] \le K1≤A[j]≤K.
0 \le B[j][0] \lt B[j][1] \lt \ldots \lt B[j][A[j] - 1] \lt K0≤B[j][0]<B[j][1]<…<B[j][A[j]−1]<K.
Sum of f(k)^2 \le 400\,000f(k)2≤400000.
Subtask 1 (12 points) :
f(k) \le 1f(k)≤1.
Subtask 2 (15 points) :
N \le 500N≤500.
M \le \min(N, 200)M≤min(N,200).
Sum of f(k)^2 \le 1\,000f(k)2≤1000.
Subtask 3 (13 points) :
N \le 500N≤500.
M \le \min(N, 200)M≤min(N,200).
Subtask 4 (23 points) :
N \le 20\,000N≤20000.
M \le \min(N, 2\,000)M≤min(N,2000).
Subtask 5 (37 points) :
- No additional constraints.
Sample Grader :
The sample grader reads the input in the following format:
N M K C[0] C[1] ... C[N-1] A[0] B[0][0] B[0][1] ... B[0][A[0]-1] A[1] B[1][0] B[1][1] ... B[1][A[1]-1] . . . A[M-1] B[M-1][0] B[M-1][1] ... B[M-1][A[M-1]-1]
The sample grader prints the value returned by the
minimumInstructions function.
Solution :
#include "paint.h" #include <bits/stdc++.h> #define sz(v) ((int)(v).size()) #define all(v) (v).begin(), (v).end() using namespace std; using lint = long long; using pi = pair<int, int>; const int MAXN = 200005; const int mod = 1e9 + 7; vector<int> use[MAXN]; // which worker can work on the color int minimumInstructions( int N, int M, int K, std::vector<int> C, std::vector<int> A, std::vector<std::vector<int>> B) { for(int i=0; i<M; i++){ for(auto &j : B[i]){ use[j].push_back(i); } } vector<pi> op(M); for(int i=0; i<M; i++){ op[i] = pi(-1e9, 0); } auto insert = [&](int i, int time){ if(op[i].first + 1 == time) op[i] = pi(time, op[i].second + 1); else op[i] = pi(time, 1); if(op[i].second >= M) return 1; return 0; }; vector<int> dp(N + 1); priority_queue<pi, vector<pi>, greater<pi> > pq; for(int i=0; i<N; i++){ pq.emplace(dp[i], i); dp[i + 1] = 1e9; bool good = 0; for(auto &j : use[C[i]]){ int kappa = (i - j + M - 1) % M; good |= insert(kappa, i); } if(good){ while(sz(pq) && pq.top().second < i + 1 - M) pq.pop(); dp[i + 1] = pq.top().first + 1; } } if(dp[N] > 1e8) return -1; return dp[N]; }
218 total views, 1 views today
Post Disclaimer
the above hole problem statement is given by apio2020.id but the solution is generated by the SLTECHACADEMY authority if any of the query regarding this post or website fill the following contact form thank you.
|
https://sltechnicalacademy.com/apio-2020-problem-and-solution-painting-walls/
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
Difference between revisions of "User talk:Dutchmega"
Latest revision as of 16:12, 4 October 2006
Contents
Fixing NPC's not bleeding
Look in AI_BaseNPC.cpp, around line 1020, look for the call to the function SpawnBlood. Remove IsPlayer() before it ;)
- Didn't work --General Eskimo
Well, in that case it gets harder... I don't know what I have changed in my code... You should do some debugging... is SpawnBlood() even called? And so, what color blood? (it shouldn't be DONT_BLEED) -- dutchmega
- >>> Hello guys. I had a friend whom asked me why the NPCs were not bleeding. I have fixed it by checking in the prediction system. Indeed, if you set cl_prediction 0, the NPCs will bleed ;o) ----Dolphin's Eye 16:42, 4 Aug 2006 (PDT)
- >>> OK. Anyway I retrieved the code fix. It was a prediction problem indeed. In file c_basecombatcharacter.cpp, in the BEGIN_RECV_TABLE function, I added:
RecvPropInt( RECVINFO( m_bloodColor ) ),
- And in the file baseentity_shared.cpp, in TraceAttack(), I changed to this :
void CBaseEntity::TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr ) { Vector vecOrigin = ptr->endpos - vecDir * 4; //***THOMAS*** NPCS & PLAYERS BLEEDING FIX #ifndef CLIENT_DLL if ( m_takedamage ) #else if ( prediction->InPrediction() ) #endif //*** { AddMultiDamage( info, this ); int blood = BloodColor(); if ( blood != DONT_BLEED ) { SpawnBlood( vecOrigin, vecDir, blood, info.GetDamage() );// a little surface blood. TraceBleed( info.GetDamage(), vecDir, ptr, info.GetDamageType() ); } } }
----Dolphin's Eye 16:42, 4 Aug 2006 (PDT)
Still need help on your Source MOD?
Hey, nice, another person from the Netherlands ^_^ Nice to meat you! :D I saw you were working on a MOD for the Source engine... I'm pretty good in making levels (by Valve Hammer). If you need someone to make levels, come to me :D Greetingz, CrabbyData 06:02, 6 May 2006 (PDT)
- I'll see you @ Gtalk --dutchmega
- *Roger that* --CrabbyData 09:12, 6 May 2006 (PDT)
- if you want a hand making a 'map' for the mod your working on just give me a call, im willing to help (even if its no good!) game4ever
- Well, I'm looking for good SP/co-op mappers, who can map HL2-quality. Hard to find... --dutchmega
- While I'm passing through, adding your page to the Help Wanted category ... Mapping "HL2-quality" isn't just a skill, it's also an incredible time commitment - hundreds of hours of work. You are having trouble finding people ... is your 'advertising' limited to what you set out in your user page?
- If that is so, my advice would be that you aren't saying enough to persuade people to even consider committing that quantity of time and you will be more successful in finding people if you write a better pitch. --Giles 05:11, 10 May 2006 (PDT)
- I also realize that but I start with active recruiting when the website is online --dutchmega
- any playtesters needed, just ask me. im a GOOD playtester... Game4ever 13:07, 14 Jun 2006 (PDT)
yo, dutchy!
hehehe, sorry about my comments, and its not hard to insult me (short-tempered) thanks for the advice (i.e. telling me that you think reading my posts are awful)
- game4ever
does anyone know how to put things bluntly? i dont know how to make a button to open a door yet, and have been looking for a long time (about half an hour i think) could someone put it bluntly (i.e. 1. open ...) please? game4ever
- Well, I'm not a mapper but there are enough mappers around here... --dutchmega
- I'll be able to help you ^^ I'll write a little tutorial on your Talk page (here)... --CrabbyData 15:16, 6 May 2006 (PDT)
howdy all quick question
ok total noob at mapping but have an uncle thats been doing mapping since counter strike was released. Just getting ahold of him is like trying to grab a cloud with your bare hands. Anyway my question is on building a map. wich is the easyest way to makeing a map i know how to make individual rooms but think thats going to take forever should i just make like a block ata time and chapter them together or build the whole thing at once and section each with a loading door?
- Lol, why are you asking mapping questions? You can see at my userpage that I'm a coder? --dutchmega
- Here I am again ;) Ok... *reading* ...Make it room-by-room, and connect them right away. If you're planning on HUGE HL2-quality maps, then I would indeed connect them with a little room that loads (like in HL2 chapters). Else I would just make normal rooms, with each one build after the other, and connecting them right away.
- who was this poster? Game4ever 13:05, 14 Jun 2006 (PDT)
- I got bored and checked your history, was CrabbyData Angry Beaver 20:30, 14 Jun 2006 (PDT)
- Yeah, sorry, that was me :P --CrabbyData 02:00, 15 Jun 2006 (PDT)
- and you go on at me for not signing my posts... *fakes anger* Game4ever 10:03, 15 Jun 2006 (PDT)
- mmm... *shakes head from left to right* not signing is different than signing the wrong way... --CrabbyData 10:56, 15 Jun 2006 (PDT)
- oopss..... lol Game4ever 09:30, 22 Jun 2006 (PDT)
Map Site Related
Would you send me an email so I have your address, please? Send to bjveazie(@)DELETEveazie.org. —BJ(talk) 09:26, 25 May 2006 (PDT)
- Just say your email is (deleted) It's that simple ;) --CrabbyData 09:28, 25 May 2006 (PDT)
- Sorry, but I get a lot of spam that I know is related to bots scanning various webpages for 'mailto:' labels! ;) —BJ(talk)
- Really? :P O, ok, sorry 'bout that then xD --CrabbyData 14:14, 25 May 2006 (PDT)
My email is at the userpage? --dutchmega 15:03, 25 May 2006 (PDT)
- So it is, Dutch. Re: spam - yes. I've posted on several forums with different email addresses (I have my own website so I can make up addresses as I go) and can tell where the spammers got my email address. By the way, I have a three-day weekend (Monday's a USA holiday) coming up. If there's something in particular I can work on, let me know. —BJ(talk) 17:16, 25 May 2006 (PDT)
- You could work on the .VMF-parser, (In PHP, if you don't mind...) which will give us info about the used entities, textures etc. Thanks for your great email :D It's been and still is a lot of help for me :D --CrabbyData 03:43, 26 May 2006 (PDT)
!player & NPC footsteps
Hi, could you please give me fix for !player messages and missing NPC footsteps ? I've no idea how to fix them, so please help :O( Thanks in advance.. --Vaber 08:00, 28 May 2006 (PDT)
- The !player issue is in
sceneentity.cpp. Instead of calling UTIL_GetLocalPlayer(), you should iterate through all players and get the closest player that's alive and hasn't got the NOTARGET-flag. For the NPC footsteps, take a look at Dynamic NPC Footsteps. If you got any more questions, you can find me at MSN/Google Talk. --dutchmega 09:30, 28 May 2006 (PDT)
Applying patches
The standard program for applying patches to existing files is GNU patch. Go here for the Windows version. --Koraktor
- Crap, where are the good old days with GUI's :P Thanks. But when I try to call that little program, it doesn't do anything.. no output/errors/changes.... --dutchmega 02:47, 30 May 2006 (PDT)
Combine HDR Renders
hey dutchmega. where did you get that combine costume? i want one so bad... Game4ever 13:22, 31 May 2006 (PDT)
- I am quite sure those aren't yours. You need to give credit to the author of those pictures.. --AndrewNeo 14:45, 31 May 2006 (PDT)
- That's correct. It's a HDR-render. No idea who made them actually, forgotten it. I'll look for the website today. --dutchmega 00:38, 1 Jun 2006 (PDT)
- Thought it was an idea from the Facepunch Studios Forum :). --Jurgen Knops 03:18, 8 Jun 2006 (PDT)
- Ah.. Well, at the facepunch forums it's just a link to the author :) The maker is Nick Bertke. Don't see anything about copyright or that I need to ask permission... --dutchmega 03:31, 8 Jun 2006 (PDT)
combine costume?
Hey dutchmega. Where did you get the combine costume on your front page? I want one! Answer on my talk page please Game4ever 09:58, 22 Jun 2006 (PDT)
- PLEASE! You have GOT to be kidding me?! Get serious; If YOU were born and raised in England, as you say on your own talk page, that my eleventh finger is as long as the Empire State Building?! This is the second (or even the third) time that you ask this question... I'm sorry, but this isn't a forum to post your spam, and it's sorry to say it (again), but I'll be happy to report you as a spammer, because you're driving me crazy and making the Wiki look bad >_< --CrabbyData 10:42, 22 Jun 2006 (PDT)
Ooopss..... Im really sorry. Im too goddamn curious for my own good I guess. Game4ever 02:38, 24 Jun 2006 (PDT)
- Sorry for the kind of overreaction... But if you've read some more and searched a little harder, than you've saw that it isn't a suite but a in-game-creation... --CrabbyData 04:08, 24 Jun 2006 (PDT)
- Looks real. Game4ever 14:57, 24 Jun 2006 (PDT)
Take a good look at my userpage (under the picture?) and talkpage... You are not the first talking about it... --dutchmega 05:00, 27 Jun 2006 (PDT)
Adding
- Can you add me at MSN/Gtalk/whatever? See my userpage for adresses
Don't take this the wrong way - but, uh, why? Also, I don't use IM software very much. I prefer the leisure of e-mail and forums. :) --Campaignjunkie (talk) 15:18, 29 Jul 2006 (PDT)
- Yes, I have my hands full with Black Mesa Source. --Campaignjunkie (talk) 18:45, 29 Jul 2006 (PDT)
Wrote you a message
Here: Talk:Func_tank
AI Relationship Table
Marking the AI relationship table is outdated isn't a very good excuse, as it can be easily updated, and the fact it can be easily found in code doesn't mean a mapper who wants to manipulate the AI relationships in a map should have to go into the code to find it. If we update the tables then it can be a useful resource. --AndrewNeo 12:39, 2 Oct 2006 (PDT)
|
https://developer.valvesoftware.com/w/index.php?title=User_talk:Dutchmega&diff=next&oldid=45487
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
A few years ago, I discovered
AssertionHelper, a base class provided by NUnit which allowed for a more familiar style of testing when one has to bounce back and forth between (Java|Type)Script and C#. Basically, it allows one to use the Expect keyword to start an assertion, eg:
[TestFixture] public class TestSystem: AssertionHelper { [Test] public void TestSomething() { Expect(true, Is.True); } }
And, for a while, that sufficed. But there were some aspects of this which bothered me:
- This was accomplished via inheritence, which just seems like "not the right way to do it".There have been times that I've used inheritence with test fixtures -- specifically for testing different implementations of the same interface, and also when I wrote a base class which made EF-based testing more convenient.Having to inherit from AssertionHelper means that I have had to push that inheritence further down, or lose the syntax
- The tenses are wrong:
Expectis future-tense, and
Is.Trueis present-tense. Now, I happen to like the future-tensed
Expectsyntax -- it really falls in line with writing your test first:
- I write code to set up the test
- I write code to run the system-under-test
- I expect some results
- I run the test
- It fails!
- I write the code
- I re-run the test
- It passes! (and if not, I go back to #7 and practice my sad-panda face)
- I refactor
A few months after I started using it, a bigger bother arrived: the NUnit team was deprecating
AssertionHelper because they didn't think that it was used enough in the community to warrant maintenance. A healthy discussion ensued, wherein I offered to maintain
AssertionHelper and, whilst no-one objected, the discussion seemed to be moth-balled a little (things may have changed by now). Nevertheless, my code still spewed warnings and I hate warnings. I suppressed them for a while with R# comments and
#pragma, but I couldn't deal -- I kept seeing them creep back in again with new test fixtures.
This led me to the first-pass: NUnit.StaticExpect where I'd realised that the existing
AssertionHelper syntax could be accomplished via
- A very thin wrapper around
Assert.Thatusing a static class with static methods
- C#'s
using static
This meant that the code above could become:
using static NUnit.StaticExpect.Expectations; [TestFixture] public class TestSystem { [Test] public void TestSomething() { Expect(true, Is.True); } }
Which was better in that:
- I didn't have the warning about using the Obsoleted AssertionHelper
- I didn't have to inherit from AssertionHelper
But there was still that odd future-present tense mix. So I started hacking about on NExpect
NExpect states as its primary goals that it wants to be:
- Readable
- Tests are easier to digest when they read like a story. Come to think of it, most code is. Code has two target audiences: the compiler and your co-workers (which includes you). The compiler is better at discerning meaning in a glob of logic than a human being is, which is why we try to write expressive code. It's why so many programming languages have evolved as people have sought to express their intent better. Your tests also form part of your documentation -- for that one target audience: developers.
- Expressive
- Because the intent of a test should be easy to understand. The reader can delve into the details when she cares to. Tests should express their intention. A block of assertions proving that a bunch of fields on one object match those on another may be technically correct and useful, but probably has meaning. Are we trying to prove that the object is a valid FrobNozzle? It would be nice if the test could say so.
- Extensible
- Because whilst pulling out a method like
AssertIsAFrobNozzleis a good start, I was enamoured with the Jasmine way, along the lines of:
expect(result).toBeAFrobNozzle();
Which also negated well:
expect(result).not.toBeAFrobNozzle();
In NExpect, you can write an extension method
FrobNozzle(), dangling off of
IA<T>, and write something like:
Expect(result).To.Be.A.FrobNozzle(); // or, negated Expect(result).Not.To.Be.A.FrobNozzle(); // or, negated alternative Expect(result).To.Not.Be.A.FrobNozzle();
The result is something which is quite stable, but open for further extension, and has proven quite powerful and useful, as well as trivial to extend. I suggest checking out the demo project I made showing the evolution
- from "olde" testing (Assert.AreEqual)
- through the better, new
Assert.Thatsyntax of
NUnit(which is quite expressive, but I really, really want to Expect and I want to be able to extend my assertions language, two features I can't get with
Assert.That, at least, not trivially)
- through expression via
AssertionHelper
- then
NUnit.StaticExpectand finally
- NExpect, including some examples of basic "matchers" (language borrowed from Jasmine): extension methods which make the tests read easier and are easy to create and re-use.
For the best effect, clone the project, reset back to the first commit and "play through" the commits.
NExpect has extensibility inspired by Jasmine and a syntax inspired by Chai (which is a little more "dotty" than Jasmine).
I've also had some great contributions from Cobus Smit, a co-worker at my ex-employer Chillisoft who has not only helped with extending the NExpect language, but also through trial-by-fire usage in his own project.
Note: these posts have been reformatted for dev.to from prior blogs, but I think that more people are likely to be interested here and I'd like to refer to NExpect in future posts, so I figure this journey has value
Discussion
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/fluffynuts/introducing-nexpect-555c
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
Objective
This example project demonstrates how to configure and use digital inputs on a PIC24F MCU. You will be shown how to configure a pin on the MCU, which is connected to a mechanical switch as a digital input. You will also configure another pin, connected to a Light-Emitting Diode (LED), as an output. The source code will be added to the project which reads the immediate value of the input switch and uses that value to drive the LED.
As a result of this lab:
- When the switch is pushed down, the LED will be on.
- When the switch is released, the LED will be off.
This project uses the PIC24F Curiosity Development Board. This board has two LEDs and two input switches:
- LED1: connected to pin RA9 (PORTA pin 9).
- LED2: connected to RA10.
- S1: connected to RC9.
- S2: connected to RC8.
We will first show you how to use MPLAB® Code Configurator (MCC) to generate code to configure RA9 (LED1) as an output pin, and RC9 (S1) as an input pin. You will then enter the code to drive LED1 high when S1 is pushed.
Materials
To follow along with this example, you will need the following software and hardware:
Software Tools
- MPLAB® X IDE
- MPLAB XC16 Compiler
- MPLAB Code Configurator (MCC)
Hardware Tools
- PIC24F Curiosity Development Board (Microchip part number DM240004)
- USB Micro-B cable to connect the PIC24F Development Board to your computer
Information on how to download the software tools or acquire the development board can be found on the "Resources Needed for PIC24F Labs" page.
Procedure
1
Create the Project
After installing the software, connect the PIC24F Curiosity Development Board to a USB port on your computer. Create a new standalone project in MPLAB® X for a PIC124FJ128GA204. The PIC124FJ128GA204 is the microcontroller on the PIC24F Curiosity Development Board. When the project creation wizard asks for a hardware tool (Step 2 in the New Project window), select the PIC24F Curiosity Board as displayed below.
If this is your first time creating an MPLAB X project, please visit the "Create a Standalone Project" page to follow step-by-step instructions on how to do this.
After the project has been created, the Projects tab in the upper-left corner of the IDE shows that the project has been created with no source or header files.
2
Open MCC
Open MCC under the Tools > Embedded menu of MPLAB X IDE.
MCC will place a Resource Management tab on the left-hand side of the IDE. Inside this tab, you will see a section for Project Resources and Device Resources. For each MCC-generated project, you will need to verify/modify the System Modules under the Project Resources window.
3
Set the Project Resources
There are three system elements which need attention:
- Interrupt Module: controls the MCU's interrupts.
- Pin Module: configures the I/O pins.
- System Module: selects and configures the clock source for the MCU.
Interrupt Module
This project does not use interrupts so this section will not be used.
System Module
The System Module allows the user to configure the MCU's clock, the Watchdog Timer (WDT), and make changes to the debug pin assignments. This feature of the PIC24F MCU has numerous options, which are typically modified to fit the needs of the application. MPLAB® Code Configurator (MCC) provides default settings if no changes are selected by the developer. For this lab, accept the default clock settings:
- 8 MHz Internal Free Running Oscillator with no Prescaler, but a 1:2 Postscaler (4 MHz Fosc)
- Watchdog Timer - disabled
- Unchanged debug pins
To verify the default settings, click on the System Module tab and verify the following selections have been made:
Pin Module
Click on the Pin Module in the Project Resources window. Three windows will open in the IDE:
- Pin Module Window
- Package View
- Grid View
You may need to resize the IDE window to replicate the screen layout.
The Pin Manager: Grid View window shows that pins RB1 and RB0 have been reserved as the programming pins.
We will now set the pin connected to LED1 (RA9) as an output and the pin connected to S1 (RC9) as an input. In the Grid View window, click on the output box under RA9 and the input box under RC9. The grid view will display the "padlocks" in green indicating these pins have been configured for use.
- Ensure that RA9 is set as an output pin.
- Rename RA9 as LED1.
- Ensure that RC9 is set as an input pin.
- Rename RC9 as S1.
4
Generate Code
To generate the code, click the Generate button on the MCC window.
The projects tab will show the source and header files created by MCC.
The main(void) is located within the main.c file. main(void) calls the MCC generated SYSTEM_Initialize() function before it enters the while(1) loop.
SYSTEM_Initialize() in turn calls PIN_MANAGER_Initialize() to configure the I/O pins. PIN_MANAGER_Initialize() loads the TRISA and TRISC registers with the vaues needed to set RA9 as an output pin and RC9 as an input pin.
Please consult the PIC24FJ128GA204 data sheet for the values used to configure TRISA and TRISC registers.
5
Modify the program to use the value of S1 to drive LED1
We will now main modify main.c to drive RA9 (LED1) with the value of pin RC9 (S1). An inspection of MCC generated header file pin-manager.h, shows MCC has created several control functions for the I/O pins we have configured and named. Among these macros are LED1_SetLow, LED1_SetHigh, and S1_GetValue().
Make the following modifications to main.c:
- Insert the text #include "mcc_generated_files/mcc.h" near the top of the file.
- Insert LED1_SetLow and LED2_SetHigh into main().
main.c
#include "mcc_generated_files/system.h" #include "mcc_generated_files/mcc.h" /* Main application */ int main(void) { // initialize the device SYSTEM_Initialize(); while (1) { if (S1_GetValue()) LED1_SetLow(); else LED1_SetHigh(); } return 1; }
#include "mcc_generated_files/mcc.h" is required to be placed in any application source file which accesses MCC-generated functions. This line must be placed above the application's call to an MCC function. Not all versions of MCC correctly include this code into main.c. You will also need to manually add this line to each of the application source files you create.
6
Build, Download, and Run the codeTo run the program on the development board, click on the Make and Program Device Main Project button
After the board is pogrammed neither LED1 or LED2 will be on; they are both turned off.
Results
When S1 is pushed, LED1will turn on. When S1 is released, LED1 will turn off.
Learn More
Here are some addtional examples of programming other 16-bit MCU peripherals:
|
https://microchip.wikidot.com/projects:16bit-digital-input
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
A python client library to easily consume BuddyNS.com's API
Project description
buddyns-python
A python client library to easily consume BuddyNS's API.
Installation and compatibility
Simply install the library from PyPI:
pip install buddyns
The library supports Python 2.7+ and 3+ natively.
Quick start
from BuddyNS import BuddyNSAPI # initialize the API object with your BuddyNS API token (from your BuddyBoard) bd = BuddyNSAPI(key='api_token_from_BuddyNS_account') # list domain names currently hosted on my account l = bd.list_domains() print(l) # add new domain 'testdomain1761826433.com' using '1.2.3.4' as primary address bd.add_domain('testdomain1761826433.com', '1.2.3.4') # remove a domain bd.remove_domain('testdomain1761826433.com') # get status of a domain s = bd.get_domain_status('testdomain1761826433.com') print(s)
How to get your account key
Get your API key from your BuddyNS account:
- Log into your BuddyNS account
- Reach your settings by clicking the respective button
- Reach section "Integration", and generate or copy your API key
If you do not have an account on BuddyNS already, create one at BuddyNS.
Bugs, enhancements and feedback
Pull requests, bug reports, enhancement proposals and any feedback are welcome on the project's page.
Support and further information
Do not contact BuddyNS for developer support with this library. Rely on this further documentation instead:
You can get general support on Python from the great people of the
#python channel on the freenode IRC network.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/BuddyNS/
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
Figure 1 The Visual Studio 2010 SharePoint Project Templates. If you have new columns specified in a workflow, they will automatically be added to the schema of the list that you associate with the workflow. These are known as association columns and can be used throughout the SharePoint Designer workflow. User profile data can be bound to properties in workflow, making it possible to get information about the SharePoint user profile. For example, you could look up the name of a direct manager for approvals..
item or document. This is such a common scenario that developers will create dummy lists and items in order to just to add workflows. In Visual Studio 2010, you simply pick Site Workflow when creating the workflow project item, as shown in Figure 2.
Figure 2 The Site/List Workflow Dialog Page You can get to the activated site workflows by choosing Site Workflows from the Site Actions menu in SharePoint. It shows you new workflows you can start, any running site workflows and completed workflows. Since site workflows dont have a list item or document to start from, they must be started manually through the SharePoint user interface or via the SharePoint API. dont have access to the list fields to access data since no specific list structure is connected.
Figure 3 The SharePoint Designer Workflow Showing a High Privilege Impersonation Step SPTimer Location SPTimer service. Using a new option in SharePoint Central Administration, you can now set the preferred server where the SPTimer service runs. To do this, click in the Manage Content Databases menu of the Application Management section of SharePoint Central Administration. Then click on your content database and scroll down to the setting for Preferred Server for Timer Jobs (as shown in Figure 4). You can also manually stop the SPTimer service on any servers you dont want it to run on.
Figure 5 The Event Receivers That Can Be Built in Visual Studio 2010 SharePoint 2007 made it easy to involve people in workflows, but it was difficult to send and receive messages with external systems. The recommended approach was to use task items to send a message to the external system using a Web service and have the external system update the task to return the result. SharePoint 2010 adds support for pluggable workflow services. These will be familiar to Windows Workflow Foundation (WF) developers and are defined by creating an interface containing methods and events. This interface is connected to a pair of activities called CallExternalMethod and HandleExternalEvent. A tool comes with WF in the .NET Framework called WCA.exe to generate strongly-typed activities for sending and receiving based on the interface. These generated activities can be used in SharePoint workflow also. They do not require the interface to be set as properties and instead can be dragged directly from the toolbox to the workflow design surface. The service code that integrates with SharePoint workflow is loaded into the GAC for access by the workflow. It needs to inherit from the SPWorkflowService base class and it needs to be referenced in the web.config. Using these new activities, you can send asynchronous messages to an external system right from within the SharePoint workflow. I will investigate creating and using these activities later in this article in the second walkthrough.
Creating a new SharePoint workflow project is easy. Choose sequential workflow on the new project template selector as shown previously in Figure 1. This can also be done with the state machine workflow style. The new workflow project wizard has four pages. The first is a page that all SharePoint tools project templates have in common, where you identify the URL of the local SharePoint site you want to use to deploy and debug your solution, as shown in Figure 6.
Figure 6 First Page of the New Workflow Project Wizard The second is a page where you supply the name of the workflow and choose whether to associate it with a list or as a site. This page is shown earlier in Figure 2. The third page is where you decide if Visual Studio will automatically associate the workflow for you or if you can do it manually after it has been deployed. If you choose to leave the box checked, it has selections for the list to associate with (if you previously chose a list-based workflow), the workflow history list to use and the task list to use (see Figure 7). Typically, the history and task list will not need changing.
Figure 7 Third Page of the New Workflow Project Wizard The fourth and final page is where you select how the workflow can be started (see Figure 8). You should not unselect all three of these or your workflow will be very difficult to start. For a site workflow, you can only choose manually starting the workflow. For a list-based workflow, you can also choose to start the workflow instance when a document is created or to start when a document is changed.
Figure 8 Fourth Page of the New Workflow Project Wizard The new blank workflow model looks like Figure 9 in the design surface in Visual Studio 2010. The workflow activated activity is derived from the HandleExternalEvent activity and provides initialization data from SharePoint to the workflow instance. I will cover more of the HandleExternalEvent activity later.
Figure 9 The Default Blank Workflow Showing the WorkflowActivated Activity Step 2 Add an initiation form to the workflow An initiation form can be shown to the user when they start the workflow. It allows the workflow to gather parameters before it gets started. This can be added in Visual Studio 2010 easily by right clicking on the workflow item in Solution Explorer and choosing Add then New Item, as shown inFigure 10. Select the Workflow Initiation Form template and the new form is automatically associated with the workflow. It is an ASPX form that you edit in HTML (see Figure 11).
Figure 10 Adding a Workflow Initiation Form One method called GetInitiationData needs editing in the code behind the ASPX file. This method only returns a string; if there are multiple values, it is recommended you serialize them into an XML fragment before returning them. Once the workflow instance is running, it is easy to get to this string just by referencing workflowProperties.InitiationData. The multiple values will need to be de-serialized from the XML fragment if they were serialized in GetInitiationData.
For the initiation form, a single text field will be added and then that field will be returned from the GetInitiationData method. The tags in the following code are added inside the first asp:Content tag, like so:<asp:TextBox <br />
The GetInitiationData method already exists and just needs to have code added to return the MyID.Text property. The following code shows the updated method code:private string GetInitiationData() { // TODO: Return a string that contains the initiation data that will be passed to the workflow. Typically , this is in XML format. return MyID.Text; }
Step 3 Add a workflow log activity The LogToHistoryList activity is extremely easy to use. Each workflow instance created has a history list that can display in the SharePoint user interface. The activity takes a single string parameter and adds an item to that list. It can be used for reporting the status of workflow instances to users in production. Simply drag the LogToHistoryList activity from the toolbox to the workflow design and set the description property (see Figure 12).
Figure 12 The Visual Studio Toolbox Showing SharePoint Workflow Activities Properties in workflows are called dependency properties. These are bound at runtime to another activities dependency property, such as a field, a property or a method. This process is often called wiring up and it is what allows activities to work together in a workflow even though they dont have specific type information for each other at compile time. Each property in the property window in Visual Studio is wired to a class field or class property in the workflow class. Fields are the simplest to create and the dialog that comes up when wiring up the workflow property allows for creating new fields, creating new properties or wiring to existing ones.
Figure 13 Dependency Property Binding to a Created Field Figure 13 shows adding a new field with the default name. The following shows the added code to the MethodInvoking event handler for the activity to set the property to the workflow initiation data:
You can actually set the HistoryDescription property directly in code since this property doesnt connect between activities, but it is a good simple activity in order to learn a little about dependency properties. Step 4 Add a CreateTask activity This next step is the main part of human workflow interaction known as the SharePoint task item. Create a task, assign it to a person and then wait for the person to make changes to that task. The CreateTask activity has to be dragged onto the workflow design surface and then configured with all the required properties. Figure 14 shows the CreateTask properties window just after the activity is dragged on to it.
Figure 14 The Properties Pane Showing the CreateTask Activity The first thing needed here is a correlation token for the task. A correlation token is used for message correlation in workflow. It provides a unique identifier that enables a mapping between a task object in a specific workflow instance and the workflow runtime in SharePoint. This is used so that when SharePoint receives a message for the workflow instance it can locate the correct task within the correct workflow instance. The CorrelationToken property must be configured and its not recommended to use the WorkflowToken for tasks, although this isnt prevented in the tool. Enter the new name for the correlation token as TaskToken and press enter. Then expand the (+) symbol which appears and click the drop down to the right of OwnerActivityName and choose the workflow. The TaskId must be configured and a new GUID specified for the task id. This is done by selecting the TaskId property and clicking the [] ellipsis to bring up the property editor. Click the Bind to a new member tab, choose Create Field, and then click OK. The same must be done for the TaskProperties property by again selecting the property, clicking on the ellipsis and adding a new field. Next, double click on the new CreateTask activity on the workflow design surface to bring up the createTask1_MethodInvoking handler code and set the properties in code. The new task must be given a title, and for good measure I will set the task description to the string I got from the initiation form. Once all those properties have been set, this is the added code:public Guid createTask1_TaskId1 = default(System.Guid); public SPWorkflowTaskProperties createTask1_TaskProperties1 = new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
Step 5 Add the OnTaskChanged and CompleteTask activities Use the While activity to wait for multiple changes to the task until you see the changes you want. The While activity must contain another activity, such as the OnTaskChanged activity. The Listen activity can also be used to listen for multiple events at one time by adding a Listen activity with actual event receiver activities inside the Listen branches. Alternatively, you can just wait until the task is deleted with the OnTaskDeleted activity. A common requirement is to escalate or timeout waiting for an event. This is done by using a Listen activity to listen for both the task changed message and a timer message by using a Delay activity. The first message to be received by either contained activity resumes the workflow and the other activity stops waiting. The Delay activity is sent a message when the timeout occurs. There are lots of options described above but the simplest is to use OnTaskChanged which will wait for any change to the task item and then continue on. To configure the OnTaskChanged, you need to wire up the CorrelationToken and the TaskId properties to the same fields as the CreateTask. Last, add a CompleteTask activity and again set the CorrelationToken and TaskId properties. As shown in Figure 15, the activities that wait for a message are green while activities that send a message are blue. This is consistent throughout SharePoint workflow.
Figure 15 The Completed Simple Task Workflow Model Step 6 Deploy and Test the Workflow
Now the workflow is almost complete, so press F5 and wait for the deployment. Pressing F5 will compile the workflow, package the workflow into a WSP, deploy that WSP to SharePoint, activate the SharePoint features, attach the Visual Studio 2010 debugger to SharePoint and start Internet Explorer with the SharePoint site. Once the SharePoint site appears, choose Site Workflows from the Site Actions menu. You will see all of the site workflows and you can click on yours to start it. Once it is selected, you will see your workflow initiation form, as shown in Figure 16.
Figure 16 The Workflow Initiation Form Other improvements can be added to this basic starter workflow model, such as using a content type to define the task you assign to a person, using email to notify the user they have been assigned a task, and even using InfoPath forms to create more complex forms for users to complete in email or online.
received. The correlation token is used to ensure the correct workflow instance is resumed when a response is received. As an example, consider two common examples of long-running work. One example is a synchronous Web service request where the caller is blocked until a response is received on the channel. This is not suited to run within a workflow activity. The workflow service needs to wait for the Web service call to complete and then to send a message back to the workflow instance with the response. Another example is a CPU intensive work item that needs to run but because it may take longer than a second it needs to run outside of the workflow activity. Again, you can use a workflow service and create a thread in the workflow service to execute the CPU intensive work item. The new thread can send a message back once it is finished. Both of these examples are implemented with the same pattern. The following walkthrough shows how to create a new SharePoint Sequential Workflow and call a pluggable workflow service that factors prime numbers to identify how many prime numbers there are under 100,000,000. This work takes too long to execute within the main line of an activity. Step 1 Create a Pluggable Workflow Service To create a pluggable workflow service in Visual Studio 2010, you need to implement the service as an interface and class in your project. Figure 17 shows an example of a pluggable workflow service which can be added to your project in a new class file called MyService.cs. In the code, the interface definition is in IMyService, the interface implementation in class MyService and the MessageOut method runs most of the logic through an anonymous method delegate on a separate thread. In the separate thread, the call to RaiseEvent will send the message back to the waiting HandleExternalMessage activity. Figure 17 The Pluggable Workflow Service// Interface declaration [ExternalDataExchange] public interface IMyService { event EventHandler<MyEventArgs> MessageIn; void MessageOut(string msg); }
// Arguments for event handler [Serializable] public class MyEventArgs : ExternalDataEventArgs { public MyEventArgs(Guid id) : base(id) { } public string sAnswer; }
// Class for state class FactoringState { public SPWeb web; public Guid instanceId; public FactoringState(Guid instanceId, SPWeb web) { this.instanceId = instanceId; this.web = web; } }
// Interface implementation class MyService : Microsoft.SharePoint.Workflow.SPWorkflowExternalDataExchangeService, IMyService { public event EventHandler<MyEventArgs> MessageIn; public void MessageOut(string msg) { ThreadPool.QueueUserWorkItem(delegate(object state) { FactoringState factState = state as FactoringState; DateTime start = DateTime.Now; int topNumber = 100000000; BitArray numbers = new System.Collections.BitArray(topNumber, true);
for (int i = 2; i < topNumber; i++) { if (numbers[i]) { for (int j = i * 2; j < topNumber; j += i) numbers[j] = false; } } int primes = 0; for (int i = 2; i < topNumber; i++)
{ if (numbers[i]) primes++; }
string sAnswer = "Found " + primes + " in " + Math.Round(DateTime.Now.Subtract(start).TotalSeconds, 0) + " seconds";
// Send event back through CallEventHandler RaiseEvent(factState.web, factState.instanceId, typeof(IMyService), "MessageIn", new object[] { sAnswer }); }, new FactoringState(WorkflowEnvironment.WorkflowInstanceId, this.CurrentWorkflow.ParentWeb)); }
// Plumbing that routes the event handler public override void CallEventHandler(Type eventType, string eventName, object[] eventData, SPWorkflow workflow, string identity, System.Workflow.Runtime.IPendingWork workHandler, object workItem) { var msg = new MyEventArgs(workflow.InstanceId); msg.sAnswer = eventData[0].ToString(); msg.WorkHandler = workHandler; msg.WorkItem = workItem; msg.Identity = identity; // If more than one event - you'd need to switch based on parameters this.MessageIn(null, msg); } public override void CreateSubscription(MessageEventSubscription subscription) { throw new NotImplementedException(); } public override void DeleteSubscription(Guid subscriptionId) { throw new NotImplementedEx:<WorkflowServices><WorkflowService Assembly="WorkflowProject1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=YOURPUBLICKEY" Class="WorkflowProject1.MyService"> </WorkflowService></WorkflowServices>
The assembly name and public key information can be obtained using GACUTIL.EXE /l. Step 3 Create the workflow model The rest of the work is easy. Add Call External Method and Handle External Event activities to the workflow and configure them to point to this service, as shown in Figure 18. The Call External Method activity will call MessageOut in the service and the Handle External Event activity will wait for the event MessageIn. This involves setting the InterfaceType and EventName properties in each of the two activities.
Figure 19 Completed Prime Calculating Pluggable Workflow Service Step 4 Run the workflow When this workflow is run, it will start a separate thread in the pluggable workflow service to do the prime number calculations. After 10-15 seconds of running, a workflow history item appears as shown in Figure 19. It shows that there are 5,761,455 prime numbers under 100,000,000. As shown, there is some code to write for pluggable workflow services and more code to write for each system you connect to. There are two options for reducing the amount of code required to communicate with external services. One is by interfacing with BizTalk Server and making use of the BizTalk adapter library for connecting other systems. The other is using the business connectivity services in SharePoint 2010 which provide a way to expose data from another system through external lists.
|
https://de.scribd.com/document/201343907/Collaborative-Workflow
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
Rex Tillerson’s tour of Latin America and the geopolitical dispute over resources with China and Venezuela
January 8, 2018 – Fort Russ News – Paul Antonopoulos – Translated from Mision Verdad.
CARACAS, Venezuela – The pulse against China
Of the four countries in which China has invested the most resources (Venezuela, Brazil, Ecuador and Argentina), only one is still ruled by forces that are not aligned or aligned with US geopolitical interests.
The White House has concentrated efforts to influence Latin America after its attempts to end the Bolivarian Revolution in 2017 and after the summit of the People’s Republic of China with foreign ministers of the Community of Latin American and Caribbean States (Celac) failed carried out in Santiago de Chile last January, to present the La Franja and La Ruta megaproject. This meeting was scheduled in 2015 under the commitment to carry out exchanges and programs on the basis of equality, respect and mutual benefit.
The world’s largest consumer of raw materials (China) promised to boost trade with the region, which currently exceeds 200 billion dollars. Trade between China and Latin America and the Caribbean increased by 22 times between 2000 and 2013. In 2017, goods were exchanged for a value of 266 billion dollars and the goal of 2025 is 500 billion dollars.
In the past, other countries criticized the US position when they were planted when Trump decided to abandon the trans-Pacific trade agreement known as TPP. For his part Rex Tillerson warned on Thursday to the countries of Latin America regarding an excessive dependence on their economic ties with China arguing that “Latin America does not need new imperial powers”, this before the visit to Mexico, Argentina, Peru and Colombia, countries that function as gringo branches in the region.
The dispute between the two powers over the influence in the region is clear. According to data from the Economic Commission for Latin America and the Caribbean (ECLAC), the Asian giant is the first destination market for exports from Brazil and Chile, and the second from Peru, Cuba and Costa Rica. In addition, it is the third country among the main origins of the region’s imports. He buys all the soy he can from Argentina; Chile, the largest copper producer in the world, earmarks a third of its production; and Venezuela places large amounts of oil in China. Peru also supplies copper.
It is notable that the influence of the US in the region is being displaced in a diplomatic style without bombs or coups, in this sense many governments prefer to negotiate with a power that does not act in an interventionist manner.
The Chinese Development Bank provides loans to Latin American and African countries in exchange for guaranteeing the supply of oil and gas that energize its New Silk Road. Between 2005 and 2015, China granted Latin America and the Caribbean more than 100 billion dollars in loans, the majority to Venezuela, not counting the multimillion-dollar investments in the oil and mining sectors.
Given this, the US has decided to step forward to ensure space, even when Chinese diplomatic spokesmen have said they do not seek to compete with them. Within the National Security Strategy (ESN), announced by Trump in December 2017, energy agents are protagonists in the security and the US economy, so that his government is determined to increase the pressure to liberalize the hydrocarbons market in Latin America. What is in dispute is the global hegemony and energy are vital to ensure the extraction of raw materials, sustain the production of goods, mobilize them, dominate markets and protect them.
Against the bad Venezuelan example
- Advertisement -
Brazil, Mexico, Argentina and Venezuela constitute 84% of the oil export potential of the region. The work of capturing these resources is almost done with the pressure for the energy reform and the dismantling of PEMEX in Mexico; but the role played by the US corporate elite in the Brazilian Operation Lava Jato that seeks the dismantling of Brazilian state companies, including Petrobras, to which China lent a maximum of 10 billion dollars in 2009. Both countries have been reduced to “a club of good oil boys”.
In particular, as we have pointed out, the oil transnationals have obtained solid gains from the new geopolitical configuration of the continent. ExxonMobil has preferred to invest in the exploration of the Essequibo coasts with remarkable success due to the large deposits obtained. From there arises the interest of this company (and the government in which it participates through Tillerson) in capturing the hydrocarbon reserves that extend to the mouth of the Orinoco and the Paria peninsula.
Added to this is the interest to strengthen commercial and military ties with the countries of Petrocaribe before the danger of contagion by the exchange with Venezuela, which goes beyond the energetic and also lies in the educational and cultural.
Although still important, the US has reduced its dependence on imports from Venezuela in a consistent manner, as well as increasing those from neighboring Canada. Of the three main suppliers, we are the only one with which it does not have agreements or treaties that guarantee the “free flow” of oil. While the Chinese-Venezuelan agreement by which the Chinese state company Sinopec invests 14 billion dollars to achieve daily oil production in 200 thousand barrels per day of oil in the Orinoco Oil Belt, considered the largest certified oil reserve in the world , would ruin the gringo goal of drying up China’s energy sources.
The US loses buying “fracked” oil from Canada whose Energy Return Rate is low (what is extracted in energy units is similar to what was spent), while wars (spending on arms and troops) increased oil production in Libya and Iraq.
The systematic and intense multifactorial war against Venezuela has included the selective shortage of articles of basic necessity, the amplification in the media of citizen insecurity and the narrative of “humanitarian crisis” that seeks a military intervention that stands as “savior of the country “It is a plan designed by the CIA, as recognized by its director Mike Pompeo and who has had the logistical help of the Colombian government and its economic elites.
It is a warning to the sovereign position of Venezuela, but also a warning to the electorate of other countries to which the nationalist left could return (Argentina with Cristina and Brazil with Lula) or dabble for the first time (Mexico with López Obrador), as expressed in polls and surveys.
Other resources in sight
The interests of the corporatocracy that governs the US articulate the economic with the military, ranging from the concentration of aquifer reserves in southern Argentina and the Guaraní Aquifer to the Andean and Central America.
Biodiversity is also a key factor for pharmaceutical and biotechnological interests, since the Amazon is the richest area in biodiversity in the world and is followed by Central America, territories in which the Americans have installed bases and carried out military exercises while others are controlled by paramilitary bands. In these regions, Plan Colombia and Plan Puebla-Panama have governed.
Fresh water could be the biggest geopolitical conflict of this century, it is expected that by the year 2025 the demand will increase by 56%, so that the countries possessing fresh water will become economic and military objectives. Venezuela is among the 10 countries with the largest amount of fresh water, which would be fundamental for extractive activities such as gas and oil primarily, but also in mining and agro-industry.
|
https://fort-russ.com/2018/02/rex-tillersons-tour-of-latin-america/
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.