text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
CryptImportKey (Windows CE 5.0)
This function transfers a cryptographic key from a key binary large object (BLOB) to the cryptographic service provider (CSP). This function can be used to import an Schannel session key, regular session key, public key, or public/private key pair. For all but the public key, the key or key pair is encrypted.
Parameters
- hProv
- [in] HCRYPTPROV handle to a CSP created by a call to the CryptAcquireContext function.
- pbData
- [in] Pointer to the buffer containing the key BLOB. This key BLOB was generated by the CryptExportKey function, either by this application or by another application running on a different computer.
This key BLOB consists of a standard header followed by the encrypted key.
- dwDataLen
- [in] Specifies the length, in bytes, of the key BLOB.
- hPubKey
- [in] The meaning of this parameter differs, depending on the CSP type and the type of key BLOB being imported.
If a signed key BLOB is being imported, this key is used to validate the signature of the key BLOB. In this case, this parameter contains a handle to the key exchange public key of the party that created the key BLOB.
If the key BLOB is encrypted with the key exchange key pair, for example, a SIMPLEBLOB, this parameter contains the handle to the key exchange key.
If the key BLOB is encrypted with a session key, for example, an encrypted PRIVATEKEYBLOB, this parameter contains a handle to this session key.
If the key BLOB is not encrypted, for example, a PUBLICKEYBLOB, this parameter is not used and must be set zero.
If the key BLOB is encrypted with a session key in an Schannel CSP, for example, an encrypted OPAQUEKEYBLOB, this parameter is not used and must be set to zero.
- dwFlags
- [in] Currently used only when a public/private key pair in the form of a PRIVATEKEYBLOB is imported into the CSP.
The following table shows defined flag values.
- phKey
- [out] Pointer to the HCRYPTKEY handle to the key that was imported.
#include <wincrypt.h> FILE *hSourceFile = NULL; HCRYPTPROV hProv = 0; HCRYPTKEY hKey = 0; BYTE *pbKeyBlob = NULL; DWORD dwBlobLen; // Open the file, getting the file handle 'hSourceFile'. ... // Get a handle to the default provider using CryptAcquireContext. // For sample code, see CryptAcquireContext. ... // Read the key BLOB length from the file and allocate memory. fread(&dwBlobLen, sizeof(DWORD), 1, hSourceFile); pbKeyBlob = malloc(dwBlobLen); // Read the key BLOB from the file. fread(pbKeyBlob, 1, dwBlobLen, hSourceFile); // Import the key BLOB into the CSP. if(!CryptImportKey(hProv, pbKeyBlob, dwBlobLen, 0, 0, &hKey)) { printf("Error %x during CryptImportKey!\n", GetLastError()); free(pbKeyBlob); goto done; } // Free memory. free(pbKeyBlob); // Use 'hKey' to perform cryptographic operations. ... done: // Destroy the session key. if(hKey) CryptDestroyKey(hKey); // Free the provider handle. if(hProv) CryptReleaseContext(hProv, 0);
Requirements
OS Versions: Windows CE 2.10 and later.
Header: Wincrypt.h.
Link Library: Coredll.lib.
See Also
CryptAcquireContext | CryptDestroyKey | CryptExportKey
Send Feedback on this topic to the authors | https://msdn.microsoft.com/en-us/library/ms938178.aspx | CC-MAIN-2015-35 | refinedweb | 490 | 57.47 |
.
(For more resources related to this topic, see here)
As we've heard a lot about UIKit. We've seen it at the top of our Swift files in the form of import UIKit. We've used many of the UI elements and classes it provides for us. Now, it's time to take an isolated look at the biggest and most important framework in iOS development.
Application management
Unlike most other frameworks in the iOS SDK, UIKit is deeply integrated into the way your app runs. That's because UIKit is responsible for some of the most essential functionalities of an app.
It also manages your application's window and view architecture, which we'll be talking about next. It also drives the main run loop, which basically means that it is executing your program.
The UIDevice class
In addition to these very important features, UIKit also gives you access to some other useful information about the device the app is currently running on through the UIDevice class.
Using online resources and documentation: Since this article is about exploring frameworks, it is a good time to remind you that you can (and should!) always be searching online for anything and everything. For example, if you search for UIDevice, you'll end up on Apple's developer page for the UIDevice class, where you can see even more bits of information that you can pull from it. As we progress, keep in mind that searching the name of a class or framework will usually give you quick access to the full documentation.
Here are some code examples of the information you can access:
UIDevice.currentDevice().name UIDevice.currentDevice().model UIDevice.currentDevice().orientation UIDevice.currentDevice().batteryLevel UIDevice.currentDevice().systemVersion
Some developers have a little bit of fun with this information: for example, Snapchat gives you a special filter to use for photos when your battery is fully charged.Always keep an open mind about what you can do with data you have access to!
Views
One of the most important responsibilities of UIKit is that it provides views and the view hierarchy architecture. We've talked before about what a view is within the MVC programming paradigm, but here we're referring to the UIView class that acts as the base for (almost) all of our visual content in iOS programming. While it wasn't too important to know about when just getting our feet wet, now is a good time to really dig in a bit and understand what UIViews are and how they work both on their own and together.
Let's start from the beginning: a view (UIView) defines a rectangle on your screen that is responsible for output and input, meaning drawing to the screen and receiving touch events.It can also contain other views, known as subviews, which ultimately create a view hierarchy. As a result of this hierarchy, we have to be aware of the coordinate systems involved. Now, let's talk about each of these three functions: drawing, hierarchies, and coordinate systems.
Drawing
Each UIView is responsible for drawing itself to the screen. In order to optimize drawing performance, the views will usually try to render their content once and then reuse that image content when it doesn't change. It can even move and scale content around inside of it without needing to redraw, which can be an expensive operation:
An overview of how UIView draws itself to the screen
With the system provided views, all of this is handled automatically. However, if you ever need to create your own UIView subclass that uses custom drawing, it's important to know what goes on behind the scenes. To implement custom drawing in a view, you need to implement the drawRect() function in your subclass. When something changes in your view, you need to call the setNeedsDisplay() function, which acts as a marker to let the system know that your view needs to be redrawn. During the next drawing cycle, the code in your drawRect() function will be executed to refresh the content of your view, which will then be cached for performance.
A code example of this custom drawing functionality is a bit beyond the scope of this article, but discussing this will hopefully give you a better understanding of how drawing works in addition to giving you a jumping off point should you need to do this in the future.
Hierarchies
Now, let's discuss view hierarchies. When we would use a view controller in a storyboard, we would drag UI elements onto the view controller. However, what we were actually doing is adding a subview to the base view of the view controller. And in fact, that base view was a subview of the UIWindow, which is also a UIView. So, though, we haven't really acknowledged it, we've already put view hierarchies to work many times.
The easiest way to think about what happens in a view hierarchy is that you set one view's parent coordinate system relative to another view. By default, you'd be setting a view's coordinate system to be relative to the base view, which is normally just the whole screen. But you can also set the parent coordinate system to some other view so that when you move or transform the parent view, the children views are moved and transformed along with it.
Example of how parenting works with a view hierarchy.
It's also important to note that the view hierarchy impacts the draw order of your views. All of a view's subviews will be drawn on top of the parent view, and the subviews will be drawn in the order they were added (the last subview added will be on top). To add a subview through code, you can use the addSubview() function. Here's an example:
var view1 = UIView() var view2 = UIView() view1.addSubview(view2)
The top-most views will intercept a touch first, and if it doesn't respond, it will pass it down the view hierarchy until a view does respond.
Coordinate systems
With all of this drawing and parenting, we need to take a minute to look at how the coordinate system works in UIKit for our views.The origin (0,0 point) in UIKit is the top left of the screen, and increases along X to the right, and increases on the Y downward. Each view is placed in this upper-left positioning system relative to its parent view's origin.
Be careful! Other frameworks in iOS use different coordinate systems. For example, SpriteKit uses the lower-left corner as the origin.
Each view also has its own setof positioning information. This is composed of the view's frame, bounds, and center. The frame rectangle describes the origin and the size of view relative to its parent view's coordinate system. The bounds rectangle describes the origin and the size of the view from its local coordinate system. The center is just the center point of the view relative to the parent view.
When dealing with so many different coordinate systems, it can seem like a nightmare to compare positions from different views. Luckily, the UIView class provides a simple convertPoint()function to convert points between systems.
Try running this little experiment in a playground to see how the point gets converted from one view's coordinate system to the other:
import UIKit let view1 = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) let view2 = UIView(frame: CGRect(x: 10, y: 10, width: 30, height: 30)) view1.addSubview(view2) let pointFrom1 = CGPoint(x: 20, y: 20) let pointFromView2 = view1.convertPoint(pointFrom1, toView: view2)
Hopefully, you now have a much better understanding of some of the underlying workings of the view system in UIKit.
Documents, displays, printing, and more
In this section, I'm going to do my best to introduce you to the many additional features of the UIKit framework. The idea is to give you a better understanding of what is possible with UIKit, and if anything sounds interesting to you, you can go off and explore these features on your own.
Documents
UIKit has built in support for documents, much like you'd find on a desktop operating system. Using the UIDocument class, UIKit can help you save and load documents in the background in addition to saving them to iCloud. This could be a powerful feature for any app that allows the user to create content that they expect to save and resume working on later.
Displays
On most new iOS devices, you can connect external screens via HDMI. You can take advantage of these external displays by creating a new instance of the UIWindow class, and associating it with the external display screen. You can then add subviews to that window to create a secondscreen experience for devices like a bigscreen TV. While most consumers don't ever use HDMI-connected external displays, this is a great feature to keep in mind when working on internal applications for corporate or personal use.
Printing
Using the UIPrintInteractionController, you can set up and send print jobs to AirPrint-enabled printers on the user's network. Before you print, you can also create PDFs by drawing content off screen to make printing easier.
And more!
There are many more features of UIKit that are just waiting to be explored! To be honest, UIKit seems to be pretty much a dumping ground for any general features that were just a bit too small to deserve their own framework. If you do some digging in Apple's documentation, you'll find all kinds of interesting things you can do with UIKit, such as creating custom keyboards, creating share sheets, and custom cut-copy-paste support.
Summary
In this article, we looked at the biggest and most important UIKit and learned about some of the most important system processes like the view hierarchy.
Resources for Article:
Further resources on this subject:
- Building Surveys using Xcode [article]
- Run Xcode Run [article]
- Tour of Xcode [article] | https://www.packtpub.com/books/content/understanding-uikitfundamentals | CC-MAIN-2017-17 | refinedweb | 1,681 | 58.42 |
Analytics for .NET
Our .NET library is the best way to integrate analytics into your .NET application or website. It lets you record analytics data from your ASP.NET, C#, F#, and Visual Basic code. The library issues requests that hit our servers, and then we route your data to any analytics service you enable on.
Getting Started
Client-side vs Server-side
The best analytics installation combines both client-side and server-side tracking. A client-side analytics.js installation allows you to install A/B testing, heat mapping, session recording, and ad optimization tools. A server-side .NET installation allows you to accurately track events that aren’t available client-side, such as payments. For best practices, check out our guide client-side vs. server-side.
Step 1: Add Analytics.js to your ASP.NET Master Page
Create a .NET server source in Segment.
You will then be presented with an
analytics.js snippet.
Copy the snippet directly into your ASP.NET Site.master.
That snippet will load
analytics.js onto the page asynchronously, so it won’t affect your page load speed.
As soon as that snippet is running on your site, you can start turning on any destinations on your Segment destinations page. In fact, if you reload, you can start seeing
page calls in our debugger.
For more in depth
analytics.js information, check out our analytics.js docs.
Lots of analytics and marketing tools want to know more information about your users, and what they’re doing on your app. In the next section, we’ll install the .NET library and start sending an event every time a new user registers on your site.
Step 2: Install our .NET Library
Your website will use our .NET library to
identify and
track users. You can use NuGet to install the library.
Install-Package Analytics -Version <version>
Note: the Analytics package has a dependency on Newton.JSON.
You can also accomplish the same thing in the Visual Studio
Tools menu, select
Library Package Manager and then click
Package Manager Console.
Now the .NET library needs to know which Segment project you want to send data to. You can initialize the library with your Segment source’s
writeKey in the Global.asax file. Then you can use the
Analytics singleton in any controller you want.:
<%@ Application void Application_Start(object sender, EventArgs e) { RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // this is your project's write key Segment.Analytics.Initialize("x24b2rmtvv"); } </script>
using Segment; // initialize the project #{source.owner.login}/#{source.slug}...
If you haven’t had a chance to review our spec, please take a look to understand what the identify method does.
The
identify call has the following fields:
An example call would look like:
Analytics.Client.Identify("019mr8mf4r", new Traits() { { "name", "#{ user.name }" }, { "email", "#{ user.email }" }, { "friends", 29 } });
Track
If you haven’t had a chance to review our spec, please take a look to understand what the track method does.
The
track call has the following fields:
An example call would look like:
Analytics.Client.Track("019mr8mf4r", "Item Purchased", new Properties() { { "revenue", 39.95 }, { "shipping", "2-day" } });
Page
If you haven’t had a chance to review our spec, please take a look to understand what the page method does.
The
page call has the following fields:
Example
page call:
Analytics.Client.Page("019mr8mf4r", "Login", new Properties() { { "path", "/login" }, { "title", "Initech Login" } });
Screen
If you haven’t had a chance to review our spec, please take a look to understand what the screen method does.
The
screen call has the following fields:
Example
screen call:
Analytics.Client.Screen("019mr8mf4r", "Register", new Properties() { { "type", "facebook" } });
Group
If you haven’t had a chance to review our spec, please take a look to understand what the group method does.
The
group call has the following fields:
Example
group call:
Analytics.Client.Group("userId", "groupId", new Traits() { { "name", "Initech, Inc." }, { "website", "" } });
Alias
If you haven’t had a chance to review our spec, please take a look to understand what the alias method does.
The
alias call has the following fields:@example.com"); // the identified user is identified Analytics.Client.Identify("identified@example.com", new Traits() { plan: "Free" }); // the identified user does actions ... Analytics.Client.Track("identified@example.com", "Identified Action");..
Analytics.Client.Track("sadi89e2jd", "Workout Logged", new Properties() { { "distance", "10 miles" }, { "city", "Boston" }, }, new Options() .SetTimestamp(new DateTime(2010, 1, 18)) );
Selecting Destinations
The
alias,
group,
identify,
page and
track calls can all be passed an object of
options that lets you turn certain destinations on or off. By default all destinations are enabled.
You can specify which analytics destinations you want each action to go to., in the
Options object.
Analytics.Client.Page("019mr8mf4r", "Login", new Properties() { { "path", "/login" }, { "title", "Initech Login" } }), new Options() .SetContext (new Context () { { "userAgent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}, { "ip", "12.212.12.49" }, { "language", "en-us" }, { "Google Analytics", new Dict() { { "clientId", User.ClientId } } } });
Anonymous ID
All libraries require all messages to have either a
userId or
anonymousId. If you would like to use an
anonymousId, which you should for anonymous users,.NET on a web server that’s serving hundreds of requests per second.
By default (in async mode), this library starts a single seperate thread on initialization, and flushes all messages on that thread. That means turn batching off?
Sometimes you might not want batching (for example,.NET is. Check out these gizmos:
Analytics.Initialize("YOUR_WRITE_KEY", new Config() .SetAsync(true) .SetTimeout(TimeSpan.FromSeconds(10)) .SetMaxQueueSize(10000));));
Multiple Clients
Different parts of your app may require different Segment. In that case, you can initialize different
Analytics.Client instances instead of using the singleton.
Client client = new Client("YOUR_WRITE_KEY", new Config() .SetAsync(false) .SetTimeout(TimeSpan.FromSeconds(10)) .SetMaxQueueSize(10000)); client.Track(...);.
Logging
Analytics.NET has detailed logging, which you can enable by attaching your own handler, like so:
using Segment; Logger.Handlers += LoggingHandler; static void LoggingHandler(Logger.Level level, string message, IDictionary<string, object> args) { if (args != null) { foreach (string key in args.Keys) { message += String.Format(" {0}: {1},", "" + key, "" + args[key]); } } Console.WriteLine(String.Format("[Analytics] [{0}] {1}", level, message)); }
Please note: the logger requires a minimum version of .NET Core 2.1.
Json.NET
Analytics.NET uses Json.NET to serialize json payloads. If you have an older version of
Json.NET in your build path,
Analytics.NET could create incomplete json payloads, which can cause strange API responses. If you’re seeing issues, try updating
Json.NET.
Mono
Analytics.NET has been tested and works in Mono.
Need support?
Questions? Problems? Need more info? Contact us, and we can help! | https://segment.com/docs/connections/sources/catalog/libraries/server/net/ | CC-MAIN-2020-10 | refinedweb | 1,118 | 52.66 |
Reindeer::Util - Common and utility functions for Reindeer
This document describes version 0.016 of Reindeer::Util - released September 17, 2012 as part of Reindeer.
This package provides the parts of Reindeer that are common to both Reindeer and Reindeer role. In general, this package contains functions that either return lists for Moose::Exporter or actively import other packages into the namespace of packages invoking Reindeer or Reindeer::Role (e.g. type libraries).
Trait alias definitions for our optional traits.
A list of sugar to export "as_is".
A list of Moose::Exporter based packages that we should also invoke (through Moose::Exporter, that is).
Import our list of type libraries into a given package.
Returns a list of type libraries currently exported by Reindeer. | http://search.cpan.org/~rsrchboy/Reindeer-0.016/lib/Reindeer/Util.pm | CC-MAIN-2016-36 | refinedweb | 124 | 58.38 |
Using Tellurium
The combination of libraries in Tellurium allow you to write python scripts that define, simulate, and analyze models. Models are defined using the Antimony syntax, which are loaded for simulation and analysis in libRoadRunner. The roadrunner tutorial is an excellent reference for available functionality.
Tellurium Tutorials YouTube Channel
We have created a Youtube channel called TelluriumTutorials which provide demonstrations of how to use Tellurium.
The following are sample Python scripts that perform such analyses. Additional examples are provided with your installed application. Check the folder Tellurium is installed at or go to Tellurium github.
Simple UniUni reaction that uses first-order mass-action kinetics
import tellurium as te # Simple UniUni reaction with first-order mass-action kinetics r = te.loada (''' S1 -> S2; k1*S1 # Initialize values S1 = 10; S2 = 0 k1 = 1 ''') # Carry out a time course simulation results returned in array result. # Arguments are: time start, time end, number of points result = r.simulate (0, 10, 100) # Plot the results r.plot (result)
Consecutive UniUni reactions using first-order mass-action kinetics
import tellurium as te # Consecutive UniUni reactions using first-order mass-action kinetics r = te.loada (''' S1 -> S2; k1*S1 S2 -> S3; k2*S2 S3 -> S4; k3*S3 # Initialize values S1 = 5; S2 = 0; S3 = 0; S4 = 0; k1 = 0.1; k2 = 0.55; k3 = 0.76 ''') result = r.simulate (0, 20, 50) r.plot (result)
Setting boundary species in a model
import tellurium as te # Setting boundary species in a model r = te.loada (''' # The $ character is used to indicate that a particular species is FIXED $S1 -> S2; k1*S1 S2 -> S3; k2*S2 - k3*S3 S3 -> $S4; Vm*S3/(Km + S3) # Initialize values S1 = 1.0; S2 = 0; S3 = 0; S4 = 0.0 k1 = 0.2; k2 = 0.67; k3 = 0.04 Vm = 5.6; Km = 0.5 ''') result = r.simulate (0, 10, 200) r.plot (result)
Single gene expressing protein and protein undergoing degradation
import tellurium as te # Single gene expressing protein and protein undergoing degradation r = te.loada (''' # Reactions: J1: -> P; Vm*T^4/(K+T^4) J2: P -> ; k1*P; # Species initializations: P = 0; T = 5; Vm = 10 K = 0.5; k1 = 4.5; ''') result = r.simulate(0, 2, 50) r.plot (result)
Example of Non-unit Stoichiometries
# Example of Non-unit Stoichiometries r = te.loada (''' S1 + S2 -> 2 S3; k1*S1*S2 3 S3 -> 4 S4 + 6 S5; k2*S3^3 ''')
Computing the Steady State
import tellurium as te r = te.loada (''' $Xo -> S1; k1*Xo - k2*S1 S1 -> S2; k3*S2 S2 -> $X1; k4*S2 Xo = 1; X1 = 0 S1 = 0; S2 = 0 k1 = 0.1; k2 = 0.56 k3 = 1.2; k4 = 0.9 ''') # Compute the steady state r.getSteadyStateValues() print "S1 =", r.model.S1, "S2 =", r.model.S2
How can I create different wave forms?
import tellurium as te # Generating different waveforms r = te.loada (''' model waveforms() # All waves have the following amplitude and period amplitude = 1 period = 10 # These events set the 'UpDown' variable to 1 or 0 according to the period. UpDown=0 at sin(2*pi*time/period) > 0, t0=false: UpDown = 1 at sin(2*pi*time/period) <= 0, t0=false: UpDown = 0 # Simple Sine wave with y displaced by 3 SineWave := amplitude/2*sin(2*pi*time/period) + 3 # Square wave with y displaced by 1.5 SquareWave := amplitude*UpDown + 1.5 # Triangle waveform with given period and y displaced by 1 TriangleWave = 1 TriangleWave' = amplitude*2*(UpDown - 0.5)/period # Saw tooth wave form with given period SawTooth = amplitude/2 SawTooth' = amplitude/period at UpDown==0: SawTooth = 0 # Simple ramp Ramp := 0.03*time end ''') r.selections = ['time', 'SineWave', 'SquareWave', 'SawTooth', 'TriangleWave', 'Ramp'] result = r.simulate (0, 90, 500) r.plot (result)
You can also load SBML models directly from BioModelsDB
r = te.loadSBMLModel("") result = r.simulate(0, 3000, 5000) r.plot (result)
| http://tellurium.analogmachine.org/documentation/tellurium-tutorial/ | CC-MAIN-2017-22 | refinedweb | 643 | 52.97 |
Read the detailed guide to the user interface
Learn how to access GenomeSpace functionality for each Tool
See answers to frequently asked questions
Access talks by the GenomeSpace community
Provides description for end-to-end analyses.
Posted by Ted Liefeld on Monday, December 16, 2013 at 11:58AM
Last updated on Wednesday, December 18, 2013 at 01:23PM
As the number of tools available in GenomeSpace grows it has become clear that having a single toolbar on the GenomeSpace User Interface (GSUI) is no longer sufficient. So, to make it easier to deal with the ever-increasing collection of GenomeSpace tools, we have added a few new features to the GSUI; including multiple toolbars, and a new tool catalog to help you arrange and manage your tools and toolbars.
The new toolbar looks like this:
Some of the changes to note include:
To reorder the tools in a toolbar, simply drag and drop them within the toolbar. Also, as with the old toolbar, you can make the icons smaller by grabbing the bottom edge of the toolbar and dragging upwards as described in the previous Toolbar Enhancements blog post. The new scrollbar buttons also work on touchscreens for those of you accessing GenomeSpace from a tablet or smartphone.
To open the tool catalog, click on the button.
In the catalog itself (on the left in the image above) you will see all the tools available to you in GenomeSpace. This includes those made available by the GenomeSpace team, as well as any private tools that other users have shared with you. If a tool is on your currently selected toolbar, it will display a checkmark at the top right corner.
On the right under Select Toolbar in the image above, is the list of toolbars you have created. Everyone will start with one called 'Default', but you can rename it, by clicking on the toolbar name, and create others. You can also change the color assigned to a toolbar's button using the color picker beside the name. Finally you can delete a toolbar by clicking the red 'x' next to it; though you must always have at least one toolbar. You can change the current toolbar by clicking on the row with its name or by clicking its matching button (i.e. the colored dots).
You can sort the tools using the 'Order by' control above the catalog. Tools can be sorted by:
You can also search for tools using the search box provided. This will search through tool names, descriptions, and tags, and display only those that match in the catalog.
To see the description of a tool you may be interested in, or to add/remove it from the current toolbar, simply mouse over the tool card in the catalog.
Clicking on the Add or Remove buttons will (suprisingly) add or remove this tool from your currently selected toolbar. You can see more information about the tool by clicking on the 'more details...' link. For example, for InSilicoDB you would see the following:
This shows you the tool's name, author, date added to GenomeSpace, the URL to access the tool directly, and also any tags that have been added to the tool in GenomeSpace. In the example above you see a tag called 'junit_tag_1376940073705' that was added by our automated build and test system. In the released version of GenomeSpace the tags typically reflect capabilities the tool has.
In some cases, a tool may have a special note attached to it. In these cases you will see an additional link called 'Special Requirements' that looks like this
Clicking on this link will bring up details you may need to know before using this tool.
Posted by Jon Bistline on Wednesday, November 20, 2013 at 05:30PM
Last updated on Friday, December 06, 2013 at 10:30AM
For those of you that are Ruby on Rails developers, you're most likely already familiar with Devise. It's a fantastically simple and flexible way to add password- and token-based authentication to your Rails application. What you may not know is that there is a companion gem called 'devise_openid_authenticatable' that extends Devise's authentication strategies to include OpenID. This post will show you how you can implement this to authenticate your application against the GenomeSpace OpenID server.
For this example, we're using Rails 3.2.12 and Ruby 1.9.2. You can use newer versions of Ruby, but I don't recommend using Rails 4 for this - there are issues with OpenID and the CSRF authenticity token in Rails that causes authentication to fail unless you completely disable it, which is less than ideal if this application is going to be public.
Once you've created your application, you'll need to add these 3 gems to your Gemfile:
gem 'devise'
gem 'devise_openid_authenticatable'
gem 'warden'
After that, create a User model in the standard fashion (see the Devise documentation for more information). If this is a new application you've created, you also need to set up a simple controller with an index method to give Devise somewhere to redirect to once we've authenticated. Here's a quick example:
From the command line:
rails g controller home index
Add this line to app/controllers/home_controller.rb
before_filter :authenticate_user!
Finally, edit your config/routes.rb:
devise_for :users
get "home/index"
root to: "home#index"
It would also be a good idea at this point to read our OpenID Requirements documentation as well so that you're familiar with the concepts before moving forward.
Once you've created your user model, you're going to want to edit it so that it only tries to authenticate against OpenID. To do this:
1. Migration to add necessary fields:
class AddOpenIDFieldsToUsers < ActiveRecord::Migration
def up
add_column :users, :identity_url, :string
add_column :users, :username, :string
add_column :users, :token, :string
remove_column :users, :encrypted_password
end
def down
remove_column :users, :identity_url
remove_column :users, :username
remove_column :users, :token
add_column :users, :encrypted_password, :string
end
end
2, 3. Edits to app/models/user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :database_authenticatable, :confirmable, :lockable, :timeoutable, :omniauthable,
# :registerable, :recoverable, :rememberable, :trackable, :validatable
devise :openid_authenticatable, :trackable
# Setup accessible (or protected) attributes for your model
attr_accessible :identity_url, :email, :username, :token
The next thing that you'll need to do is set up the proper GenomeSpace OpenID parameters inside you User model. This is done via a custom extension (option #3 from our OpenID Requirements documentation). To set this up, you need to do 2 things:
1. app/views/devise/sessions/new.html.erb:
<%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>
<%= f.hidden_field :identity_url, value: "" %>
<%= f.submit "Sign in using GenomeSpace" %>
<% end %>
In our login form (above), you can see that we've removed the standard username/password fields and instead added a hidden field that points directly at GenomeSpace's OpenID URL. This way, when the user clicks the "Login with GenomeSpace" button, they are redirected to our GenomeSpace login page, which will then return back to your Rails application once the login is successfully completed.
2. Implement required OpenID User methods (inside app/models/user.rb):
def self.openid_required_fields
["gender", "nickname", "email"]
end
def self.build_from_identity_url(identity_url)
User.new(:identity_url => identity_url)
end
def openid_fields=(fields)
fields.each do |key, value|
# Some AX providers can return multiple values per key
if value.is_a? Array
value = value.first
end
case key.to_s
when "nickname"
self.username = value
when "email"
self.email = value
when "gender"
self.token = value
else
logger.error "Unknown OpenID field: #{key}"
end
end
end
These 3 methods will provide the necessary functionality so the devise_openid_authenticatable can map the fields from GenomeSpace's OpenID server to the instance of the User model you're working with. Here's a brief overview of what each method is doing:
i. self.openid_required_fields
This is an array of required fields for any successful authentication response. We're providing the SReg names for fields here even though we're using the custom extension as this is what is returned from GenomeSpace (more on this later). Specifically, we're saying that GenomeSpace must provide the gender and nickname fields in it's response. We'll map these fields to our User model later.
ii. self.build_from_identity_url(identity_url)
This method automatically creates your User record once we've successfully logged in and records it in the database. The :identity_url is your GenomeSpace OpenID unique identifier, and takes the following format:[YOUR GENOMESPACE USERNAME]. We need this method so that we can record our other OpenID fields somewhere later on.
iii. openid_fields=(fields)
This is where the real heavy lifting happens. In this instance method (as opposed to the above class methods), once we have a valid User instance, we can then take the response from OpenID and parse out the various fields that we said we needed. It takes a hash from devise_openid_authenticatable (fields) and maps each field to what we want. Specifically, it takes the SReg names for the values we requested and maps them inside the case statement to the User columns we created earlier.
You might think you're done at this point, but there is one last thing we need to do. Even though we're using the custom extension, devise_openid_authenticatable can only send the request as either SimpleRegistration (SReg) or AttributeExchange (AX). This was why we specified the SReg names for the parameters in our required fields rather than the custom GenomeSpace fields. We need this because otherwise the fields aren't "signed" when they're returned, and devise_openid_authenticatable won't parse any unsigned fields. So we need to tell devise_openid_authenticatable how to handle this custom case. It requires a one-line fix to the source code for the gem. To do this:
Once you've vendored all of your gems (it is possible to only vendor the devise_openid_authenticatable gem, but I don't recommend it - it's much simpler to vendor them all), find the strategy.rb file inside the lib/devise_openid_authenticatable folder of the gem. Navigate down to the fields method (it should be around line 100) and look for the following line:
if ns_alias.to_s == "sreg"
And change the line to read like so:
if ns_alias.to_s == "sreg" || ns_alias.to_s == "ext1"
The reason we're doing this again is because of the response that comes back from GenomeSpace. If you refer back to the GenomeSpace OpenID Requirements documentation, you'll notice that using the custom extension sets the namespace to "ext1" instead of "sreg". Since the fields method parses the values returned by from OpenID by namespace, if we don't tell it how to handle this special namespace your username, email and token values won't get recorded.
That's it - you've now got a simple Rails application that can authenticate against GenomeSpace's OpenID server.
Posted by Ted Liefeld on Monday, November 04, 2013 at 10:17AM
Last updated on Tuesday, November 05, 2013 at 07:21AM
It has long been possible to customize your GenomeSpace toolbar by adding, reordering or hiding tools. This has now gotten a little easier with the changes that we've just released.
You have always been able to reorder tools in your toolbar from the View>>Customize Toolbar menu but you can now also accomplish this just by dragging and dropping the tools within the toolbar itself. Simply click and hold on a tool's icon and drag it to the left or right to change its place in the toolbar order.
As with the reordering, you could previously do this from the View>>CustomizeToolbar menu, but you can now also hide a tool by clicking on the tool's dropdown menu and then selecting the 'Hide' option. If it is a private tool that you have permission to edit, you will also see an 'Edit' menu item here to allow you to change the tools properties.
If you have hidden a tool or want to find out what else is available and not showing on your toolbar, use the View>>CustomizeToolbar menu item. This will bring up the toolbar dialog which will show you the currently hidden tools in the panel on the right. You can also use this dialog to reorder or hide tools by dragging and dropping them within or between the shown/hidden tool lists.
Finally, you can now also resize the toolbar to give your files more space in the browser window. To do this simply click on the handle along the bottom edge of the toolbar slider and drag it upwards. Once the icons get smaller than about 50% it will also hide the tool names to leave even more space for your files.
Posted by Ted Liefeld on Monday, September 30, 2013 at 09:36AM
The Cancer Cell Line Encyclopedia portal (CCLE) can now export data directly to GenomeSpace to facilitate its analysis in any of the GenomeSpace tools.
The Cancer Cell Line Encyclopedia provides public access to genomic data, analysis and visualization for about 1000 cell lines.
Since the CCLE is using the GenomeSpace lightweight data integration library, you will still need a separate account on the CCLE in order to access the data it contains.
Sending data from the CCLE to GenomeSpace starts by going to the Browse > Data menu from any page.
Once on the data page, a GenomeSpace icon has been added beside each file name.
Clicking on this icon will launch the GenomeSpace import dialog window. From there you can login to GenomeSpace if necessary (or register for GenomeSpace), select the directory you want to save the file to, and optionally rename the file.
Once you hit the submit button, the file will be automatically copied from the Cancer Cell Line Encyclopedia portal into your GenomeSpace directory. From here you can then analyze the data using the usual GenomeSpace mechanisms.
Posted by Ted Liefeld on Thursday, September 05, 2013 at 10:09AM
Last updated on Tuesday, September 24, 2013 at 10:19AM
The Multiple Myeloma Genomics Portal (MMGP) can now export data directly to GenomeSpace to facilitate its analysis in any of the GenomeSpace tools.
The Multiple Myeloma Genomics Portal (MMGP) provides access to significant multiple myeloma datasets. These include the Multiple Myeloma Reseach Foundation-funded reference aCGH, mutation and gene expression data as well as 8 other additional public multiple myeloma datasets.
Since the MMGP is using the GenomeSpace lightweight data integration library, you will still need a separate account on the MMGP in order to access the data it contains.
Sending data from the MMGP to GenomeSpace starts by going to the Browse > Data menu from any page.
Once you hit the submit button, the file will be automatically copied from the Multiple Myeloma Genomics portal into your GenomeSpace directory. From here you can then analyze the data using the usual GenomeSpace mechanisms.
Posted by Ted Liefeld on Thursday, August 29, 2013 at 11:45AM
Last updated on Wednesday, September 04, 2013 at 09:40AM
For those of you frequently working with data in the gct matrix format, or a format that can be converted to gct (currently gxp and Genomica tab formatted files) it is now possible to visualize your files as heatmaps directly within the GenomeSpace user interface.
To start, select the file preview for a file.
This will open the standard preview dialog. If it is possible to visualize this file as a heatmap. you will se a 'Heatmap' tab beside the 'Preview' tab.
Clicking on this tab will display your data as a heatmap.
Some notes:
Posted by Ted Liefeld on Wednesday, August 28, 2013 at 11:39AM
Last updated on Friday, August 30, 2013 at 11:11AM
When GenomeSpace was first released, to share a file (or a private tool) you needed to know your collaborator's username which often involved emailing them to ask them what it was. GenomeSpace now supports looking up other GenomeSpace users by their email address or by partial username matching. So if you have your collaborator's email address, you can now look up their username when you are
When you click on the username text field in the dialog boxes for any of the above, you will now see the 'find user' dialog appear. Simply enter either an email address or a partial username and the GenomeSpace User Interface will find your collaborator's username for you and fill it in in the form.
For those of you who would prefer not to let other GenomeSpace users find you via your email address (or partial username matching) you can opt-out of being in the search results from your GenomeSpace profile dialog. Other users will then have to know your exact username in order to share tools or files with you.
Posted by Ted Liefeld on Tuesday, August 06, 2013 at 12:47PM
Last updated on Friday, August 09, 2013 at 08:34AM
The GenomeSpace team has updated the servers and GSUI to allow you to now share your 'private' tools to multiple user groups at the same time. Click here to see the original post about adding private tools to your GenomeSpace toolbar.
The only change is at the bottom of the dialog where the list of groups the tool is hared to is located. The new interface looks like this with the changed region highlighted by a red box;
In this example, the tool is shared with the two groups 'GS-Developers' and 'Test1'. To add a group, select its name from the '---Select a Group---' dropdown and click the 'add' button. To remove a group from the list simply click the red 'x' beside its name. For either adding or removing you must also then 'Save' your changes with the 'Save' button.
Hopefully this will make it easier than ever to share your tools with your coworkers.
Posted by Ted Liefeld on Wednesday, July 31, 2013 at 11:19AM
Last updated on Tuesday, August 06, 2013 at 10:19AM
We are pleased to announce that we have added the ability to 'tag' your files to GenomeSpace. With this feature you can add any number of tags to your GenomeSpace files to provide another way to organize them or to make it easy to find all of the files belonging to a particular project.
To add a tag to a file, simply right click on a file and select 'tags' from the context menu. To add tags to many files at once, check the files in the file browser and then select Tags from the File menu. This will open up the file tagging dialog.
Start typing the text for your tag in the field provided.
When you hit the 'Enter' key, the tags will be created and added to the file(s). To add multiple tags at one time, simply put a comma "," at the end of each tag.
Once you close the dialog, the tags will be displayed in your file view like this.
To remove a tag, open the file tagging dialog as before on one or more files, and click the red 'x' next to the tag name. The tag will then be deleted from the selected files.
Along with the file tags, we have also added a file search capability to GenomeSpace. To use it simply type the search term you want in the search box at the top right corner of the GenomeSpace User Interface Window.
Search automatically searchs for files based on the tags and the file name. Search results are seperated between files and tools and are displayed in place of the usual directory view. To return to the directory view click on the 'Return to file list' link.
Search is always case insensitive and automatically adds wildcards to the front and end of the term you typed. So if you search for for 'FOO' you would get any files with FOO, foo, FoO etc anywhere in the filename or in a tag. You can constrain the search to filenames and tags starting or ending with a particular string by adding a percent sign '%' at the start or end of the search string. e.g. use '%.bai' to seach for files with the '.bai' extension or 'SFPK%' to search only for files starting with the String 'SFKP'. Unfortunately, you cannot at the moment use the '%' wildcard in the middle of the search string.
Files in search results will display their path if you hover the mouse over them. You can also go directly to the containing folders from the file context menus.
Please let us know if you have any suggestions for how to make this more useful for you and your team.
Posted by Ted Liefeld on Wednesday, June 19, 2013 at 09:55AM
Last updated on Monday, November 02, 2015 at 11:06. | http://genomespace.org/blog?page=3 | CC-MAIN-2017-43 | refinedweb | 3,470 | 59.43 |
using .
Posted
Monday, February 04, 2008 6:25 AM
by
OrenEllenbogen
Alright alright, so I didn't post anything for... a decade or so. but I'm here (at the office that is) all day long, being a part of a great Team, building the greatest\coolest piece of software I've ever dream of.I promised myself that I'll be short this time so here it goes, Oren's 60 seconds update:
Posted
Friday, January 25, 2008 12:46 PM
by
OrenEllenbogen
Imagine!
Posted
Sunday, November 18, 2007 12:54 AM
by
OrenEllenbogen
Well.
Posted
Thursday, November 15, 2007 12:34 PM
by
OrenEllenbogen
What is more important to you - having the brightest dude in the world in your team, doing his magic with God-like authority or real "together-will-conquer-the-world" Team work? Tricky question...
For those of you who don't know the TV series "House", this is your wake up call! Go see it. Now. Seriously.Well, if you don't have the time or you're just too damn eager to read my post, we'll, "you're an idiot!", but that's your right so I'll give you a short summary: Dr. House, played by the genius actor Hugh Laurie, is the go-to-guy for all the rare cases where the rest of the doctors go bananas. With his extremely cynical point of view and shameless wittiness, combined with a very bright, analytic and (yet) creative thinking, he manage to solve all (we'll, almost) of these cases and still being a complete jerk to his "teammates" during the show. Just a few pearls from Wikiquote so you'll get the drift:
Dr. Cuddy: You don't prescribe medicine based on guesses. At least we don't since Tuskeegee and Mengele. Dr. House: You're comparing me to a Nazi? [admiringly] Nice ...
If you ask me, I would pick House any day. Now, if any of you know such a man, let him know that we're at Semingo are hiring; Till then, I guess that I would stick to a strong Team and real commitment instead of software-Nazi.
I'm lying. I don't think that following someone blindly is for me. I don't believe in this kind of leadership. I grew up at the court, playing Basketball since I was ~9, there is nothing I love more than genuine Team spirit. Facing the fact that "white man can't jump" quite early in my life, I realized that Michael Jordan can be rest assured, I'm not going to steal his glory. Knowing that and still being the competitive guy that I am, there is no other choice but to build a strong Team and having fun together. It worked for me so far.
Shame though, It would have been funny working with someone like House; If only life were a TV show...
Posted
Saturday, October 20, 2007 5:16 AM
by
OrenEllenbogen
Moti and I have decided to form an invite-only Scrum Clan.We would like to tag Pasha Bitz (snapshot below) as the 3rd clan member.
Pasha, choose carefully, you can only tag one Scrum-Lover like yourself to this distinguish clan ;)
p.s - If you want to be part of the Scrum Clan, please drop a comment and you *might* get an invitation...
Scrum Rules !
Posted
Wednesday, October 10, 2007 12:47 AM
by
OrenEllenbogen
Let
A few pearls from the office:
Posted
Thursday, July 26, 2007 7:32 PM
by
OrenEllenbogen
| with no comments
After almost 1.5 months of Scrum at Semingo (a baby startup), I decided to expose the way we work at the moment and talk about the adjustments we've made in order to suit Scrum to our needs.
I'll start with our implementation to the Daily Stand-up Meeting. No doubt, our meetings are pretty funny (most of the time) and create the right vibe for the Team. The one thing I love most about our meetings is that by the end of the meeting, I know what is the general work-plan for each member in my Team. Now it's easy to know what I'm planning to complete today (I spend 5-10 minutes planning my day before the meeting), when & if I need to finish something earlier (or at least decide about interfaces after the meeting) in order to integrate with others, help out or ask for someone's else help(code review for example), stay after the meeting in order to talk about something that pop up during the meeting, remove impediments (if I can) and most importantly - have a good laugh before the day begins.
Daily Stand-up Meeting (aka DSM) structure at Semingo:
When: Every day at 10:30. Where:Meetings room.Time Box:15 minutes.Attendants: Pigs only (Chickens can (only) listen)On the table: Each Pig answer these 4(!) questions:(1) What have I done since the last DSM ?(2) What am I planning to do until the next DSM ?(3) Impediments - what bothers me to work ?(4) Am I on track? If someone feels that one of his tasks won't be finished as planned, a flag is raised so the Team could assist. The same goes if someone feels that he's going to finish before the expected time. This means that he could help out someone else or take a few extra tasks we did not plan for the current iteration.Notes:Only one Pig talks at a time and he leads the conversation if reasonable questions comes up. He (alone) has the power to stop a conversation if he feels the conversation stray from the DSM path. Team members can decide to talk about an issue that was raised during the DSM just after the meeting is finished.
What next (DSM planned improvements)?(1) You late, you get (punished, that is): each team member that late to the DSM must wear the "I was late to DSM, I will serve you coffee today" sign on his shirt.(2) Red-Back on track: If the conversation is getting out of control (too many jokes, drill-down conversations, more than 1 Pig talk etc) - the red button is clicked and each Team member is being electrified with 120V. Well no, but it could have been a nice feature right? Clicking the red button will make a nice GONG!! so we could move on. The Team agree to listen to the GONG and get back on track, so we could finish in time and keeping the DSM productive.
Posted
Saturday, July 14, 2007 5:51 PM
by
OrenEllenbogen
| with no comments
Gosh, I did not know Raymond Lewallen was reading my blog (I guess I should start writing some meaningful stuff and stop playing around ;)) but I'm more than happy to raise up to the challenge and talk about what I am doing in order to go to the next level.
In one of my post, What it takes to become a great developer, I mentioned the notion of "Be Eager To Learn". I don't consider myself as a good developer due to my natural skills (I don't think that I'm mediocre, but certainly not Larry Page). Starting 8 years ago as a little teenager at 15, I had to work my ass off in order to keep up and show the rest of the people I was working with that I'm just as good as they are. Reaching this goal, I wanted to show myself that I can be the best guy at the company.
Eight years passed and a lot have changed, but I'm still very much eager to get better and more versatile. One thing I'll always keep with me, as it proved it self so far, is the no-fear attitude and the (sometimes) ridiculous optimism. I'm not afraid of doing new things or changing positions when an "offer you can't refuse" knocks on my door. Life is short and you most grow each and every day. I'm still the same team player guy, although I can get over confident (aka arrogant) or raise my voice here and there. I care about my teammates and know when to say "I'm sorry". I work with my heart and hopefully my current and future teammates will forgive me for my faults.
I think that in the last few years I've learned a lot about myself, about the things that really intrigued me, that push me to excel. I love coding, I love talking with people, mentoring, lecturing about technologies or Agile methodologies, but most of all - I enjoy taking ownership of projects I participate in and making them successful. I'm looking to surround myself with people smarter than me, those that have natural gifts in them, and making them better.
Things I should do
I should try to get more organized in planning my time. I read a lot of books about self management but I don't feel like I'm practicing them as much as I should. I should really invest more time in myself, trying to set goals and constantly reviewing them. I'm leading the Agile a la Scrum at Semingo so I hope to use this work & review notion more in my life.
I should learn more about Agile, Scrum and XP. I've read a few great books about Agile\Scrum\Management but I still have a lot of unanswered questions. I know that these methodologies only offer some solutions but I don't believe we should enforce them. I believe in making our own Agile process at Semingo. That said, I do want to read more books from people with different experience, different ideas and best practices I could learn from.
I should definitely write more posts! (particularly about Agile\Scrum)
Things I want to do
TDD: getting better in it and start lecturing about it more.Multi-threading: This one is a new set of skills I'm developing at my current job. Looking at the near future, this skill is crucial as a developer.WCF: I need to use it in my current job and I have a lot of catch up to do.Lecturing: At least 4-5 lectures a year looks like a solid goal at the moment.Most of all, I want to make Semingo the best place to work at, to bring more amazing guys&gals to work with us and making an application that will change the way millions of people work.Things I won't do
I think that it's getting clear to me that I do not want to be an external coach. I don't see myself coaching a team for a 2-3 months and then shifting to another team. I enjoy working with people and I take pride and strength in making things complete.
I won't stop talking and writing about software, practices and people as long as I have keyboard and working set of 1-N fingers available. Count on it!
Tagging these folks
Pasha Bitz, Shani Raba, Doron Yaacoby, Eran Nachum, Ken Egozi
Posted
Friday, July 13, 2007 8:52 PM
by
OrenEllenbogen
| with no comments
One of the downsides of using lock is obviously performance. While locking an object, any other thread trying to acquire the lock on that object will wait in line. This can open up a deep hole to performance hit. Rule of thumb while working with locks is to acquire it as late as possible and release it as soon as possible. To demonstrate the order of magnitude bad usage of locks can affect your performance, I decided to write a little demo. So let's assume we have a component that is responsible for executing tasks while getting new ones in the process (on different threads). I tried to make this example as simple as possible. Let's start with our "task" class:
public class Task{ private int _id; private string _name; public Task(int id, string name) { _id = id; _name = name; } public int Id { // getter, setter } public string Name { // getter, setter }}
We have a TasksRunner that's responsible for getting new tasks and saving it to internal list and executing the current tasks every X milliseconds (via timer). In order to simulate a real-life process, I've made sure that executing a single task is expensive. Let's start with the non-optimized solution:
public class TasksRunner{ private List<Task> _tasks; private System.Timers.Timer _handleTasksTimer; public TasksRunner() { _tasks = new List<Task>(); _handleTasksTimer = new Timer(200); _handleTasksTimer.Elapsed += new System.Timers.ElapsedEventHandler(_handleTasksTimer_Elapsed); _handleTasksTimer.Start(); }
public void AddTask(Task t) { lock (_tasks) { _tasks.Add(t); Console.WriteLine("Task added, id: " + t.Id + ", name: " + t.Name); } } //Execute the (delta) tasks in a thread from the ThreadPool private void _handleTasksTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { ExecuteCurrentTasks(); } public void ExecuteCurrentTasks() { lock (_tasks) { foreach (Task t in _tasks) ExecuteSingleTask(t); _tasks.Clear(); } } private void ExecuteSingleTask(Task t) { Console.WriteLine("Handling task, id: " + t.Id + ", name: " + t.Name); Thread.Sleep(1000); //simulate long run }}
AddTask will acquire the lock on _tasks and add the new task to the list while ExecuteCurrentTasks will acquire the lock (on _tasks) and simulate real execution on the task. Notice that during the execution, calling AddTask will wait until the current execution will be finished. Using Roy's ThreadTester, we can run the following in order to notice the behavior so far:
static void Main(string[] args){ TasksRunner runner = new TasksRunner(); ThreadTester threadTester = new ThreadTester(); threadTester.RunBehavior = ThreadRunBehavior.RunUntilAllThreadsFinish; Stopwatch watch = new Stopwatch(); watch.Start(); int numberOfTasksToCreate = 100; threadTester.AddThreadAction(delegate { for (int j = 0; j < numberOfTasksToCreate; j++) { runner.AddTask(new Task(j, "job " + j)); Thread.Sleep(100); } }); threadTester.StartAllThreads(int.MaxValue); //wait, no matter how long Console.WriteLine("Total time so far (milliseconds): " + watch.ElapsedMilliseconds); Console.WriteLine("Tasks added so far: " + runner.TasksAdded); Console.WriteLine("Tasks executed so far: " + runner.TasksExecuted); Console.WriteLine("Waiting for tasks to end..."); while (runner.TasksExecuted < numberOfTasksToCreate) Thread.Sleep(1000); runner.Shutdown(); Console.WriteLine("done!"); Console.WriteLine("Total time so far (milliseconds): " + watch.ElapsedMilliseconds); Console.WriteLine("Tasks added so far: " + runner.TasksAdded); Console.WriteLine("Tasks executed so far: " + runner.TasksExecuted);}
Running this test will give us a very poor result for adding & executing 100 tasks takes around ~99 seconds.
No doubt, the lock on _tasks while executing each and every task in the list is too expensive as we're depend on ExecuteSingleTask (which is expensive by itself). This way, each new task we're trying to add must wait until the current execution is finished. An elegant solution to this problem, suggested by my teammate Tomer Gabel, is to use a temporal object to point to the current tasks thus freeing the lock much quicker. So here is an optimized version of ExecuteCurrentTasks:
public void ExecuteCurrentTasks(){ List<Task> copyOfTasks = null; lock (_tasks) { copyOfTasks = _tasks; _tasks = new List<Task>(); } foreach (Task t in copyOfTasks) ExecuteSingleTask(t);}
This little refactoring give us around ~11 seconds for adding & executing 100 tasks.
Smoking!
Posted
Thursday, July 12, 2007 11:44 AM
by
OrenEllenbogen
| with no comments.
Posted
Monday, July 09, 2007 3:30 PM
by
OrenEllenbogen
| with no comments
P' inch LCD at the moment):
More pictures we'll be posted soon...
Posted
Sunday, July 08, 2007 9:39 PM
by
OrenEllenbogen
| with no comments | http://blogs.microsoft.co.il/blogs/orenellenbogen/ | crawl-003 | refinedweb | 2,581 | 70.43 |
I'm new to Scala... Here's the code:
def ack2(m: BigInt, n: BigInt): BigInt = { val z = BigInt(0) (m,n) match { case (z,_) => n+1 case (_,z) => ack2(m-1,1) // Compiler says unreachable code on the paren of ack2( case _ => ack2(m-1, ack2(m, n-1)) // Compiler says unreachable code on the paren of ack2( } }
I'm trying to understand that... why is it giving that error?
Note: I'm using Scala Eclipse Plugin 2.8.0.r21376-b20100408034031 ch.epfl.lamp.sdt.feature.group
--------------Solutions-------------
The z inside the pattern match does not refer to the z you declared outside, it introduces a new variable binding. So the first case will match every possible pair (binding z to the first element of the pair and discarding the second) and the other cases will never be reached.
If you replace
z in the pattern with
`z`
it will refer to the existing z and not introduce a new binding, so it will work as you intend. You can also rename z to Z if you don't like the syntax with backticks. | http://www.pcaskme.com/scala-compiler-says-unreachable-code-why/ | CC-MAIN-2019-04 | refinedweb | 189 | 67.79 |
This is the mail archive of the gdb-patches@sources.redhat.com mailing list for the GDB project.
>>>>> "David" == David Carlton <carlton@math.stanford.edu> writes: David> I'm no Java expert, but here's the situation as I understand David> it. When evaluating Java code, sometimes you have to generate David> new Java classes in an unpredictable manner. David> Alas, I don't know enough Java to be able to create a test David> case. I don't know very much about this part of gdb. However, I can say that in libgcj we create classes on the fly to represent arrays. Even the simplest Java program will create at least one such array (for String[]): public class t { public static void main(String[] args) { System.out.println(args.length); } } Then compile with: gcj --main=t -o t t.java There is at least one longstanding gdb SEGV that happens when trying to re-run a Java executable. This happens in most, but not every, gdb session. Unfortunately I can't try your patch in the near future. Tom | http://www.sourceware.org/ml/gdb-patches/2003-01/msg00662.html | CC-MAIN-2019-26 | refinedweb | 180 | 67.45 |
Encore: like a standalone JavaScript
application: it will require all of the dependencies it needs (e.g. jQuery or React),
including any CSS. Your
app.js file is already doing this with a special
require() function:
Encore’s job (via Webpack) is simple: to read and follow all of the
require()
statements and create one final
app.js (and
app.css) that contains everything
your app needs. Encore can do a lot more: minify files, pre-process Sass/LESS,
support React, Vue.js, etc. three new files:
public/build/app.js(holds all the JavaScript for your “app” entry)
public/build/app.css(holds all the CSS for your “app” entry)
public/build/runtime.js(a file that helps Webpack do its job)
Next, include these in your base layout file. Two Twig helpers from WebpackEncoreBundle can do most of the work for you:
That’s it! When you refresh your page, all of the JavaScript from
assets/js/app.js - as well as any other JavaScript files it included - will
be executed. All the CSS files that were required will also be displayed.
The
encore_entry_link_tags() and
encore_entry_script_tags() functions
read from an
entrypoints.json file that’s generated by Encore to know the exact
filename(s) to render. This file is especially useful because you can
enable versioning or
point assets to a CDN without making any changes to your
template: the paths in
entrypoints.json will always be the final, correct paths.
If you’re not using Symfony, you can ignore the
entrypoints.json file and
point to the final, built file directly.
entrypoints.json is only required for
some optional features.
New in version 0.21.0: The
encore_entry_link_tags() comes from WebpackEncoreBundle and relies
on a feature in Encore that was first introduced in version 0.21.0. Previously,
the
asset() function was used to point directly to the file.! If you previously ran
encore dev --watch, your final, built files
have already been updated: jQuery and
greet.js have been automatically
added to the output file (
app.js). Refresh to see the message!
The import and export Statements¶
Instead of using
require() and
module.exports like shown above, JavaScript
provides an alternate syntax based on the ECMAScript 6 modules that includes
the ability to use dynamic imports.
To export values using the alternate syntax, use
export:
To import values, use
import:
Page-Specific JavaScript or CSS (Multiple Entries)¶
So far, you only have one final JavaScript file:
app.js. For small applications
or SPA’s (Single Page Applications), that might be fine! However, as your app grows,
you may want to have page-specific JavaScript or CSS (e.g. checkout, account,
etc.). To handle this, create a new “entry” JavaScript file for each page:
Next, use
addEntry() to tell Webpack to read these two new files when it builds:
And because you just changed the
webpack.config.js file, make sure to stop
and restart Encore:
Webpack will now output a new
account.js file
in your build directory. And, if any of those files require/import CSS, Webpack
will also output
account.css files.
Finally, include the
script and
link tags on the individual pages where
you need them:
Now, the checkout page will contain all the JavaScript and CSS for the
app entry
(because this is included in
base.html.twig and there is the
{{ parent() }} call)
and your
See Creating Page-Specific CSS/JS for more details. To avoid duplicating the same code in different entry files, see Preventing Duplication by “Splitting” Shared Code into Separate Files.
Using Sass/LESS/Stylus¶
You’ve already mastered the basics of Encore. Nice! But, there are many more
features that you can opt into if you need them. For example, instead of using plain
CSS you can also use Sass, LESS or Stylus. To use Sass, rename the
app.css
file to
app.scss and update the
import statement:
Then, tell Encore to enable the Sass pre-processor:
Because you just changed your
webpack.config.js file, you’ll need to restart
Encore. When you do, you’ll see an error!
Encore supports many features. But, instead of forcing all of them on you, when you need a feature, Encore will tell you what you need to install. Run:
Your app now supports Sass. Encore also supports LESS and Stylus. See CSS Preprocessors: Sass, LESS, Stylus, etc..
Compiling Only a CSS File¶
Caution
Using
addStyleEntry() is supported, but not recommended. A better option
is to follow the pattern above: use
addEntry() to point to a JavaScript
file, then require the CSS needed from inside of that.
If you want to only compile a CSS file, that’s possible via
addStyleEntry():
This will output a new
some_page.css.
Keep Going!¶
Encore supports many more features! For a full list of what you can do, see Encore’s index.js file. Or, go back to list of Encore articles.
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license. | https://symfony.com/doc/4.3/frontend/encore/simple-example.html | CC-MAIN-2020-40 | refinedweb | 837 | 66.94 |
Extensible Hypertext Mark Up Language (XHTML) is the successive markup language to the near ubiquitous Hypertext Mark Up Language (HTML). Rooted in Standard Generalized Markup Language (SGML), HTML is flexible but complex, leaving the liberties with which web browsers take with its rules to cause a number of problems. Based on the strict and simple Extensible Markup Language (XML) standard, XHTML aims to resolve said problems while offering extensibility with other XML-based applications. In summation, XHTML is HTML rewritten to comply with XML, hence its name.
XHTML, being a subset of XML, will also be extensible to other XML applications and featured. For example, it may also include fragments from other XML based languages, such as Scalable Vector Graphics or MathML through the usage of namespaces.
What HTML Stands ForEdit
The abbreviation of HTML stands for HyperText Mark-Up Language. Explained in more detail, this means:
- H (Hyper): The opposite of linear. Instead of going from the first line to the following one, the decision in where and when everything is set is up to the programmer (Specifically, you.).
- T (Text): This one is self-explanatory. The programming language is created through text.
- M (Mark-Up): This is what you can do with the text; you can mark-ups to edit a text's style, such as boldness, headings, bullets, and so on.
- L (Language): Also self-explanatory. HTML is a programming language.
The ComponentsEdit
An XHTML document is made up of four main components:
- Document Type Definition (DTD): This used to be optional in HTML, but it is compulsory in XHTML. The DTD describes the language or script in which the text has been encoded.
- Text content: the headers and paragraphs that appear on the page.
- References: Advanced content like links and images.
- Mark-Up: Instructions on how the content should be displayed.
Each of these components is comprised of text. This means that the page can be saved in text format and viewed in any browser.
XHTML stands for extensible Hypertext Markup Language. It is a different version of HTML, it is based off of XML. XHTML is used to make webpages and has a very specific way to be written to be correct and without error. XHTML is also very case-sensitive. the tags are written in lowercase and need to be closed.The order of the tags also need to be in correct order for the information to come out correct. there are three main sections of XHTML consist of A declaration statement, a Head statement and a body. | https://en.m.wikibooks.org/wiki/XHTML/What_is_XHTML | CC-MAIN-2016-50 | refinedweb | 424 | 64.91 |
15-square Game
Join the DZone community and get the full member experience.Join For Free
py_s60 1.1.3 was released a week ago. I wonder why there's no more people playing with it. So, I have created a simple game as an example. I don't know what this game is called. It has 4x4 square box with 15 pieces (1 piece missing). You need to move all the pieces into sorting order. Since the program is so simple, I decided to make the moving of a piece smoother by moving it bit by bit. Hope this doesn't make the code to hard to read.
from appuifw import * from key_codes import * import e32, random # run and break-loop type of app sleep = e32.ao_sleep running = 1 def set_exit(): global running running = 0 app.exit_key_handler= set_exit # canvas and typical colors c = Canvas() app.body = c red, green, blue, gray, white = 0xff0000, 0x00ff00, 0x0000ff, 0x777777, 0xffffff # randomize number order for pieces seq = range(1,17) random.shuffle(seq) b = [seq[0:4], seq[4:8], seq[8:12], seq[12:16]] def piece(i, j, n): if n < 10: c.text( (12+20*i, 20+20*j), unicode(n)) else: c.text( (7+20*i, 20+20*j), unicode(n)) def box(i, j, color, fill=None): c.rectangle( [5+20*i, 5+20*j, 25+20*i, 25+20*j], color, fill) # draw board pieces for k in range(16): j, i = divmod(k, 4) piece(i, j, b[j][i]) y, x = divmod(seq.index(16), 4) box(x, y, white, white) moving = 0 # cursor to lock if animating # move cursor in dx, dy direction def move(dx, dy): global x,y, moving if moving: return moving = 1 if 0 <= x-dx < 4 and 0 <= y-dy < 4: b[y][x] = b[y-dy][x-dx] animate(x-dx, y-dy, dx, dy, b[y][x]) x -= dx # the hole move in opposite direction y -= dy moving = 0 # moving a piece for x,y to dx, dy direction def animate(x, y, dx, dy, n): if n < 10: px = 12 else: px = 7 for i in range(5): c.text( (px+20*x + 4*i*dx, 20+20*y + 4*i*dy), unicode(n)) sleep(0.05) c.text( (px+20*x + 4*i*dx, 20+20*y + 4*i*dy), unicode(n), white) c.text( [px+20*(x+dx), 20+20*(y+dy)], unicode(n) ) # bind arrow keys c.bind(EKeyRightArrow,lambda:move(1, 0)) c.bind(EKeyLeftArrow,lambda:move(-1, 0)) c.bind(EKeyUpArrow,lambda:move(0, -1)) c.bind(EKeyDownArrow,lambda:move(0, 1)) # main loop, just wait while running: sleep(0.1)
Topics:
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/15-square-game | CC-MAIN-2016-40 | refinedweb | 463 | 67.55 |
Synopsis edit
-
- yield ?value?
See Also edit
- yieldto
- instead of yielding a value directly, execute a command in place of the current coroutine context, which then returns a value.
- tcl::unsupported::yieldm
- an experiment in passing multiple values to a coroutine. yieldm turned out to be trivial to implement in terms of yieldto.
Description edityield arranges for the associated coroutine command of the current coroutine to return value if it is provided, or the empty string otherwise. The current coroutine context continues to exist. The next time the associated coroutine context command is executed, any argument passed to it becomes the return value of the yield that previously exited the coroutine context. If the associated coroutine context command is not given an argument, the return value of yield is the empty string.DKF: Can also be thought of as a magical form of return. That itself returns (possibly).
Example: Basic edit
proc onetwo {} { yield [info coroutine] yield 1 return 2 }
% coroutine count onetwo ::count % count 1 % count 2 % count invalid command name "count"
Coloop editDKF: If you're trying to build a coroutine that iteratively yields values, it can be a little bit tricky to work out how to string the value passing through yield nicely; the values just don't seem to pass around in a way that feels natural (well, to me anyway). Here's a helper procedure that makes it all much easier:
proc coloop {var body} { set val [info coroutine] upvar 1 $var v while 1 { set v [yield $val] set val [uplevel 1 $body] } }With this, you get an automatic yield of the name of the coroutine to start with, and then you can pass values in and have results passed back. The given variable is set to the value passed in, and the result of evaluating the body is the next value yielded. You might use it like this:
proc summerBody n { coloop x { incr n $x } } coroutine s summerBody 0; # ==> ::s s 10; # ==> 10 s 5; # ==> 15 s 2; # ==> 17 s 1; # ==> 18Without coloop, you'd need to write something like this:
proc summerBody {n} { set x [yield [info coroutine]] while 1 { set x [yield [incr n $x]] } }Which is not much longer, but is much less clear as to what value is flowing where. With longer bodies, it becomes even less clear.
Example: yield From Any Command in a Coroutine Context edityield can happen in anywhere in a coroutine context, not just in the command specified as the initial entry point to the coroutine context. In the following example, alphadig is the initial entry point, but p1 and p2 also yield from the same coroutine context:
proc p1 {} { foreach digit {1 2 3} { yield $digit } p2 } proc p2 {} { foreach digit {4 5 6} { yield $digit } } proc alphadig {} { yield [info coroutine] p1 } set name [coroutine c1 alphadig] while 1 { set res [c1] if {[namespace which c1] eq $name } { puts $res } else { #discard last result, which is the coroutine "falling off the end" rather #than a real value break } }Output:
1 2 3 4 5 6 | http://wiki.tcl.tk/13849 | CC-MAIN-2016-50 | refinedweb | 512 | 58.25 |
OSError: Couldn't connect to Modem!
Hello.
We are trying to debug a problem we are having related to the LTE modem on the FiPy.
When pycom.lte_modem_en_on_boot() is set to False we are experiencing that we can not start LTE communication at all after a reset (deepsleep, machine.reset or button), but not after power cycling the device. As far as I understand, this flag should only stop the LTE modem from starting up every boot, but should not disable it all together. Will not post the entire code where we have done most of our testing with (too many files), but have created a simplified version that we have been able to reproduce it with:
from network import LTE import pycom import time import machine if pycom.lte_modem_en_on_boot(): print("LTE on boot was enabled. Disabling.") pycom.lte_modem_en_on_boot(False) lte = LTE() print("got lte!") time.sleep(10) machine.reset()
expected output when doing a "soft" reset: "OSError: Couldn't connect to Modem!"
expected output after powercycle: "got lte"
fipy firmware: 1.18.2.r7
modem firmware: LR5.1.1.0-41065
Any help or suggestions would be appreciated.
@tveito Sorry for the late reply. I meant 1.18.2 with no revision update. So I had 1.18.2.r7 and it didn't work so I downgraded to 1.18.2 and it worked.
@rskoniec Thank you for your support. I've already fixed this problem by upgrading the modem firmware.
Now I am trying to connect to Telstra network in Australia but I got stuck when lte is not attached, as shown in the picture below. Could you please help me to figure out this problem?
@diepducle Maybe clues from this thread would be helpful
@rskoniec Thank you for your reply.
I tried to downgrade to some versions like: FiPy-1.18.2.r6, FiPy-1.18.2.r5, FiPy-1.18.2, FiPy-1.18.1.r7 but all show the same problem is that the triple arrows are disappeared.
When I upgrade to version FiPy-1.18.3 from the version FiPy-1.18.2.r7 (using), they show the problem of OSError: Couldn't connect to modem.
@diepducle Try with downgrade to or upgrade to Here is the full list of FiPy f/w
@rskoniec By the way, before the firmware version 1.18.2.r7 being used, I used to upgraded the firmware to version 1.18.2.r6 [pybytes], and I got a different problem when entering the code "lte = LTE()" (as same as the following topic:). I wonder that which firmware version should I use and am I doing the right track.
@rskoniec Thank you for your reply. I tried to use pycom.lte_modem_en_on_boot(False) but the result was still the same.
I am a newbie in this area and trying to send data to pybytes after this. But now I am struggling with LTE M1 connection. Could you please tell me the way to fix this problem? Many thanks!
@diepducle From the logic of your code/commands you want to disable
pycom.lte_modem_en_on_bootif it's enabled so you shold use
pycom.lte_modem_en_on_boot(False)or
pycom.lte_modem_en_on_boot(0)
@tveito Hi, I got the same problem here. My device has firmware version 1.18.2.v7. I did a reset but there is still stuck after entering the code "lte = LTE()". Please help me. Thank you!!
@Edward-Dimmack Hello and thanks for the response. Could you please give me the last part of the firmware? As my units did have firmware version 1.18.2.r7 (so still 1.18.2).
If anyone still have problems we have figured out a way of reliably turning on the modem:
When communicating set lte_modem_en_on_boot() to True.
Do a reset.
communicate.
This does however introduce the need to keep state between resets, but that can be done by ether checking if lte_modem_en_on_boot is set to True or by checking reset cause if you don't want to start using the eeprom.
@rskoniec Thank you for that. I tried all the modem firmware and it seemed to have little effect. However, I changed the firmware version to version 1.18.2 on the FiPy and so far they are all working. Even the ones that weren't working at all. Not sure if it will work for anyone else and I haven't done thorough testing yet. Will update if anything changes.
@Edward-Dimmack said in OSError: Couldn't connect to Modem!:
(...) Maybe the Sequans firmware on the first device is different but I am not sure where to get an older firmware for the modem.
You can use my prv modem f/w repo
I agree. I wasn't having this issue with the first device we bought so we bought 14 more and all 14 are having the same issue. Some intermittent and some simply never work. I need to try downgrading the firmware but other than that everything is the same. Maybe the Sequans firmware on the first device is different but I am not sure where to get an older firmware for the modem.
@tveito It's insane that this thread never received a response from Pycom. I'm facing the same issue on the GPy which is entirely foreclosing usage of the one and only thing I bought the board for: LTE communications. | https://forum.pycom.io/topic/4922/oserror-couldn-t-connect-to-modem/1 | CC-MAIN-2021-17 | refinedweb | 892 | 76.22 |
Provided by: openssh-client_8.4p1-6ubuntu2_amd64_file]
DESCRIPTION
ssh-keygen generates, manages and converts authentication keys for ssh(1). ssh-keygen can create keys for use by SSH protocol version 2. The type of key to be generated is specified with the -t option. If invoked without any arguments, ssh-keygen will generate an RSA key./id_dsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ecdsa_sk, ~/.ssh/id_ed25519, ~/.ssh/id_ed25519_sk the corresponding public key copied to other machines. ssh-keygen will by default write keys in an OpenSSH-specific format. This format is preferred as it offers better protection for keys at rest as well as allowing storage of key comments within the private key file itself. The key comment may be useful to help identify the key. The comment is initialized to “user@host” when the key is created, but can be changed using the -c option. It is still possible for ssh-keygen to write the previously-used PEM format private keys using the -m flag. This may be used when generating new keys, and existing new-format keys may be converted using this option in conjunction with the -p (change passphrase) flag. After a key is generated, ssh-keygen will ask where the keys should be placed to be activated. The options are as follows: -A For each of the key types (rsa, dsa, ecdsa and ed25519) for which host keys do not exist, generate the host keys with the default key file path, an empty passphrase, default bits for the key type, and default comment. If -f has also been specified, its argument is used as a prefix to the default path for the. Generally, 3072. authenticator. -k Generate a KRL file. In this mode, ssh-keygen will generate a KRL file at the location specified via the -f flag that revokes every key or certificate presented on the command line. Keys/certificates to be revoked may be specified by public key file or using the format described in the KEY REVOCATION LISTS section. -L Prints the contents of one or more certificates. -l Show fingerprint of specified public key file. For RSA and DSA keys ssh-keygen tries to find the matching public key file and prints its fingerprint. If combined with -v, a visual ASCII art representation of the key is supplied with the fingerprint. -M passphrase operation. format is “RFC4716”. Setting a format of “PEM” when generating or updating a supported private key type will cause the key to be stored in the legacy PEM private key format. authenticator,. verify-required Indicate that this private key should require user verification for each signature. Not all FIDO tokens support this option. Currently PIN authentication is the only supported verification method, but other methods may be supported in the future. write-attestation=path May be used at key generation time to record the attestation data returned from FIDO tokens during key generation. Please note that this information is potentially sensitive. By default, this information is discarded. The -O option may be specified multiple times. . If the -l option is also specified then the contents of the KRL will be printed. -q Silence ssh-keygen. recommended), “rsa-sha2-256”, and “rsa-sha2-512” (the default). . the string “always” to indicate the certificate has no specified start time, a date in YYYYMMDD format, a time in YYYYMMDDHHMM[SS] format, a relative time (to the current time) consisting of a minus sign followed by an interval in the format described in the TIME FORMATS section of sshd_config(5). The end time may be specified as a YYYYMMDD date, a YYYYMMDDHHMM[SS] time, a relative time starting with a plus character or the string “forever” to indicate that the certificate has no expiry date.). “-1m:forever” (valid from one minute ago and never expiring). -v Verbose mode. Causes ssh-keygen to print debugging messages about its progress. This is helpful for debugging moduli namespace, used to prevent signature confusion across different domains of use (e.g. file signing vs email signing) must be provided specified. user_key.pub Similarly, it is possible for the CA key to be hosted in a ssh-agent(1). This is indicated by the -U flag and, again, the CA key must be identified by its public half. $ ssh-keygen -Us ca_key.pub disable a flag). Extensions may be ignored by a client or server that does not recognise them, whereas unknown critical options will cause the certificate to be refused.. no-touch-required Do not require signatures made using this key include. Only SHA256 fingerprints are supported here and resultant KRLs are not supported by OpenSSH versions prior to 7.9..type, base64-encoded key. Empty lines and lines starting with a ‘#’ corresponding key to be considered acceptable for verification. The options (if present) consist of comma-separated option specifications. No spaces are permitted, except within double quotes. The following_ecdsa_sk.pub ~/.ssh/id_ed25519.pub ~/.ssh/id_ed25519_sk.pub ~/.ssh/id_rsa.pub Contains the DSA, ECDSA, authenticator-hosted ECDSA, Ed25519, authenticator-hosted. | https://manpages.ubuntu.com/manpages/impish/en/man1/ssh-keygen.1.html | CC-MAIN-2022-27 | refinedweb | 830 | 56.96 |
Alex Rousskov wrote:
>.
Ah, but it did. it just used a mix of some #define (2.x,3.0) and class
methods (3.0) and added upper case letters in the name.
>
>>.
Ok let me make this clearer. the #defines and methods above did
_explicit_ calls to c_str().
At this stage we actually have a three-way choice:
- backout
- add in c_str() every place its needed.
- add forced down-casting.
since the down-caster is simply an inline of c_str() the last two
options are the same, one with more work, one with less. Same actions.
With the downcasting its only 'implicit' in the nature of we cannot say
'its used there, and there, and there' without a full code audit.
Being part of string we can be certain that it will be be used only
where the old methods/defines were valid.
>
> Moreover, if we must have implicit casts for the new API to work,
> perhaps we should back out the entire API change for now because we are
> not good at predicting the side-effects of such implicit casts.
>
It's one of the options.
>>...
After you mentioned this on IRC I went back to my copy of the original
patch.
Attached is a pseudo-patch (has stuff elided so I don't expect it will
map cleanly) showing all the str* changes and re-arranging you are
worried about. All I have elided is the effected debug calls and
straight name mods; buf() to c_str() etc.
I have also left in the hash function-ptrs where I explicitly set the
namespace on strcmp so as not to clash their old values with anything new.
Amos
This archive was generated by hypermail pre-2.1.9 : Fri Jun 01 2007 - 12:00:09 MDT | http://www.squid-cache.org/mail-archive/squid-dev/200705/0141.html | CC-MAIN-2014-15 | refinedweb | 296 | 82.75 |
On Fri, Feb 17, 2017 at 12:02:52PM +0100, Florian Weimer wrote:> We want to reject PTY devices from other namespaces as valid input to> the ttyname and ttyname_r functions, while still providing a hint to> callers that the device is, in fact, a PTY. Christian Brauner wrote a> glibc patch for this:> > <>> > It hard-codes the major PTY device number range. Is this feasible?> Is it part of the stable userspace ABI for the TTY subsystem?What major numbers are you using in the patch '2' and '3'? And yes,major numbers are static and you should be fine to rely on them. Butcan't you test that the device is a pty to verify it?thanks,greg k-h | https://lkml.org/lkml/2017/2/17/556 | CC-MAIN-2017-43 | refinedweb | 122 | 80.51 |
Details
- Type:
Bug
- Status: Closed
- Priority:
Minor
- Resolution: Done
- Affects Version/s: Jena 2.7.4
- Fix Version/s: Jena 2.11.0
- Component/s: Build, Ontology API
- Labels:None
- Environment:
Java 7 (1.7.0_07) Linux 64 bit. (but not Java 1.6.0_24)
Description
Under java7, the build of jena core gets two stacktraces (marked as warning) in javadoc production. Unclear if the javadoc output is materially affected.
The following two files are:
com/hp/hpl/jena/vocabulary/DAMLVocabulary.java
com/hp/hpl/jena/vocabulary/DAML_OIL.java
It's unclear as to whether DAML_OIL.java problems maybe due to implementing DAMLVocabulary and nothing more.
/usr/lib/jvm/java-7-openjdk-amd64/bin/javadoc \
-classpath fuseki-server.jar \ – just a source of compiled Jena and all dependencies
-encoding utf-8 \
-d jdoc I.java
The core problem is the form:
-----------------------------------------------------
import com.hp.hpl.jena.rdf.model.Resource ;
import com.hp.hpl.jena.rdf.model.Property ;
public interface I{ public Resource Property(); }
-----------------------------------------------------
where Property is a class and a method name, which is legal, it just breaks javadoc (standard doclet).
Activity
- All
- Work Log
- History
- Activity
- Transitions
I haven't checked on the consequence of ignoring the build error - stand-alone you get one blank page but maybe whether later classes also are missing.
We can live with two missing pages.
If there is no other DAML in Jena any more, I think removal is in order.
I deleted the vocabularies to see what breaks:
reasoner - DAMLMicroReasonerFactory
ontapi - DAML_OILProfile
OntResourceImpl.
Can these be cleaned up now? Is it just a case of removing old junk?
ARP and the RDFXML unparser know about DAML vocabulary. We could move the vocabularies to be internal and do a rename of the painful Property().
For now:
1/ Classes marked deprecated
2/ removed from some common prefixes
Restored default prefix mappings - tests break otherwise looking for a built-in prefix.
It seems there are still tests of DAML stuff in Jena in TestOntAssembler. Together with DAMLMicroReasoner just how much of DAML has been removed from Jena? Maybe much/all of it is unreachable from the API.
Can we do more removal before the next release?
OK, I deleted the various DAML vocabulary classes in my local copy of Jena, and then performed a bunch of edits to make the codebase consistent and the tests pass. None of the edits were particularly bothersome - commenting out DAML-specific tests and unparser behaviours - but there were quite a lot of them. I think the right think to do is mark the classes as deprecated this cycle, and I'll remove them - and make the codebase consistent - immediately after we release so that they're gone in the next cycle. Would that be OK?
Set fix version – bulk change to set old and unmarked issues to 2.11.0.
The rest of the DAML support is long gone in Jena, so I suggest these classes get removed as soon as practicable. At the very least we should deprecate them this cycle and remove them next cycle. In practice, I strongly doubt anyone would notice if we just removed them now.
In the meantime, I would like to think that it would be possible to exclude a certain class from Javadoc generation, but a quick look at the Maven javadoc configuration page [1] suggests that you can only exclude by package name, not by class.
[1] | https://issues.apache.org/jira/browse/JENA-333 | CC-MAIN-2017-34 | refinedweb | 567 | 57.57 |
By default, the view frustum is arranged symmetrically around the camera’s center line, but it doesn’t necessarily need to be. You can make the frustum oblique, which means that one side is at a smaller angle to the centre line than the opposite side.
This makes the perspective on one side of the image seem more condensed, giving the impression that the viewer is very close to the object visible at that edge. An example of how this can be used is a car racing game; if the frustum is flattened at its bottom edge, it appears to the viewer that they are closer to the road, accentuating the feeling of speed.
In the Built-in Render Pipeline, a Camera that uses an oblique frustum can only use the Forward rendering path. If your Camera is set to use the Deferred Shading rendering path and you make its frustum oblique, Unity forces that Camera to use the Forward rendering path.
Although the Camera component does not have functions specifically for setting the obliqueness of the frustum, you can do it by either enabling the camera’s Physical Camera properties and applying a Lens Shift, or by adding a script to alter the camera’s projection matrix.
Enable a camera’s Physical Camera properties to expose the Lens Shift options. You can use these to offset the camera’s focal center along the X and Y axes in a way that minimizes distortion of the rendered image.
Shifting the lens reduces the frustum angle on the side opposite the direction of the shift. For example, as you shift the lens up, the angle between the bottom of the frustum and the camera’s center line gets smaller.
For further information about the Physical Camera options, see documentation on Physical Cameras.
For further information about setting individual Physical Camera properties, see the Camera Component reference.
The following script example shows how to quickly achieve an oblique frustum by altering the camera’s projection matrix. Note that you can only see the effect of the script while the game is running Play mode.
using UnityEngine; using System.Collections; public class ExampleScript : MonoBehaviour { void SetObliqueness(float horizObl, float vertObl) { Matrix4x4 mat = Camera.main.projectionMatrix; mat[0, 2] = horizObl; mat[1, 2] = vertObl; Camera.main.projectionMatrix = mat; } }
_Ejemplo de un C# script
It is not necessary to understand how the projection matrix works to make use of this. The horizObl and vertObl values set the amount of horizontal and vertical obliqueness, respectively. A value of zero indicates no obliqueness. A positive value shifts the frustum rightwards or upwards, thereby flattening the left or bottom side. A negative value shifts leftwards or downwards and consequently flattens the right or top side of the frustum. The effect can be seen directly if this script is added to a camera and the game is switched to the scene view while the game runs; the wireframe depiction of the camera’s frustum will change as you vary the values of horizObl and vertObl in the inspector. A value of 1 or –1 in either variable indicates that one side of the frustum is completely flat against the centreline. It is possible although seldom necessary to use values outside this range. | https://docs.unity3d.com/es/2020.1/Manual/ObliqueFrustum.html | CC-MAIN-2020-29 | refinedweb | 543 | 50.97 |
The FeedFlare API (FlareAPI) allows anyone to extend our existing FeedFlare service. Provide new actions and incorporate outside services to make your content more interesting and engaging — both in your FeedBurner feed and on your website.
This document assumes you are a web application developer familiar with XML and one or more server-side programming structures, such as Perl, Cold Fusion, Java/JSP, ASP, or Ruby. Server-side language skills are required in order to create "dynamic" FeedFlare units, which are described in more detail below.
Note: In the XML code samples below, the ↵ symbol is used to indicate a linebreak used for spacing in the middle of long, unbroken string (such as a URL). If you copy and paste the code, you will want to remove this character and stitch the string back together at the point this symbol appeared.
The code that defines how FeedFlare should operate is encapsulated in a FeedFlare Unit file. This is an XML document that tells FeedBurner how to render a FeedFlare in the feed and on the site, and it identifies the communication channels that need to be established when creating an instance of a FeedFlare. Every FeedFlare unit is ultimately identified by a URL that either FeedBurner or a third party maintains.
A FeedFlare unit has two pieces of
information: catalog information and the instructions for generating an
instance of a FeedFlare. Additional attributes and behaviors will be
added over time. There are two main classifications for a FeedFlare unit: static or
dynamic. A static FeedFlare unit (represented by a
<FeedFlare>
element in the unit XML) generates FeedFlare that does not change its
text or image over time, while a dynamic FeedFlare unit (represented by
a
<DynamicFlare>
element in the unit XML) might change its representation based upon the
item data over time. A FeedFlare that says "Email This" would most
likely be static, while a FeedFlare that says "There are 3 comments ...
add yours now!" would be dynamic (because the number of comments would most likely increase over
time). In both cases, the flare link destination will likely be
variable based upon information from the feed or item.
Ah, Hello World, my old friend. We meet again. Let's say that we want to create a FeedFlare unit that just says "Hello, World" and nothing else. It's so featureless it doesn't even offer a link to click on, but we have to start somewhere.
Here's what this FeedFlare unit looks like:
<FeedFlareUnit> <Catalog> <Title>Hello World 1</Title> <Description>A static FeedFlare unit that just shows the text "Hello, World" </Description> </Catalog> <FeedFlare> <Text>Hello, World</Text> </FeedFlare> </FeedFlareUnit>
To create this FeedFlare unit, we have to create an XML file and then host it somewhere so it has a URL FeedBurner can read.
Aside: Where do I put this XML file?
The XML file that describes a FeedFlare unit needs to be addressable by a public URL, so that means it needs to be hosted on a server somewhere so it can be periodically retrieved by FeedBurner. Here are suggestions for where you can host this file:
We have hosted this file at. Publishers can now log in to FeedBurner, select the FeedFlare service, and enter that URL. Save the feed, take a look, and you should see your "Hello, World" nice and proud at the bottom of every feed item.
Let's do something a little more interesting. Let's create a FeedFlare unit that links to web resources that might be related to the current item. To do that, we'll need to do some variable substitution.
The neat thing about FeedFlare is that the unit has the entire context of the item (including the rest of the feed) available for
these variable substitutions. So, if you want to get the item's title, you can just put
${title}
in the text of the FeedFlare and the current item's title will be substituted in there. Another variable that is available is the item's
link:
${link}.
We'll talk about more powerful XPath variable substitutions below, but for now we can use Google's "similar pages" query and construct a FeedFlare unit like this:
<FeedFlareUnit> <Catalog> <Title>See Related Pages at Google</Title> <Description>A static FeedFlare unit that links to a Google page that shows pages that are similar to the current item</Description> </Catalog> <FeedFlare> <Text>Hello, see related pages</Text> <Link href="{link}"/> </FeedFlare> </FeedFlareUnit>
It seems to work, and now when a reader clicks on the FeedFlare they are taken to a page with related links. You can find this file at.
Let's make the greeting a bit more personalized. Many times, the author or publisher's name is present in the feed. So let's do a couple of things .. let's say "Hello from (author)" and then link to the blog home page. We saw before that there are a few "shortcut" variables like title, but you as a FeedFlare developer have the full power of XPath at your disposal. You can construct XPath variable substitutions, so if you'd like the feed's title you could use an expression like
${../title}, which would get the item's parent's title, i.e. the feed title.
Now, that's not exactly true. The actual expression you'd need to use is
${../a:title}.
When you do XPath variable substitution, each element needs a "namespace prefix", and the "normal" feed elements have the prefix "a".
You also can define other namespaces to use.
"But wait," you exclaim. "There are all sorts of different feed formats. Do I have to provide different XPaths for different formats? That's sheer madness." Good question. The answer we are happy to offer is an emphatic "no." If you use XPath variable substitution, FeedBurner will automatically convert your feed to an Atom 1.0 feed behind the scenes and use that for the XPath. This doesn't mean that your RSS 2.0 feed will now be delivered as an Atom 1.0 feed; it just means that, for the purposes of doing this variable substitution, FeedBurner works on an Atom 1.0 copy of the feed to grab the appropriate information.
That's plenty of talk; let's see what this FeedFlare unit looks like:
<FeedFlareUnit> <Catalog> <Title>Hello World 2</Title> <Description>A static FeedFlare unit that says hello from the author and links to the main web page</Description> </Catalog> <FeedFlare> <Text>Hello from ${(ancestor-or-self::*/a:author/a:name)[last()]}</Text> <Link href="${../a:link[(@rel='alternate' or not(@rel))]/@href}"/> </FeedFlare> </FeedFlareUnit>
So, this is more complex than your average FeedFlare unit. But let's walk through it. This is a static FeedFlare, since the link and text we construct never changes. Both the text and the link are using variable substitution. There are a bunch of common XPath expressions listed in the Common XPath Expressions section of the document, but let's look at these:
${(ancestor-or-self::*/a:author/a:name)[last()]}
hrefattribute of the feed's link with
rel="alternate"or the feed's link with no
relattribute (since if the
relattribute is not specified, it represents the alternate location ... see the rel attribute documentation for more information).
When all is said and done and we put this FeedFlare unit at some URL (we have it at), we get some new FeedFlare (provided your feed has an author element specified for it):
Let's try a dynamic FeedFlare unit. How about we greet the name of the person who made the most recent comment? This is going to change over time, so we need to make this a dynamic FeedFlare unit. We're going to assume here that the publisher is using the Atom Feed Thread Extension framework, but you could also adapt this to support the wfw Comment API.
In a dynamic FeedFlare unit, you are constructing a URL that will be periodically called by FeedBurner, and it is the responsibility of that URL to return an XML document that represents a FeedFlare. That means you need to have some server-side programming language skills to be able to create dynamic FeedFlare units.
Let's look at this FeedFlare unit
<FeedFlareUnit> <Catalog> <Title>Hello, Visitor</Title> <Description>Greet the person who made the most recent comment to the current post.</Description> </Catalog> <DynamicFlare href="?↵ feedUrl=${a:link[@rel='replies']/@href}"/> <SampleFlare> <Text>Hello, Crawford Matrix. Thank you for your comment!</Text> </SampleFlare> </FeedFlareUnit>
When FeedBurner sees a new item and applies this FeedFlare unit to that item, it does the variable substitution to construct a URL that it will call periodically. This URL is only constructed once, but it is expected that the results that the URL returns will change over time. If an XPath variable substitution cannot be resolved (i.e., the feed is not using the Feed Thread Extension), then a FeedFlare will not be created for that item.
To continue with the example, let's say an item in the feed looks like this:
<entry> <title>Increasingly disenchanted with backgammon</title> <link rel="replies" type="application/atom+xml" href="" thr: <link rel="service.edit" type="application/atom+xml" href="" title="Increasingly disenchanted with backgammon"/> <id>tag:</id> <published>2006-01-03T23:25:39Z</published> ... </entry>
FeedBurner sees this item and constructs the following URL that it will call periodically:
GET↵ .com/2006/01/increasingly_di-comments.xml
(In this example, we're using a
feedburner.com address for the DynamicFlare URL,
but it is expected that these will be hosted on many third party sites, including yours.) When FeedBurner calls this URL, it expects a response that contains a FeedFlare element:
<FeedFlare> <Text>Hello, Crawford Matrix. Thank you for your comment!</Text> <Link href=""/> </FeedFlare>
FeedBurner will make sure that the latest value for the dynamic FeedFlare unit is displayed in the feed — without the item showing up as modified. Cool, huh? The FeedFlare will also be updated on the site.
One more thing to mention about this example. You may wonder what the
SampleFlare element is. When a publisher wants to add your FeedFlare unit to their feed, the
SampleFlare serves as an example of what the FeedFlare might look like. FeedBurner
won't have an actual feed to use the
DynamicFlare to generate a FeedFlare, so that's why a
SampleFlare is
required for dynamic FeedFlare units. You can also provide a
SampleFlare element with static FeedFlare units, but it's not required.
One thing to note with dynamic FeedFlare units is that, at this point, FeedBurner only supports a GET query to retrieve the FeedFlare. That means that you are somewhat limited in the information that you can pass to the DynamicFlare URL — passing in the entire content of an item, for example, will most likely result in a GET request that is too long. We plan on supporting the POST method in a later iteration, which would address this limitation, but for now you might have to get creative if you want to create a FeedFlare unit that operates on the content of an item.
As an example, let's say that you want to create a FeedFlare unit that simply displays "Monkey Alert!" if an item's content references, well, a monkey (thank you Jon Klem for this demented example). One can get creative with some XPath functions to achieve this result:
<FeedFlareUnit> <Catalog> <Title>Monkey Alert!</Title> <Description>Show an alert if the post contains the word "monkey"</Description> </Catalog> <FeedFlare> <Text>Monkey Alert for "${.[count((a:content//text())[contains(.,'monkey')]) > 0]/a:title}"!</Text> </FeedFlare> </FeedFlareUnit>
The text of this static FeedFlare unit (which is found at) will only evaluate if a content object associated with the item contains the word "monkey". I'm sure publishers are rushing right now to include the Monkey Alert FeedFlare unit in their feeds.
The best way to learn how to create a FeedFlare unit is to probably find one that pretty much does what you want, and then adapt it. To that end, FeedBurner is maintaining a list of numerous FeedFlare examples that can be "adapted" to your own needs. If you create a FeedFlare unit that you'd like to share, visit the FeedBurner for Developers forum.
Official FeedFlare: Static Examples
In this initial release of the FeedFlare API, you can test your FeedFlare code with real feeds immediately by using FeedBurner's FeedFlare Scratchpad. Also, here is a FeedFlare unit XML quick reference. While FeedBurner plans on adding a number of testing and diagnostic tools to help FeedFlare developers, here are a few tips to help developers create new FeedFlare units., start out by using the URL something like that, and then just increment the version number every time you edit the XML file. This will force FeedBurner to retrieve the latest version of the file when it is used for the first time.
xmlns:prefixmechanism.
Since a FeedFlare unit is a static XML file, the variability comes
from,
well, variables in the link and text declarations. Basically, a
FeedFlare unit
has access to the context of the item and its feed container.
FeedBurner normalizes the item to an Atom 1.0 item with a feed
container, and the publisher can include any XPath as a variable in the
elements that support variability. We currently support XPath 1.0, but
we will upgrade to XPath 2.0 soon. Please note that the "current node"
for that XPath
expression will be the
<entry> element that represents the current item. Here is a list of some common variable substitutions:
The Atom 1.0 namespace is available with the "a" prefix. Other namespaces can be declared on the containing element and referenced in the expression.
A few of the variables are used so often there are "shortcuts" for them:
This is the initial release of the FeedFlare API, and we'll be adding new features and functionality often. Here are some things you can look forward to in future iterations of the API:
Here is the DTD for the FeedFlare unit file:
<!ELEMENT FeedFlareUnit (Catalog, ((FeedFlare,SampleFlare?) | (DynamicFlare,SampleFlare)))>
<!ELEMENT Catalog (Title, Description, Link?, Author?)>
<!ELEMENT Title (#PCDATA)>
<!ELEMENT Description (#PCDATA)>
<!ELEMENT Link EMPTY>
<!ATTLIST Link href CDATA #REQUIRED>
<!ELEMENT Author (#PCDATA)>
<!ATTLIST Author email CDATA #IMPLIED>
<!ELEMENT FeedFlare (Text?, Image?, Link?)>
<!ELEMENT Text (#PCDATA)>
<!ELEMENT Image EMPTY>
<!ATTLIST Image src CDATA #REQUIRED>
<!ELEMENT DynamicFlare EMPTY>
<!ATTLIST DynamicFlare href CDATA #REQUIRED>
<!ATTLIST DynamicFlare method CDATA #IMPLIED>
<!ELEMENT SampleFlare (Text?, Image?)>
And here is the DTD for the XML that is returned from a dynamic FeedFlare call:
<!ELEMENT FeedFlare (Text?, Image?, Link?)>
<!ELEMENT Text (#PCDATA)>
<!ELEMENT Image EMPTY>
<!ATTLIST Image src CDATA #REQUIRED>
<!ELEMENT Link EMPTY>
<!ATTLIST Link href CDATA #REQUIRED> | http://code.google.com/apis/feedburner/feedflare_dev_guide.html | crawl-002 | refinedweb | 2,463 | 63.8 |
Welcome to the Parallax Discussion Forums, sign-up to participate.
#include "simpletools.h"
#define POS_EDGE_CTR 0b01010 << 26; // Pos edge counter config val
void pinToggle(void *par); // Function prototype
volatile int dt, n, pin; // Shared between cogs
unsigned int stack[43 + 128]; // Large stack - prototyping
int main() // Main function
{
pin = 5;
//dt = CLKFREQ/10; // Set toggle interval
cogstart(pinToggle, NULL, // Pin toggle process to other cog
stack, sizeof(stack));
FRQA = 1; // PHSA+1 for each pos edge
CTRA = pin | POS_EDGE_CTR; // CTRA pos edge count on P5
int dtm = CLKFREQ; // Time increment for main
int t = CNT; // Capture current tick count
while(1) // Main loop
{
PHSA = 0; // Clear phase accumulator
waitcnt(t += dtm); // Wait 1 s
int cycles = PHSA; // Capture cycle count
print("n = %d, ", n); // Display n
print("cycles = %d\n", cycles); // Display cycles counted
}
}
//__attribute__((fcache)) // Cache this function in cog
void pinToggle(void *par) // pinToggle function
{
int pmask = 1 << pin; // Set up pin mask
DIRA |= pmask; // Pin to output
//int t = CNT; // Capture current time
while(1) // Main loop in cog
{
//n++; // Keep a running count
OUTA ^= pmask; // Toggle output
//waitcnt(t+ = 5; // Set pin to P5
pinToggle.dt = CLKFREQ/100; // Set toggle interval
pinToggle.n = 0; // Initialize n to 0
// Launch COGC code into another cog.
// IMPORTANT: pinToggle_cogc is a term that has to match pinToggle_cogc in
// the pinToggle.cogc file. If you change it to abc there, it would have to be
// changed to abc here too.
extern unsigned int *pinToggle_cogc;
int cog = cognew(pinToggle_cogc, &pinToggle) + 1;
FRQA = 1; // PHSA+1 for each pos edge
CTRA = pinToggle.pin | POS_EDGE_CTR; // CTRA pos edge count on P5
int dtm = CLKFREQ; // Time increment for main
int t = CNT; // Capture current tick count
while(1) // Main loop
{
PHSA = 1; // Clear phase accumulator
waitcnt(t += dtm); // Wait 1 s
int cycles = PHSA; // Capture cycle count
print("n = %d, ", pinToggle.n); // Display n
print("cycles = %d\n", cycles); // Display cycles counted
}
}
/*
pinToggle.h
Type-define a structure with variables that the code in Test pinToggle.c and
pinToggle.cogc can both access.
*/
typedef // A custom variable that's
struct pinToggle_s // a structure named pinToggle_s
{
volatile int dt, n, pin; // with vars shared by cogs
}
pinToggle_t; // is type-defined pinToggle_t.
/*
pinToggle.cogc
The machine codes generated when this file is compiled will be copied to
Cog RAM and executed from there.
*/
extern unsigned int _load_start_pinToggle_cog[];
const unsigned int *pinToggle_cogc = _load_start_pinToggle_cog;
#include <propeller.h> // Header with I/O & timing defs
#include "pinToggle.h" // Header with pinToggle struct
__attribute__((naked)) // Never returns
void main(pinToggle_t *share) // COGC main function
{
int pmask = 1 << share->pin; // Set up pin mask
DIRA |= pmask; // Pin to output
int t = CNT; // Capture current time
while(1) // Main loop in cog
{
(share->n)++; // Keep a running count
OUTA ^= pmask; // Toggle output
waitcnt(t+=share- = 26; // Set pin to P26
pinToggle.dt = CLKFREQ/10; // Set toggle interval
pinToggle.n = 0; // Initialize n to 0
// Launch COGC code into another cog.
extern unsigned int *pinToggle_cogc;
int cog = cognew(pinToggle_cogc, &pinToggle) + 1;
pinToggle_t pinToggle2; // Declare pinToggle type (structure)
pinToggle2.pin = 27; // Set pin to P27
pinToggle2.dt = CLKFREQ/13; // Set toggle interval
pinToggle2.n = 0; // Initialize n to 0
// Launch COGC code into another cog.
int cog2 = cognew(pinToggle_cogc, &pinToggle2) + 1;
int dtm = CLKFREQ; // Time increment for main
int t = CNT; // Capture current tick count
for(int i = 1; i <= 7; i++) // Main loop
{
PHSA = 1; // Clear phase accumulator
waitcnt(t += dtm); // Wait 1 s
print("n = %d\n", pinToggle.n); // Display n
}
cogstop(cog - 1); // Stop first light
pinToggle2.dt = CLKFREQ; // Change P27 rate
print("n2 = %d\n", pinToggle2.n); // Display n2
pause(4000); // Wait 4 seconds
print("n2 = %d\n", pinToggle2.n); // Display n2
cogstop(cog2 - 1); // Stop second light
}
Advanced Topic - Increase Function Execution Speed with _FCACHE
Here is an example with function code that gets copied unused space in a cog. This reduces the access time for data because the kernel executing the machine codes looks inside its own cog RAM for the next instruction instead of having to wait for the next access window to get the instruction from Main RAM, which is shared with 7 other cogs.
Run the program as-is, and note the cycles per second that P5 toggles at is about 83 kHz. Then, un-comment the __attribute__((fcache)) line, and re-run the program. The toggle rate should increase to about 2.5 MHz. That's about a 30x speed increase and also lends itself to precisely timed loops. You can also un-comment n++ in the pinToggle function to share counted repetitions with the main function. Without fcache, the frequency is about 48 kHz. With fcache, it's about 828 kHz. Since there is now some communication with Main RAM that slows loop execution, so there is only a 17x speed increase. ...but hey, that's still 17x!
According to ersmith in the How can I get most out of Fcache thread, functions can have the fcache attribute applied to them for improved performance if the function is small enough to fit in a cog along with the kernel for the memory model. The allowable size of the code varies from one memory model to the next. If the function is too large, you will see a compiler error. fcached functions are also severely restricted on the functions they can call; they can only call NATIVE functions. You can add a native function by adding __attribute__((native)) or _NATIVE.
Both fcached and native functions have to reside in the Cog RAM. This means, you cannot use many cmm/lmm/xmm library functions. For example, simpletools library functions like high, low and pause are not native. The propeller.h library has macros like OUTA, DIRA, and waitcnt that can be used to get the same functionality. So, instead of high(5), use OUTA |= 5 and DIRA |= 5. Instead of pause(100), use waitcnt(CNT + CLKFREQ/10).
How it Works
This application measures the number of times the while(1) loop in the pinToggle function repeats by measuring the number of low-to-high transitions on P5. By commenting and commenting different parts of the example, you can measure different execution rates. Keep in mind that the actual repeat rate is twice that fast because the pinToggle function's loop performs a low-to-high transition on one repetition, and a high-to-low transition on the next.
The simpletools library has some has some convenience functions used by main.
Each Propeller cog has CTRA and CTRB modules that can be configured to perform certain processes independently. One of the features is positive edge detection. In this mode, a counter module adds 1 to its corresponding PHSA/PHSB register every time a low-to-high transition is detected on a certain I/O pin. This macro definition is a value that can be ORed with an I/O pin number and then stored in the cog's CTRA or CTRB register to provide edge counting for measuring signal frequencies.
This is a function prototype for the pinToggle function. This function is designed to be launched into another cog. The actual function is below main.
These volatile variables are going to be modified/accessed by more than one function running in more than one cog. The volatile declaration ensures that the compiler doesn't optimize out code that re-checks its value before performing each operation. This could happen if one function is modifying the variable from another cog because the compiler cannot figure that out, so volatile just prevents it from ever happening.
Compact memory model (CMM) code running in another cog needs 176 bytes (44 ints) of stack space for the C kernel, and often additional stack space for function call/return and, local variables, and etc. I'm not sure if an fcached cog really needs any stack space, so this line is just out of habit at this point.
This main function is running in cmm mode. In this mode, the C kernel runs in a cog and it fetches and executes machine stored in the Propeller chip's Main RAM.
{
Pin is one of the volatile variables shared by main and pinToggle. Main has to set it before starting pinToggle in another cog because pinToggle uses pin to determine which pin to toggle.
The pinToggle function also has commented code to keep the I/O pin on/off for a certain number of clock ticks. If statements with dt are un-commented in pinToggle, this also needs to be un-commented.
This starts the pinToggle function in another cog. For more info on this, see Multicore Example.
__ stack, sizeof(stack));
As mentioned earlier, POS_EDGE_CTR was defined so that it could be ORed with a pin number to configure a counter module. Here, the cog that's executing the main function gets its counter module A configured to count low-to-high transitions on P5.
The rule for counting positive transitions counter module A is that the value in the FRQA register gets added to PHSA every time a positive transition is detected. So, we'll set FRQA to 1, so that PHSA increases by 1 with each transition.
These two variables are created for setting up a loop that repeats at precise time intervals. The first one establishes the time interval by setting dtm (time increment for main) to CLKFREQ, the number of system clock ticks in a second. The second marks the current number of clock ticks that have elapsed (CNT) by storing a copy of that value in t. Every time the Propeller chip's system clock ticks, the CNT register increases by 1. In this application, the system clock is running at 80 MHz. So, the value of CNT increases by 80,000,000 each second.
__ int t = CNT;
The main loop starts by setting PHSA to 0. Then, wiatcnt(t += dtm) adds the number of clock ticks in 1 second to the system clock time that was previously stored in t. That sets a target CNT register value for the waitcnt function to wait for. It's more precise than the simpletools library's pause function. The waitcnt function allows the program to continue after 1 second, at which point, int cycles = PHSA captures the number of low-to-high transitions that have occurred on P5. Then, two print function calls display that value along with the value of n. The value of n might or might not increase depending on whether or not n++ has been un-commented in pinToggle.
__{
____PHSA = 0;
____waitcnt(t += dtm);
____int cycles = PHSA;
____print("n = %d, ", n);
____print("cycles = %d\n", cycles);
__}
}
The pinToggle function uses only built-in propeller.h macros for I/O pin manipulations, which allows it to be labeled with the fcache attribute so that it can be copied into the portion of Cog RAM not used by the C kernel. This greatly increases execution speed because the program does not have to wait for Main RAM access, which is shared with 7 other cogs, to get the next instruction. Local variables also have faster access because they are stored in Cog RAM as well. Global variables are stored in Main RAM, and when fast execution speed is the goal, they should be used sparingly.
IMPORTANT: You won't see the speed increase until you un-comment the __attribute__((fcache)) statement.
void pinToggle(void *par) // pinToggle function
{
__ int pmask = 1 << pin;
__ DIRA |= pmask;
__ //int t = CNT;
__ while(1)
__ {
____ //n++;
____ OUTA ^= pmask;
____ //waitcnt(t+=dt);
__ }
}
Here is a COGC application that does the same thing as the fcache application from the previous post. One important difference is that the COGC kernel is smaller than a CMM or other memory models, which means your application can fit more code into the cog.
The shared variables from the previous post were modified and moved into a header file. The fcached function was also modified so that it could be run from a COGC file. So what's left in the main file is just code that launches the COGC cog and tests it.
Did You Know?
First, follow the checklist instructions for the creating a project and adding the three files below to it. Then continue to the Test Instructions.
A header file with shared variables provides a convenient place where code in both files can access them.
If the COGC code is going to be part of an application running in a different mode, like CMM, LMM or XMM, it needs to live in its own COGC file that's part of the project.
Test Instructions
Now you are ready to run the application.
Let's try modifying the main file to set up two light blinking processes on P26 and P27.
Thanks for the really quick and detailed example on fcache. :)
A working code example has been added to the COGC project in post #3. Next step is to write a narrative of what's happening in the code.
Thanks for this second tutorial too.
They are very valuable to me and I think for others who are looking for advanced stuff as well.
Daniel
PropWare: C++ HAL (Hardware Abstraction Layer) for PropGCC; Robust build system using CMake; Integrated Simple Library, libpropeller, and libPropelleruino (Arduino port); Instructions for Eclipse and JetBrain's CLion; Example projects; Doxygen documentation
Attached here is the intro to the C section.
You can buy the book on leanpub (you can download a sample to give you an idea of the things I cover)
Propeller Programming
Leanpub has a 45 day return policy.
Best,
Sridhar | http://forums.parallax.com/discussion/160301/mixed-mode-programming-tutorial | CC-MAIN-2017-34 | refinedweb | 2,273 | 61.16 |
Fun with the iRobot Create
Very little in the Linux universe interacts directly with the physical world. Although you may have peripherals that allow you to work with the computer, the computer has no way to interact with you. This is easily solvable by creating a robot for it to control. iRobot, famous for its Roombas, has created an educational robot called the iRobot Create, based on the Roomba, that is incredibly easy to work with. The Create provides a simple base to extend upon with very little effort. Some people even have mounted an old laptop to the robot to allow mobility, but that is overkill for most situations. It's not hard to create a link between a Linux box and the Create, even though it lacks official support.
The easiest way to interact with the Create is through a serial link using the cable that comes with the robot. For some computers, you may need a USB-to-serial adapter; however, they are readily available for less than $15. The connection will be a TTY serial, such as /dev/ttyS0, or if you are using a USB adapter, the connection most likely will show up as /dev/ttyUSB0.
In order to pass commands back and forth though the serial cable, the easiest tool to use is a serial port terminal. There are several versions of this type of software available. Here, I use gtkterm, a GUI terminal, but if you prefer CLI tools, both screen and minicom will work. After installing and launching gtkterm, you have to set the correct port under Configuration→Port. The port will be the device specified earlier, and if you are unsure which number to choose, you may have to try them all. The speed should be set to 57600 (baud). The other default settings (No parity, 8-bit, 1 stopbit and no flow control) are fine. I also prefer to turn on Local echo, which also is under Configuration and lets you see what you type.
To test the configuration, plug in the Create to charge and connect it to your computer. The terminal should start displaying lines such as the following every second:
bat: min 0 sec 11 mV 16699 mA 566 deg-C 21
Unless you plan on mounting a computer to the robot itself, the serial cable will prove cumbersome as soon as the robot begins to move. To get around this, the robot needs to go wireless. Although 802.11 Wi-Fi has become ubiquitous on laptops, it is not common on embedded systems like the Create. Another candidate is Bluetooth, which also is becoming widespread; however, Bluetooth modules generally are expensive, have hit-or-miss Linux support and are very short-ranged. Recently, Maxstream's line of XBee radios have been gaining popularity in projects like this. They are very similar to Bluetooth modems and are better suited for this type of project.
All of the parts for this project can be purchased at SparkFun and are listed in Table 1. In addition to these items, you also will need some basic tools and supplies, such as a breadboard, wire and a soldering iron.
First, you need to configure your two XBee modules. To start, plug one of them in to the USB XBee explorer and connect it to your computer via USB cable (the USB XBee explorer is simply a serial-to-USB converter board that accepts an XBee module). Using gtkterm again, set it up to listen on a USB port (most likely /dev/ttyUSB0), and set the speed to 9600 baud. Type into the terminal +++, and the module should reply OK.
The module now is ready to be configured. Type in ATID3330,DH0,DL1,MY0,BD6,WR,CN, and after each comma, the module will reply with OK. Remove this XBee, and insert the other one. Again, type +++, and wait for the OK to enter into configuration mode. This time, however, configure it with ATID3330,DH0,DL0,MY1,BD6,WR,CN. Each module is configured to be on network 0x3330 and to send data directly to the other at 57600 baud. One module is connected to the computer, and the other to the Create. The modules are interchangeable—either one can be connected to the computer or the Create.
Next, build the circuit to connect the XBee with the Create serially. This circuit connects the 3.3-volt XBee to the 5-volt Create. To start, solder the two sockets into the XBee breakout board. The easiest way to do this is to place the sockets on the XBee module itself, flip it over, and place the breakout board on top.
After the sockets are soldered, remove the module and solder four wires to VCC, DOUT, DIN and GND. After that, solder four more wires to the male DB-25 connector on pins 1, 2, 8 and 21. The pins should be labeled, although the markings are faint. Next, break off two six-pin lengths from the strip of male header pins, and solder them to each side of the level converter. Again, it is easiest if you use the breadboard as a jig to hold the pins straight as you solder them. Finally, assemble everything according to the schematic (Figure 2) and/or the breadboard wiring diagram (Figure 3). The completed breadboard is shown in Figures 4 and 5.
Figure 2. Schematic for the XBee/Create Interface
Plug the DB-25 connector in to the Create's expansion port, and remove the command module if present. With the other XBee plugged in to your computer, set up gtkterm to communicate with it at 57600 baud. As before, plug the Create in to charge, and with luck, you will see some output on the terminal, and the RX light on the USB explorer should blink. If not, check your connections and configuration.
Even if you did not decide to go wireless, you still can control the Create in exactly the same way. The Create, and most Roombas, implement the iRobot Open Interface protocol, or OI for short. On the computer side, let's use Python to communicate with the Create using iRobot's implementation of OI in Python. This allows you to work on a higher level and not worry about opcodes and such. You will need pySerial and openinterface.py (see Resources). There is a small bug in openinterface.py that can make it difficult to work with on Linux. The simplest way to solve this is to run this sed command in the same directory as the file:
$ sed -ie "803s/ - 1//" openinterface.py
Alternatively, you can remove - 1 manually from line 803.
The library is easy to use—for example, to drive the Create forward at full speed, do this:
import openinterface as oi PORT = "/dev/ttyUSB0" # change to your serial port bot = oi.CreateBot(com_port=PORT,mode="full") bot.drive_straight(500) # drive forward, full speed
In order to access sensor data, you need to request it. If you use bot.stream_sensors(), the Create will update the specified sensors in each argument automatically every 15 milliseconds. To stop, execute bot.stop_streaming_sensors(). Although you can specify manually which sensors you want to stream, it generally is easiest just to stream all of them.
Driving also is pretty simple. bot.drive() takes two arguments: speed and turning radius. Speed is an integer between 500 and –500, specifying the average speed of the wheels in millimeters per second, with negative values corresponding to going backward. Turning radius is a number between 200 and –200, specifying the radius of a turn in millimeters. Positive values turn left, and negative values turn right. There also are special methods that can be used for going straight and turning in place.
The following code uses sensor data to drive and maneuver around obstacles:
bot.stream_sensors(6) # packet 6 -- all sensors while True: # loop forever if bot.sensors["bump-left?"]: # is it pressed? bot.drive(-500, 10) # spin to maneuverer bot.wait(5) # spin for 5 cycles elif bot.sensors["bump-right?"]: # other direction bot.drive(500, 10) bot.wait(5) else: bot.drive_straight(500) # otherwise, go forward bot.wait() # prevents excess cycling
You can access the Create's song-playing abilities very easily too, and you can store songs in the 17 available song slots. Use bot.define_song() to store a song. The first argument is the song slot where the song will be stored, and you also use this value later to play the song back. The rest of the arguments are notes, represented by tuples of pitch and length. Length is measured in 64ths of a second. Call bot.play_song() to play the song. I'm no musical genius, so hopefully you can write a better tune:
bot.define_song(1, # index of song ("G1", 16), # note tuples ("G2", 16), # note, duration ("G3", 64), # 64 = 1 second ("G9", 16)) # up to 100 notes # ...snip... bot.play_song(1)
To control the Create wirelessly with a joystick and Python, we can use pygame (the full details of the pygame joystick API are beyond the scope of the article; check the documentation for more information):
import pygame from pygame import locals pygame.init() js = pygame.joystick.Joystick(0) # create joystick js.init() import openinterface as oi PORT = "/dev/ttyUSB0" # change to your serial port bot = oi.CreateBot(com_port=PORT,mode="full") while True: if js.getAxis(0) > 0: turn = 1 - js.getAxis(0) else: turn = -(1 + js.getAxis(0)) bot.drive(js.getAxis(1)*500, turn*200) bot.wait()
This code allows you to use a joystick (autodetected) to have primitive control over the Create. The x-axis value has to be manipulated so that when in a neutral position, the robot moves straight and does not spin.
Where to go from here? That's up to you. On the hardware side, you can attach additional hardware to the Create and control it through its digital inputs and outputs (see OI specifications for pin-outs). However, with just the base and some software, there still are tons of possibilities. For example, you could turn the Create into an alarm clock reminiscent of Clocky, the clock that drives around the room forcing you to get out of bed to shut it off. Or, if you are more mathematically inclined, you could use the the “distance” and “angle” sensors to map out a
FYI, this software API,
FYI, this software API, Distributed Control Framework, can play various tunes for the iRobot Create. Check it out.
ZACH BANKS IS AWESOME! AND
ZACH BANKS IS AWESOME! AND SOOOOOO SMART | http://www.linuxjournal.com/magazine/fun-irobot-create | CC-MAIN-2015-40 | refinedweb | 1,766 | 65.22 |
.
:
Array
Array( )
//.
push( )
unshift( )
You append elements to the end of an existing array using the Array.push( ) method, passing it one or more values to be appended:
Array.push( ):
length
.length:
undefined
letters
["a", "b", "c", undefined, undefined, "f"].
Array.pop( )
Recipe 5.2
You want to access each element of an array in sequential order.
Use a for loop that increments an index variable from 0 until it reaches Array. length. Use the index to access each element in turn.
for.
Alternatively, you can use a for statement that loops backward from Array. length -1 to 0, decrementing by one each time. Looping backward is useful when you want to find the last matching element rather than the first (see Recipe 5.3), for example:
var letters:Array = ["a", "b", "c"];
for (var i:int = letters.length - 1; i >= 0; i--){
// Display the elements in reverse order.
trace("Element " + i + ": " + letters[i]);
}
There are many instances when you might want to loop through all the elements of an array. For example, by looping through an array containing references to sprites, you can perform a particular action on each of the sprites:
for (var i:int = 0; i < sprites.length; i++){
// Move each sprite one pixel to the right.
sprites[i].x++;
}
You can store the array's length in a variable rather than computing it during each loop iteration. For example:
var length:int = sprites.length;
for (var i:int = 0; i < length; i++){
// Move each sprite one pixel to the right.
sprites[i].x++;
}
The effect is that there is a very marginal performance improvement because Flash doesn't have to calculate the length during each iteration. However, it assumes that you are not adding or removing elements during the loop. Adding or removing elements changes the length property. In such a case, it is better to calculate the length of the array with each iteration.
Recipe 12.8 for ways to loop through characters in a string. Recipe 5.16 for details on enumerating elements of an associative array. See also Recipe 5.3.
You want to find the first element in an array that matches a specified value.
Use a for statement to loop through an array and a break statement once a match has been found. Optionally, use the ArrayUtilities.findMatchIndex( ), ArrayUtilities.findLastMatchIndex( ), and/or ArrayUtilities.findMatchIndices( ) methods.
break
ArrayUtilities.findMatchIndex( )
ArrayUtilities.findLastMatchIndex( )
ArrayUtilities.findMatchIndices( )
When you search for the first element in an array that matches a specified value, you should use a for statement, as shown in Recipe 5.2, and add a break statement to exit the loop once the match has been found.
Using a break statement within a for statement causes the loop to exit once it is encountered. You should place the break statement within an if statement so it is executed only when a certain condition is met.
if
When searching for the first matching element, the importance of the break statement is twofold. First, you don't need to loop through the remaining elements of an array once the match has been found; that would waste processing time. In the following example, the break statement exits the loop after the second iteration, saving six more needless iterations. (Imagine the savings if there were a thousand more elements!)
Furthermore, the break statement is vital when searching for the first match because it ensures that only the first element is matched and that subsequent matches are ignored. If the break statement is omitted in the following example--all matching elements are displayed, as opposed to the first one only.
// Create an array with eight elements.
var letters:Array = ["a", "b", "c", "d", "a", "b", "c", "d"];
// Specify what we want to search for.
var match:String = "b";
// Use a for statement to loop through, potentially,
// all the elements of the array.
for (var i:int = 0; i < letters.length; i++) {
// Check whether the current element matches
// the search value.
if (letters[i] == match) {
// Do something with the matching element.
// In this example, display a message
// for testing purposes.
trace("Element with index " + i +
" found to match " + match);
// Include a break statement to exit the for loop
// once a match has been found.
break;
}
}
You can also search for the last matching element of an array by reversing the order in which the for statement loops through the array. Initialize the index variable to Array .length -1 and loop until it reaches 0 by decrementing the index variable, as follows.
-1
var letters:Array = ["a", "b", "c", "d", "a", "b", "c", "d"];
var match:String = "b";
// Loop backward through the array. In this example,
// the "b" is at index 5.
for (var i:int = letters.length - 1; i >= 0; i--) {
if (letters[i] == match) {
trace("Element with index " + i +
" found to match " + match);
break;
}
}
To simplify the process of searching for matching elements, you can use some of the static methods of the custom ArrayUtilities class. The class is in the ascb.util package, so the first step is to import the class:
ArrayUtilities
ascb.util
import ascb.util.ArrayUtilities;
The ArrayUtilities class has three methods for finding matching elements-- findMatchIndex( ), findLastMatchIndex( ), and findMatchIndices( ). The findMatchIndex( ) method requires at least two parameters: a reference to the array you are searching, and the value you want to match. The method then returns either the index of the first matching element or -1 if no matches are found; for example:
var letters:Array = ["a", "b", "c", "d"];
trace(ArrayUtilities.findMatchIndex(letters, "b"));
// Displays: 1
trace(ArrayUtilities.findMatchIndex(letters, "r"));
// Displays: -1
You can also specify the starting index from which the search begins. That way, you can find matches subsequent to the first match. Specify the starting index as the third parameter; for example:
var letters:Array = ["a", "b", "c", "d", "a", "b", "c", "d"];
trace(ArrayUtilities.findMatchIndex(letters, "a", 1));
// Displays: 4
You can tell the method to find elements that are partial matches as well. By default, only exact matches are found. However, if you specify a value of true for the third parameter, the method finds any element containing the substring:
true
var words:Array = ["bicycle", "baseball", "mat", "board"];
trace(ArrayUtilities.findMatchIndex(words, "s", true));
// Displays: 1
If you want to run a partial match and still specify a starting index, simply pass the starting index as the fourth parameter.
The findLastMatchIndex( ) method works identically to findMatchIndex( ) except that it starts looking from the end of the array.
The findMatchIndices( ) method returns an array of indices for all elements that match the value passed in. The method requires at least two parameters--the array and the element you want to match. For example:
var letters:Array = ["a", "b", "c", "d", "a", "b", "c", "d"];
trace(ArrayUtilities.findMatchIndices(letters, "b"));
// Displays: 1,5
You can also run partial matches using findMatchIndices( ). Simply specify a Boolean value of true as the third parameter:
var words:Array = ["bicycle", "baseball", "mat", "board"];
trace(ArrayUtilities.findMatchIndices(words, "b", true));
// Displays: 0,1,3
Each of the ArrayUtilities methods described use the same basic techniques with a for statement. Let's take a look at the code for the methods. The findMatchIndex( ) method is fairly straightforward, and you can see the comments inline. One thing to note, however, is that the method doesn't use any break statements within the for loop. That's because it uses return statements if a match is found. In the context of a function or method, a return statement exits the for statement, so the break statement is not necessary:
public static function findMatchIndex(array:Array, element:Object):int {
// Use a variable to determine the index
// from which to start. Use a default value of 0.
var startingIndex:int = 0;
// By default don't allow a partial match.
var partialMatch:Boolean = false;
// If the third parameter is a number,
// assign it to nStartingIndex.
// Otherwise, if the fourth parameter is a number,
// assign it to nStartingIndex instead.
if(typeof arguments[2] == "number") {
startingIndex = arguments[2];
}
else if(typeof arguments[3] == "number") {
startingIndex = arguments[3];
}
// If the third parameter is a Boolean value,
// assign it to partialMatch.
if(typeof arguments[2] == "boolean") {
partialMatch = arguments[2];
}
// Assume no match is found.
var match:Boolean = false;
// Loop through each of the elements of the array
// starting at the specified starting index.
for(var i:int = startingIndex;
i < array.length; i++) {
// Check to see if the element either matches
// or partially matches.
if(partialMatch) {
match = (array[i].indexOf(element) != -1);
}
else {
match = (array[i] == element);
}
// If the element matches, return the index.
if(match) {
return i;
}
}
// The following return statement is only reached
// if no match was found. In that case, return -1.
return -1;
}
The findLastMatchIndex( ) method is almost identical to the findMatchIndex( ) method, except that it loops in reverse. The findMatchedIndices( ) method loops through the array to find every matching index. It appends each matching index to an array, and then it returns that array. It uses the findMatchIndex( ) method, as shown here:
public static function findMatchIndices(array:Array,
element:Object, partialMatch:Boolean = false):Array {
var indices:Array = new Array( );
var index:int = findMatchIndex(array,
element,
partialMatch);
while(index != -1) {
indices.push(index);
index = findMatchIndex(array,
element,
partialMatch,
index + 1);
}
return indices;
}
Recipes 5.2 and 5.10
Pages: 1, 2, 3, 4
Next Page
© 2015, O’Reilly Media, Inc.
(707) 827-7019
(800) 889-8969
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners. | http://archive.oreilly.com/pub/a/actionscript/excerpts/as3-cookbook/chapter-5.html | CC-MAIN-2015-40 | refinedweb | 1,581 | 56.96 |
sasl_errstring man page
sasl_errstring — Translate a SASL return code to a human-readable form
Synopsis
#include <sasl/sasl.h> const char * sasl_errstringbledygook). Note that a server should call sasl_usererr on a return code first if the string is going to be sent to the client.
saslerr specifies the error number to convert.
langlist is currently unused; Use NULL.
outlang specifies the desired RFC 1766 language for output. NULL defaults to "en-us," currently the only supported language.
It should be noted that this function is not the recommended means of extracting error code information from SASL, instead application should use sasl_errdetail(3), which contains this information (and more)
Return Value
Returns the string. If langlist is NULL, US-ASCII is used.
Conforming to
RFC 4422
See Also
sasl(3), sasl_errdetail(3), sasl_errors(3)
Referenced By
sasl(3). | https://www.mankier.com/3/sasl_errstring | CC-MAIN-2017-17 | refinedweb | 137 | 58.58 |
Unity 2019.4.30_Release Notes (.PDF)
릴리스 정보
Known Issues in 2019.4.30f1
Ads: [Android] Unity Ad return app to Lock screen (1281041)
Animation: Inspector not displaying state and transition properties once duplicated (1251586)
Asset Import Pipeline: Editor crashes with out of memory while importing a lot of assets (mostly textures) at once, on Windows/DX11 (13245: ): Crash on mono_thread_get_undeniable_exception (1308625): Performance degradation when activating or deactivating uGUI GameObject (1348763)
Shadows/Lights: Crash on ProgressiveRuntimeManager::GetGBufferChartTexture when entering UV Charts mode before baking lights (1309632)
Terrain: Terrain Lit Opacity as Density option causes alpha'd areas on the 5th layer or greater to appear with artifacts (1283124)
WebGL: [iOS] Video is not playing (1288692)
2019.4.30f1 Release Notes
Features
- Version Control: Added auto sign in when logged into Unity account.
Burst: Update Burst package to 1.4.11. Please refere to the package change log online here:
Package: Update Addressables to 1.18.9. Please refer to the package changelog online here:
Package: Update Scriptable Build Pipeline to 1.19.0. Please refer to the package changelog online here:
Package Manager: Removed confusing function call traces from
upm.logfile. (1331947)
Package Manager: The Package Manager's global cache root folder, which is used to store downloaded packages, can now be configured using the
UPM_CACHE_ROOTenvironment variable or the
cacheRootkey in the user configuration file.
Particles: Optimize Mesh data stripping vertex channels that are used by particle systems when the mesh is included in assetbundles. (1313420)
Version Control: Added Checkin and Update confirmation notification
Version Control: Improved load time performance.
Web: Updated UnityWebRequest's libCurl backend (used on most platforms)
WebGL: Improved error messages that are printed when a build to WebGL fails. (1245847)
API Changes
- Services: Added: Added new com.unity.services.core package that is used for common behaviour of Game Service packages
Changes
Shaders: Shaders that specify package requirements will no longer produce a parsing error.
Version Control: Simplified and decluttered UI.
XR: The Oculus XR Plugin package has been updated to 1.10.0. Please refer to the package changelog online here:
XR: Updated XR Legacy Input Helpers to 2.1.8. Please refer to the package changelog online here:
Fixes
2D: Fixed a crash on Tilemap::SetEditorPreviewTileAsset when trying to painting on an invalid Tilemap component. (1220442)
2D: Fixed an issue where SystemInfo.deviceUniqueIdentifier wa not actually being unique on some Windows 7 machines.
2D: Fixed an issue where user was unable to remove Empty Category in Sprite Editor after changing Sprite Layer name with external image editor. (1328475)
AI: Fixed a crash caused by the NavMesh builder code in very rare and specific configurations of the world geometry. (1329346)
AI: Fixed a rare crash that happened when an OffMeshLink on the path of the NavMeshAgent was disconnected due to modifications to the underlying NavMesh. (1298211)
AI: Fixed an issue where OffMeshLink and NavMeshLink sometimes were not automatically reconnecting after navigation mesh carving. (1287238)
Android: Fixed a crash caused by an uncaught "java.lang.IllegalStateException: The specified child already had a parent" that mainly affects Android 7.x. (1347211)
Android: Fixed a long startup on Mali GPUs)
Android: Fixed an isseu where Android build when streaming asset had quote in it's name. (1281934)
Android: Fixed an issue where all microphones were reporting the same recording state when bluetooth microphone was connected. (1298249)
Android: Fixed an issue where selection highlight appeared above keyboard when "Hide Mobile Input" was enabled. (1313620)
Android: Fixed an issue where there was an unresponsive area just above keyboard when "Hide mobile input" was checked. (1305663)
Android: Fixed an severe disk I/O regression issue on Android 5.0.x. (1287681)
Asset Pipeline: Fixed an issue for loaded native assets that got unnecessarily reloaded after a domain reload. (1323425)
Asset Pipeline: Fixed an issue where asset hot-reloading could take place, even when no assets had changed. (1335843)
Asset Pipeline: Fixed an issue where duplicating folders and assets would not invokes OnWillCreateAsset callbacks on the duplicated items. (949423)
Editor: Fixed a Linux editor EndLayoutGroup console error when clicking on Material shader dropdown. (1287721)
Editor: Fixed a Linux editor GTK timeout error when opening tooltips. (1279878)
Editor: Fixed a slow Editor startup times when ShaderCache/EditorEncounteredVariants had grown too large. (1330453)
Editor: Fixed an ArgumentException in the Linux editor when a tab was detached from the primary window.
Editor: Fixed an issue when Unity editor was in lower display scaling would not remain maximized on Windows. (1283299)
Editor: Fixed an issue where a maximized instance of Unity on a second, lower resolution display would not remain maximized on that display when the Editor was restarted on Windows. (1314966)
Editor: Fixed an issue where ScreenCapture.CaptureScreenshot in the Editor did not works as expected on Vulkan Graphics API. (1338579)
Editor: Fixed an issue where tablet users had trouble using scrollbars because the splitter gets in the way, since the picking zones were increased for touch (tablet + finger).
The behavior is reverted. (1240329)
Editor: Fixed an issue where the Linux editor player settings window was spamming console with error messages. (1291443)
Editor: Fixed an issue where there was no basic system information logged when launching the Editor to the log file on macOS or Linux. (1325370)
Editor: Fixed mouse hide issue in windows editor playmode. (1273522)
Game Core: Fixed a crash caused by invalid data in resource versioning. (1339469)
GI: Fixed a crash when baking with Enlighten on a system with more than 64 threads. (1229259)
GI: Fixed an issue when TempBuffer<RenderTexture> was not released in memory when using deprecated Realtime Global Illumination. (1206727)
GI: Fixed an issue where Light Probe Proxy Volumes on Automatic mode were not being updated, when baked probe coefficients were changed in the editor while in play mode. (1265289)
GI: Fixed an issue where there was no Gizmo for the Disc Light. (1273193)
Graphics: Fixed a crash with accessing individual pixels on crunch compressed texture. This should now throw an error instead. (1314831)
Graphics: Fixed a rare async texture uploading deadlock when synchronously blocking. (1353805)
Graphics: Fixed an issue when dynamic scaling was enabled and a Render Target was attached to a Camera the ScreenTo and ToScreen functions would no longer use the scaled viewport size, instead match the behaviour when a Render Target wat not attached as per the documentation. (1329240)
Graphics: Fixed an issue where Encoding RFloat and RHalf to PNG, JPG or TGA would not encode to a grayscale image. (1325643)
Graphics: Fixed an issue where MeshRenderer would render a mesh when the MeshFilter had been removed while editing the prefab in context. (1251154)
Graphics: Fixed an occasional error message if getting trail positions from script. (1335899)
Graphics: Fixed hue variation color selector issue for speedtree7 materials. (1326227)
Graphics: Fixed inconsistencyissue in anisotropic level setting across temporary RenderTextures. (1319319)
IL2CPP: Fixed a crash in the runtime when a managed thread object had been destroyed was used from a finalizer. (1341024)
IL2CPP: Fixed an issue where a required System.Uri constructor was being stripped in Medium or High stripping modes. (1338763)
IL2CPP: Fixed an issue where an embedded resources was not loaded on an assembly processed with ILRepack. (1323772)
IL2CPP: Fixed an issue where unaligned reads and writes which occur in the System.Runtime.CompilerServices.Unsafe.dll assembly (among others) on ARMv7 where not handled properly. (1343375)
IL2CPP: Fxed a crash when calling DynamicInvoke on delegate returned from Marshal.GetDelegateForFunctionPointer(). (1335306)
iOS: Fixed 'end Encoding' crash when force closing iOS application. (1329593)
iOS: Fixed a crash when using several Application.RequestUserAuthorization in coroutine. (1323715)
iOS: Fixed a query of Display native resolution issue. (1342424)
iOS: Fixed an issue where Mute Other Audio Sources was not muting background audio on a device when toggled on when Unity audio was enabled. (1335093)
iOS: Fixed an issue where the password input cleared on first character when touch keyboard input was hidden. (1251498)
macOS: Fixed an issue where the usage description fields for macOS in player settings were not visible on Windows and Linux editors. (1323741)
macOS: Fixed Windows and Linux native plugins that were getting included into the generated Xcode project. (1321049)
Networking: Fixed an issue where UnityWebRequest did not supports gzip compression on Windows. (1343274)
Nintendo Switch: Fixed a shader precision issue that could cause artifacts in Terrain rendering. (1345800)
Package Manager: Fixed an issue where removing a project dependency using
PackageManager.Client.Removewould throw an error when the project manifest has no dependencies property. (1324067)
Particles: Fixed a fog issue in all blend modes of the Standard Unlit shader. (1297332)
Particles: Fixed an occasional error message and invalid bounding box, when using the Collision Module in Planes mode. (1282268)
Physics: Fixed a crash in "PhysicsScene2D::UpdateJoints()". (1342152)
Prefabs: Fixed an issue where the use could not move/rotate/scale static objects in Prefab Mode when playing. (1343040)
Profiler: Fixed an issue where the Profiler was showing metadata for sliced samples only in the first frame. (1133819)
Project Browser: Fixed an issue where the folder icon never changed back to empty icon when the folder was expanded in Project Browser when the last item was removed. (1330467)
PS5: Fixed a crash that can occur in ReadbackImage with a R8 texture format. (1348451)
Scripting: Fixed a crash when closing the editor after a failed AssetBundle.LoadFromStreamAsync operation. (1331280)
Scripting: Fixed an issue where globalgamemanagers.assets to contain scripts that will be part of the player builds. (1335997)
Serialization: Fixed the issue where Editor freezes when clicking on Presets while being in a Project settings subwindow. (1334751)
Shaders: Fixed a crash when attempting to use a compute buffer created with 0 length.
Shaders: Fixed an issue where the Properties section could not be folded in the Shader Inspector. (1350236)
Shaders: Fixed incorrect memory attribution in the profiler for shader variants. (1328654)
UI Toolkit: Fixed a corruption of the stencil buffer issue caused by misplaced geometry used to pop masks. (1332741)
UI Toolkit: Fixed a read only fields mouse dragger issue. (1337002)
UI Toolkit: Fixed an issue were there was a wrong addressing of dynamic transforms when new atlas slot was used. (1293058)
UI Toolkit: Fixed an issue where the disabled state did not properly showing after a hierarchical changes were applied. (1321042)
UI Toolkit: Fixed an issue with inspector fields failing to get focused when clicks depend on neighboring fields. (1335344)
Version Control: Fixed a SSO renew token issue after a password change.
Version Control: Fixed an issue where the contextual menu was not showing up in project view.
Version Control: Fixed an issue where view was not switching to workspace after creating an Enterprise Gluon workspace.
Version Control: Fixed some namespace collisions issue with Antlr3.
Video: Fixed an issue where Audio was delayed when pausing VideoPlayer. (1316817)
Video: Fixed an issue where a Video clip with unsupported audio track was not usable. (1327470)
Video: Fixed an issue where Audio did not play during VideoPlayer.Prepare. (1316819)
Video: Fixed an issue where Audio was desynchronized when playing via AudioSource. (1304061)
Video: Fixed an issue where the VideoPlayer was not working on some AMD switchable GPUs. (1237818)
Video: Fixed an issue where VideoPlayback was leaked if destroyed while seeking. (1308317)
WebGL: Fixed a WebAssembly trap when a touch point got canceled on mobile devices. (1262657)
Windows: Fixed an issue where Input System was failing to detect gamepad if it was connected during splash screen logos. (1328742)
Windows: Fixed an issue where object selector would not opens in between two windows in side-by-side multi-monitor setups. (1289440)
Windows: Fixed an issue where SystemInfo.deviceUniqueIdentifier was not actually being unique on some Windows 7 machines. (1339021)
Windows: Fixed an issue where the Input System failed to detect a touchscreen device connected after startup. (1305703)
Windows: Fixed an issue where the mouse deltas was always 0 when running Windows in a VM. (1303445)
Windows: Fixed an issue where Windows Standalone builds crashed when the window was resized on startup (for instance, when using -monitor command line argument to move the window to a display with different DPI settings). (1338515)
Windows: Fixed IME composition text duplicating between InputFields due to bugs in 3rd party Chinese IMEs. (977600)
XR: Fixed an issue where MTLCommandEncoder was nog available at frame submission time for display providers when in XR mode. (1329853)
XR: Fixed an issue where the Splash screen did not sends correct zNear and zFar values to XRDisplaySystem. (13498: e8c891080a1f | https://unity3d.com/kr/unity/whats-new/2019.4.30 | CC-MAIN-2022-05 | refinedweb | 2,065 | 54.32 |
Video descriptionThe quickest way to learn the basics of Python.
Massimo Perga, Microsoft
The Quick Python Book offers a clear, crisp introduction to the elegant Python programming language and its famously easy-to-read syntax. Made for programmers new to Python, this Python development landscape, including GUI programming, testing, database access, and web frameworks.
- Concepts and Python 3 features
- Regular expressions and testing
- Python tools
- All the Python you need—nothing you don't
This is my favorite Python book...a competent way into serious Python programming.
Edmon Begoli, Oak Ridge National Laboratory
Like Python itself, its emphasis is on readability and rapid development.
David McWhirter, Cranberryink
Python coders will love this nifty book.
Sumit Pal, Leapfrogrx
NARRATED BY MARK THOMAS
Table of contents
- PART 1 STARTING OUT
- PART 2 THE ESSENTIALS
- Chapter 4. The absolute basics
- Chapter 4. Numbers
- Chapter 5. Lists, tuples, and sets
- Chapter 5. Sorting lists
- Chapter 5. Tuples
- Chapter 6. Strings
- Chapter 6. String methods
- Chapter 6. Modifying strings
- Chapter 6. Converting from objects to strings
- Chapter 6. Formatting strings with %
- Chapter 7. Dictionaries
- Chapter 7. Word counting
- Chapter 8. Control flow
- Chapter 8. List and dictionary comprehensions
- Chapter 8. Boolean values and expressions
- Chapter 9. Functions
- Chapter 9. Local, nonlocal, and global variables
- Chapter 10. Modules and scoping rules
- Chapter 10. The module search path
- Chapter 10. Python scoping rules and namespaces
- Chapter 11. Python programs
- Chapter 11. Making a script directly executable on UNIX
- Chapter 11. Scripts on Windows vs. scripts on UNIX
- Chapter 11. Distributing Python applications
- Chapter 12. Using the filesystem
- Chapter 12. The current working directory
- Chapter 12. Getting information about files
- Chapter 13. Reading and writing files
- Chapter 13. Screen input/output and redirection
- Chapter 13. Pickling objects into files
- Chapter 14. Exceptions
- Chapter 14. Exceptions in Python
- Chapter 14. Debugging programs with the assert statement
- Chapter 15. Classes and object-oriented programming
- Chapter 15. Class variables
- Chapter 15. Inheritance
- Chapter 15. Using @property for more flexible instance variables
- Chapter 15. Destructors and memory management
- Chapter 16. Graphical user interfaces
- Chapter 16. Principles of Tkinter
- Chapter 16. Creating widgets
- Chapter 16. What else can Tkinter do?
- PART 3 ADVANCED LANGUAGE FEATURES
- Chapter 17. Regular expressions
- Chapter 17. Extracting matched text from strings
- Chapter 18. Packages
- Chapter 18. import statements within packages
- Chapter 19. Data types as objects
- Chapter 20. Advanced object-oriented features
- Chapter 20. Giving an object full list capability
- Chapter 20. Metaclasses
- PART 4 WHERE CAN YOU GO FROM HERE?
- Chapter 21. Testing your code made easy(-er)
- Chapter 21 Using unit tests to test everything, every time
- Chapter 22. Moving from Python 2 to Python 3
- Chapter 22. Using 2to3 to convert the code
- Chapter 23. Using Python libraries
- Chapter 23. Installing Python libraries using setup.py
- Chapter 24. Network, web, and database programming
- Chapter 24. Creating a Python web application
- Chapter 24. Sample project—creating a message wall
Product information
- Title: Quick Python, 2nd Ed, video edition
- Author(s):
- Release date: December 2009
- Publisher(s): Manning Publications
- ISBN: None
You might also like
video
Python Beyond The Basics - Object Oriented Programming
In this Python Beyond the Basics - Object-Oriented Programming training course, expert author David Blaikie will … Programming Language
6+ Hours of Video Instruction Python Programming Language LiveLessons provides developers with a guided tour of … | https://www.oreilly.com/library/view/quick-python-2nd/9781935182207VE/ | CC-MAIN-2022-40 | refinedweb | 550 | 55.1 |
My previous installation of CUDA on Ubuntu 14.04 was a bit frustrating due to the booting issue after installation. System would often be frozen and stuck on the Ubuntu logo while booting. Some say it was due to the driver issues.
And I have turned to windows and issues seemed solved. I basically followed this blog guide, but some steps were done differently.
OK, here are the steps:
1. Install Visual Studio (2013)
First you need to check the supported version of VC according to the CUDA version that you will be downloading. At my time, the latest supported VC was 2013, so it would NOT be supported if you had chosen to install VC 2015 for example.
After installation, add below two paths to your system PATH:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\;C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE
2. Install CUDA (7.5)
My version was 7.5, which is the latest version at my time. Installation should be quite simple.
3. Python and dependencies
Since I have Anaconda installed as my python, just type below commands to install additional dependencies:
conda install mingw libpython
4. Install Theano
I chose to install the bleeding-edge version from github. As for installation of other python packages, cd to anaconda/Lib/site-packages, and clone the package from github:
git clone
Then cd into the Theano folder and install:
cd Theano python setup.py develop
After installing theano, create a .theanorc.txt file in your HOME directory (somewhere like c:/Users/YOURNAME/), with following contents:
[global] floatX = float32 device = gpu [nvcc] flags=-LC:\SciSoft\Anaconda\libs compiler_bindir=C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin
Make sure
flags=-LC:\SciSoft\Anaconda\libs
goes to your correct Anaconda directory. (e.g. I installed Anaconda in HOME\SciSoft\Anaconda)
5. Install PyCUDA
Download the .whl file from here. My python was 2.7 so I downloaded the latest pycuda‑2015.1.3+cuda7518‑cp27‑none‑win_amd64.whl.
And installed it using
pip install pycuda‑2015.1.3+cuda7518‑cp27‑none‑win_amd64.whl
6. Testing Theano and PyCUDA
Theano with GPU:
Import theano should give you similar lines as below:
import theano Using gpu device 0: GeForce GT 705 (CNMeM is disabled)
And follows theano docs to test example snippet like below:')
PyCUDA:
And this should give a screen of zeros.
You are good to go!
7 thoughts on “Installing CUDA 7.5 and PyCUDA on windows (for testing theano with GPU)”
Thanks A lot Weimin Wang . Your Blog helped a lot.
Clear, concise, and it worked!
Thank you so much! You’ve saved me hours
When I running the code for pycuda its shows me error:
CompileError: nvcc compilation of C:\Users\NRB\AppData\Local\Temp\tmplothnihj\kernel.cu failed
I have added NVCC compiler path also but I got the same error. Can you please tell me how can I fix the problem. | https://weiminwang.blog/2015/10/25/installing-cuda-7-5-and-pycuda-on-windows-for-testing-theano-with-gpu/comment-page-1/ | CC-MAIN-2020-24 | refinedweb | 496 | 59.7 |
clean up xpfe/ after suite moving to toolkit
RESOLVED FIXED in seamonkey2.0a1
Status
People
(Reporter: kairo, Assigned: kairo)
Tracking
Firefox Tracking Flags
(Not tracked)
Details
Attachments
(4 attachments, 1 obsolete attachment)
When bug 328887 lands and SeaMonkey will use toolkit, a lot of code in xpfe/ will go unused. We should clean that up (cvs removing lots of stuff), so that the tree gets cleaner for everybody.
This patch removes those parts I could easily spot that we can kill in xpfe/ Additionally, those dirctories can be cvs removed: mozilla/xpfe/components/alerts/resources/ mozilla/xpfe/components/cookie/ mozilla/xpfe/components/updates/resources/ mozilla/xpfe/components/xfer/ mozilla/xpfe/components/filepicker/res/ mozilla/xpfe/components/console/resources/ mozilla/xpfe/components/find/resources/ ;-)
Assignee: jag → kairo
Status: NEW → ASSIGNED
Attachment #267090 - Flags: superreview?(neil)
Attachment #267090 - Flags: review?(bugzilla)
(In reply to comment #1) > ;-) Well you're right that Camino is the only other one we need to worry about in xpfe/components (Minimo has MOZ_XPFE_COMPONENTS not defined, so it just does an exports cycle through xpfe/components - I've never been able to convince myself if thats really required now or not). Can I suggest that you do a patch that removes all of alerts, updates, console, startup, extensions and ask Camino to try it out/approve it? From the fact that Camino don't incorporate alerts or startup in the build section, I'm guessing that Camino don't actually use them (a quick search for the public interfaces in camino found no matches). For the others, I'm guessing that as we're able to remove the chrome dirs, we're probably safe in removing the source anyway. I've had good responses from them in the past wrt tidy up, so it'd be good to take this opportunity if we can.
From what I'm seeing, every Mozilla build process at least enters xpfe/components (if MOZ_XPFE_COMPONENTS is unset, it goes in at least in the export stage) - and everyone else than Minimo (which even has MOZ_XUL_APP=1 btw, through the "basic" embedding profile) is using the default embedding profile, which has this var turned on. Together with the MOZ_HAVE_BROWSER stuff in the Makefile and Camino, this looks a bit too hot for me.
Comment on attachment 267090 [details] [diff] [review] remove a list of definitions from the xpfe/ source (checked in) Last time I looked, filepicker and console had patches which are still waiting to be ported to toolkit, so they can't be CVS removed just yet. >-#ifndef MOZ_XUL_APP >-NS_GENERIC_FACTORY_CONSTRUCTOR(nsCmdLineService) >-NS_GENERIC_FACTORY_CONSTRUCTOR(nsAppStartup) >-NS_GENERIC_FACTORY_CONSTRUCTOR(nsUserInfo) >-#endif // !MOZ_XUL_APP Are you sure that Camino doesn't use these?
Attachment #267090 - Flags: superreview?(neil) → superreview+
(In reply to comment #4) > (From update of attachment 267090 [details] [diff] [review]) > Last time I looked, filepicker and console had patches which are still waiting > to be ported to toolkit, so they can't be CVS removed just yet. At least their UI isn't used any more in suiterunner, so I don't think it's too useful to keep that around. > >-#ifndef MOZ_XUL_APP > >-NS_GENERIC_FACTORY_CONSTRUCTOR(nsCmdLineService) > >-NS_GENERIC_FACTORY_CONSTRUCTOR(nsAppStartup) > >-NS_GENERIC_FACTORY_CONSTRUCTOR(nsUserInfo) > >-#endif // !MOZ_XUL_APP > Are you sure that Camino doesn't use these? At least not here, as this is inside |#ifdef MOZ_SUITE| (even visible in the patch context).
Comment on attachment 267090 [details] [diff] [review] remove a list of definitions from the xpfe/ source (checked in) r=me for suite build config. I'd prefer it if you get benjamin's (or someone's) review as well. Also I assume you're going to be sorting out the MOZ_SUITE ifdefs in xpfe/global and xpfe/bootstrap in another patch?
Attachment #267090 - Flags: review?(bugzilla) → review+
Comment on attachment 267090 [details] [diff] [review] remove a list of definitions from the xpfe/ source (checked in) Requesting additional build system review as requested by Mark. And yes, I'll attack the additional, not as clear cases with additional patches.
Attachment #267090 - Flags: review?(ted.mielczarek)
Note: From what I see in only search, bookmarks, and startup are directly referenced from elsewhere in the tree, everything else is built directly from within xpfe/components/ - oh, and is directly referencing libappcomps.
This patch plus the removed files listed at its end kill off most of xpfe/bootstrap. From what I see, we might only need nsSigHandlers.cpp and showOSAlert.cpp from it in toolkit/xre, but I didn't dare to kill off more than I did in this step. This at least builds fine on Linux (SeaMonkey, Firefox, Thunderbird). Not sure if we could remove more in the "export" target - I just saw that no SHAREDCMMSRCS are defined anyways in that Makefile.
Attachment #267633 - Flags: review?(benjamin)
ad comment #9 - I just finished a build flawlessly (on Linux) with having only nsSigHandlers.cpp and showOSAlert in xpfe/bootstrap :)
Comment on attachment 267090 [details] [diff] [review] remove a list of definitions from the xpfe/ source (checked in) checked in this parts, cvs removes still pending, need to check back with Neil about comment #4
Attachment #267090 - Attachment description: remove a list of definitions from the xpfe/ source → remove a list of definitions from the xpfe/ source (checked in)
Comment on attachment 267633 [details] [diff] [review] kill a list of files from xpfe/bootstrap (checked in) checked in along with removing the files listed there. will get separate review about unused .cpp/.h files in xpfe/bootstrap - maybe via IRC
Attachment #267633 - Attachment description: kill a list of files from xpfe/bootstrap → kill a list of files from xpfe/bootstrap (checked in)
(In reply to comment #1) > mozilla/xpfe/components/alerts/resources/ > mozilla/xpfe/components/cookie/ > mozilla/xpfe/components/updates/resources/ > mozilla/xpfe/components/xfer/ > mozilla/xpfe/components/find/resources/ I cvs removed those now as well. > mozilla/xpfe/components/filepicker/res/ > mozilla/xpfe/components/console/resources/ Those were left alive per comment #4, need to sort out first what improvements went in on the xpfe side which are lacking on toolkit and file bugs for those.
I just did the rest of the possible cvs removes in xpfe/bootstrap - for reference, this leaves the following content in that directory: appleevents / - still built on mac nsDocLoadObserver[.cpp|.h] - used by appleevents nsSigHandlers.cpp - used by toolkit/xre showOSAlert.cpp - used by toolkit/xre
I have taken a look into xpfe/global and xpfe/communicator - we still need xpfe/global/resources/content/nsWidgetStateManager.js which is packed up by suite/ as long as we're using the old prefwindow, and I need to find out what Thunderbird needs from communicator, but apart from that, I think both can be killed.
Regarding comment #4 (and comment #13): Bug 266629 fixed all inconsistencies of filepicker, so we can actually get rid of filepicker/res/ (the public and src portions probably should also be moved at some point). Error Console is a different story, I filed bug bug 386899 for that.
filepicker/res/ has been removed after OK from Neil via IRC.
Robert, Are you still working on this ?
I will be once the blockers are resolved. There is a reason for bugs having blockers set. ;-)
As we don't have to take care of Camino still entering those directories now on Mercurial, I'd like to move on and kill xpfe/communicator/ and xpfe/global/ from mozilla-central. I've searched for any occurrences of those on mozilla-central or comm-central, and this patch fixes everything I found. Please see this review request as being for that patch _and_ the removal of those two directories - with one exception: xpfe/global/resources/content/nsWidgetStateManager.js is used by SeaMonkey until the switch to the new prefwindow is completed (bug 394522). Once that task is done (target is early September), we can remove that last file to complete the extinction of xpfe/global.
Attachment #334092 - Flags: review?(ted.mielczarek)
This is probably the last part of this bug - everything else that needs cleanup can be done in other bugs, including components/ subdirs that might be in need to get obsoleted. The patch here reorders the components/Makefile.in a bit to not have as many nested ifdefs and kills off the two directories that are only built for non-xulapps, which don't exist any more on hg (startup and xremote).
Attachment #335223 - Flags: superreview?(neil)
Attachment #335223 - Flags: review?(ted.mielczarek)
Comment on attachment 335223 [details] [diff] [review] clean up xpfe/components >+ifdef MOZ_SUITE >+DIRS += \ >+ related \ >+ $(NULL) Might as well make this DIRS += related
Attachment #335223 - Flags: superreview?(neil) → superreview+
Comment on attachment 334092 [details] [diff] [review] patch to go along with killing off communicator/ and global/ (checked in) Thanks, pushed as
Attachment #334092 - Attachment description: patch to go along with killing off communicator/ and global/ → patch to go along with killing off communicator/ and global/ (checked in)
New version of the patch, including more places where startup and xremote were referred to - see toolkit-makefiles.sh and bootstrap/appleevents changes in the beginning. Re-requesting sr for those changes as well - the rest of the patch is unchanged.
Attachment #335223 - Attachment is obsolete: true
Attachment #335380 - Flags: superreview?(neil)
Attachment #335380 - Flags: review?(ted.mielczarek)
Attachment #335223 - Flags: review?(ted.mielczarek)
Comment on attachment 335380 [details] [diff] [review] clean up xpfe/components, v1.1 [Checkin: Comment 28] +ifdef MOZ_SUITE +DIRS += \ + related \ + $(NULL) + +ifdef SUITE_USING_XPFE_DM +DIRS += download-manager +endif + +ifndef MOZ_PLACES +DIRS += history +endif + +ifeq ($(OS_ARCH),WINNT) +DIRS += winhooks +endif +endif Could you stick a # MOZ_SUITE after the last endif here? It gets a little difficult to follow nested if blocks.
Attachment #335380 - Flags: review?(ted.mielczarek) → review+
(In reply to comment #25) > Could you stick a # MOZ_SUITE after the last endif here? It gets a little > difficult to follow nested if blocks. Sure, will do that - even if I I decreased nesting with this patch.
Comment on attachment 335380 [details] [diff] [review] clean up xpfe/components, v1.1 [Checkin: Comment 28] >+DIRS += \ >+ related \ >+ $(NULL) Still might as well make this DIRS += related ...
Attachment #335380 - Flags: superreview?(neil) → superreview+
Landed with nits addressed as From what I see, we should have cleaned out all dead code from xpfe/ now, all further code should be tracked by appropriate bugs that switch over users of the old code to newer code.
Status: ASSIGNED → RESOLVED
Closed: 11 years ago
Resolution: --- → FIXED
Attachment #335380 - Attachment description: clean up xpfe/components, v1.1 → clean up xpfe/components, v1.1 [Checkin: Comment 28] | https://bugzilla.mozilla.org/show_bug.cgi?id=380786 | CC-MAIN-2019-26 | refinedweb | 1,738 | 52.6 |
Silverlight Toolkit for Windows Phone? What does it bring to the table?
Silverlight Toolkit for Windows Phone? What does it bring to the table?
Join the DZone community and get the full member experience.Join For Free
Developing for Windows Phone 7 is fun and the default SDK comes pre-loaded with the basic set of components that allows you to build fully-functional Windows Phone 7 applications. Of course, there are some controls out there that are used in the OS itself but you aren't able to insert those directly without your own implementation. For this specific case, Microsoft released and continues to maintain the Silverlight Toolkit for Windows Phone.
Download and install it. Once done, in an existing Windows Phone 7 application project, you need to add a reference to the toolkit libraries. Those are located in <SystemDrive>:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Toolkit\Nov10\Bin (for 64-bit systems) or <SystemDrive>:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Toolkit\Nov10\Bin (for 32-bit systems).
You need to add a reference to Microsoft.Phone.Controls.Toolkit.dll:
Then, you need to add a namespace reference in the page itself:
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
Now you can add controls to your page by prefixing the objects with toolkit:
So here is what you get by using the toolkit.
AutoCompleteBox
This control is extremely helpful when you have a pre-set collection of words and you want to make it easier for the end-user to type those words. Don't confuse this control with the auto-correct option that you can get for a TextBox control - AutoCompleteBox works as contextual suggestions. It won't automatically correct a word, even if it wasn't typed correctly. To tie this control to your set of words, you should use the ItemsSource property and bind it, for example, to a List<string>.
ContextMenu
This is a control that can easily be used to trigger specific actions targeted to a specific control. For example, you might want to implement a custom copy & paste mechanism in your application or you want to have specific actions performed on an image. Instead of cluttering the main UI, you can trigger the list of actions on continuous touch.
DatePicker
For now, I haven't seen this control to be massively used, but nonetheless it offers a great way to select a specific date. It returns a DateTime instance that is nullable (can be set to null).
ListPicker
Sometimes this can be considered as an alternative to the ComboBox, sometimes to a ListView. The interesting fact about this control is that it changes appearance depending on the number of items passed to it from the bound collection.
If there are 5 or less items, it will appear as a dropdown list right on the page:
When more item are present, a separate list container page will be displayed. It isn't really a page, but rather a container that goes on top of the existing page.
LongListSelector
This is the same control that it is used in Zune and the contact list on Windows Phone 7. It is the same ListView, however items can be now grouped and the groups easily accessed by clicking on the group header. The name of the control speaks for itself - it is targeting very large lists.
TimePicker
Having the same structure as DatePicker, TimePicker is used to select a time value. The returned result will be DateTime also represented as a nullable type.
ToggleSwitch
When the radio button is not enough, you can let the user switch between states with a slider. If you've already used a real Windows Phone 7 device, then you probably know that ToggleSwitch is used in the system settings (e.g. to turn the WiFi on or off). Speaking of this control, I recently was working on my own implementation of ToggleSwitch.In my opinion, this control is much more intuitive from a user's perspective than any other possible switch.
WrapPanel
This is basically a combination between a StackPanel and a Grid. It works based on the same idea as the regular Silverlight WrapPanel. I find it useful when you need to display small snapshots (e.g. photos) in an organized manner with custom orientation.
Conclusion
As you can see, the Silverlight Toolkit for Windows Phone 7 brings more value to the component part of the application. Although it is an additional dependency, it will most certainly help you in the long run when you won't have to reinvent the wheel (unless you want to do it for fun). So far, the toolkit is regularly updated, so I would recommend you checking the CodePlex page for updates from time to time.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/why-you-need-download | CC-MAIN-2018-30 | refinedweb | 822 | 63.49 |
Details
- Type:
Bug
- Status: Closed
- Priority:
Critical
- Resolution: Fixed
- Affects Version/s: Scala 2.10.0, Scala 2.10.1-RC1
- Fix Version/s: Scala 2.10.2-RC1
- Component/s: None
- Labels:None
Description
In Types.scala we have the following code:
Statistics.newView("#unique types") { if (uniques == null) 0 else uniques.size }
Let's have a closer look at Statistics.newView:
def newView(prefix: String, phases: String*)(quant: => Any): View = new View(prefix, phases, quant)
As you can see newView takes by-name argument (that in our case closes over the whole Global) and passes it to View.
The View class inherits from Quantity that is defined as follows:
trait Quantity { if (prefix.nonEmpty) { val key = s"${if (underlying != this) underlying.prefix else ""}/$prefix" qs(key) = this } val prefix: String val phases: Seq[String] def underlying: Quantity = this def showAt(phase: String) = phases.isEmpty || (phases contains phase) def line = f"$prefix%-30s: ${this}" val children = new mutable.ListBuffer[Quantity] }
So we register this in global (defined in top-level object) HashMap stored in variable qs. The consequence is that even if you don't use Global it'll be still hanging there because Statistics holds reference to it. This is a memory leak that I observed while using Scala IDE where Global used for compiling the code was kept around and consumed aroung 0.5GB of heap.
Activity
The simple solution to avoid memory leak is to turn all operations in Statistics into no-ops in case statistics is disabled.
However, the whole design is broken because it doesn't work across many Globals. Also, life cycle of that top-level object is not clear to me since you can mutate enabled flag at any time.
Added Iulian to watchers as he might be interested in this ticket. | https://issues.scala-lang.org/browse/SI-7130 | CC-MAIN-2014-15 | refinedweb | 300 | 58.28 |
.
PayPal Buyer Protection uses online dispute resolution to address transaction-related disputes between buyers and sellers. For transactions that are eligible for PayPal Buyer Protection (look for the blue and white shield on the eBay listing), buyers can report a problem with a purchase as long as it's tangible merchandise that has been shipped by a courier that uses online package tracking.
There are two kinds of claims you can file as a buyer:
You did not receive a package.
You received a package, but it is not as described (which includes getting an empty box).
To file a PayPal Buyer Protection claim, log in to your PaypPal account, click the Resolution Center tab, and read the instructions. When you're ready, click File a Claim and fill in the information as prompted.
The first thing you'll be asked for is the PayPal Transaction ID, a unique 17-digit code that corresponds to the transaction you're disputing. To find the code, click Get PayPal Transaction ID and then wade through your PayPal history until you've found the transaction. Simply click the code in the Transaction ID column, and PayPal will automatically insert it into the claim form.
Each claim opens a case at PayPal and notifies the seller to respond. Once you have filed a claim, click the Resolution Center tab to check the status of your claim.
Before you transact with a seller, make sure you read the merchandise description carefully for details and disclaimers. If the deal seems too good to be true, beware! A brand new iPod for half the price you'd normally pay should raise a big red flag. (You can also buy a plasma screen TV off the back of a truck in a dim alley.) Great deals can be found online, but don't ignore your common sense.
Always contact the seller before filing a claim; sellers appreciate this and might be willing to work things out to avert the claim going on their PayPal record. (If your neighbor's dog is barking all night, try talking to your neighbor before calling animal control about a rabid dog.) A lot of issues can be resolved with simple communication, leaving both the buyer and seller on good terms.
Allow the seller time to ship the merchandise to you. Sellers are required to ship within seven days to qualify for the Seller Protection Policy, that this does not include the time it might take for the courier to deliver the package. International shipments might take longer, due to customs and fundamental shipping delays. Obviously, filing a claim an hour after you pay makes you appear irrational and only angers your seller. An angry seller will be less likely to be reasonable and responsive to your claim.
Finally, be patient. Instead of contacting PayPal in multiple ways at multiple times, allow the claim process to work. Multiple contacts just add clutter to your case and might actually delay it.
Filing a claim does not necessarily mean that you'll get your money back. As with any online dispute resolution forum, both parties involved in the dispute tell their sides of the story and are asked to submit information to substantiate their statements. Most claims are resolved without any intervention from PayPal at all; for instance, you might cancel your claim after receiving a tracking number from the seller.
PayPal uses a variety of checks and balances to vet the buyer's claims. This might include requiring you to fax a letter of inauthenticity from a third-party dealer on claims for counterfeit goods or fax a police report for higher-priced merchandise.
"Not as described" claims are handled on a case-by-case basis because there are millions of items that change hands every day, and it's impossible to generalize about the meaning: a scratch on a priceless violin cannot be compared to a scratch on a Frisbee©.
If it's an eBay item, the original eBay listing is the main decision factor: what exactly did the seller advertise? Only claims for significantly "not as described" merchandise will be granted. (If a shirt is light blue instead of dark blue, you'll probably be denied a refund.)
In almost all cases, a buyer has to return (at her own expense) the significantly not-as-described merchandise to the seller before getting a refund. Buyers do not get to keep both the item and the money.
Although PayPal might find that you're due a refund, PayPal never draws money from a seller's bank account or credit card without the seller's permission (this would be considered an unauthorized transaction and is therefore illegal). PayPal might not be perfect (in some people's opinions), but they're not stupid. For this reason, don't dawdle when it comes to filing Buyer Protection claims.
If a seller's PayPal balance has insufficient funds to complete a refund, the PayPal account balance will become negative as soon as the buyer has been refunded and the acouunt might be limited. See [Hack #5] for more information on what you can do if your account has been limited.
Even if a buyer's claim is denied, there is a record of every claim on the seller's account. Sellers with a high claim rate quickly trigger investigation by PayPal. Fraudulent sellers have been taken to court, convicted, heavily fined, put in jail, and blacklisted. Every now and then, you'll read about these cases in the newspaper.
If you made your purchase on eBay, you can also check out eBay's Security Center to read about ways to protect yourself. In 2003 or earlier, eBay might have paid you under their $200 ($25 processing fee) purchase protection program, but now that eBay and PayPal are one company, there is sufficient coordination such that you'll be directed to the right place to file a claim. If your purchase was paid for with PayPal, eBay will ask you to work with PayPal to get your money back. For other issues, you will find various forms in the Security Center to report sellers asking for additional money after the listing ends, suspended sellers selling under another ID, sellers abusing feedback, and so on. In addition to getting your money back from PayPal, you can alert eBay to problem sellers. | http://etutorials.org/Misc/paypal+hacks/Chapter+2.+Making+Payments/Hack+16+Dispute+Merchandise+Payments/ | CC-MAIN-2017-22 | refinedweb | 1,062 | 59.84 |
It’s been four weeks and 7 EAP builds since we blogged about the ReSharper Ultimate 2017.2 EAP (Early Access Program) — time to have a thorough look at what’s new since!
- Improved C# 7.1 support in ReSharper
- ReSharper – Navigation
- ReSharper – Inspections and quick-fixes
- ReSharper – Web
- ReSharper – More!
- dotPeek
- dotTrace and dotMemory
- ReSharper C++ improvements
Improved C# 7.1 support in ReSharper
With C# 7.1 around the corner, several new language features will come available. In our first ReSharper 2017.2 EAP, we already added support for the
default literal. This newest EAP comes with support for a change in pattern matching with generic types, full support for
async main, and supports tuple projection initializers.
Traditionally, when we would want to project a collection and then run LINQ over it, we’d have to resort to using either a helper class or an anonymous type for doing that projection. Not only that: if we just wanted the values for
name and
age, we’d have to allocate those explicitly as well:
It looks verbose, and in fact there are several things happening under the covers that make this less than optimal. The compiler will generate an anonymous type which we are allocating on the managed heap (for every element in our list). We then have to allocate our
name and
age as well.
Granted, we could make this a bit more efficient by rewriting the example a little bit, or use C# 7.1’s tuple projection initializers. No anonymous type, less allocatons on the managed heap, and pleasant to read:
Just like with the anononymous type, C# 7.1 infers the value tuple’s element names from the projection here. We’ve also added an inspection for checking redundant value tuple component names:
Note if you want to use this, the
ValueTuple type is required. It’s built into .NET 4.7, .NET Core 2.0, Mono 5.0 and .NET Standard 2.0. If you’re on another target framework, the System.ValueTuple package will have to be installed.
ReSharper – Navigation
When using ReSharper’s Go to Everything (Ctrl+T) or one of the other navigation features, we can find types, type members, files, text, … It’s a powerful search engine, much like the ones we use to find things on the Internet! ReSharper’s search supports partial search terms, CamelHumps, misspellings, … In this EAP build, we made finding things in our projects even more powerful!
ReSharper now returns results when word order is incorrect. What was that method called again? Was it
ValidUser() or
UserValid()? No worries, Go to … will find it:
Sometimes we do know the correct name of what we are looking for. However when that name is something more generic like
Service, ReSharper may return a lot of search results…
Just like with Internet search engines, ReSharper now supports adding quotes to enforce an exact match:
It’s also possible to use wildcard
* or
? inside quotes for a more exact wildcard match. For example
"*Service" will show
UserService,
IssueService,
WorkItemService – as long as it ends in Service.
ReSharper – Inspections and quick-fixes
We’ve always had a code inspection that encourages using implicit types using the
var keyword (or, depending on your code style, the other way around, using explicit types). This EAP now also applies this inspection and its corresponding quick-fix to
out variables:
A couple of other inspections were added as well:
- New code inspection that detects possibly unintended transformations from
IQueryableto
IEnumerable.
- More context actions and quick-fixes supporting
<inheritdoc/>. We now show a warning when
<inheritdoc/>is used in an invalid context. There is also a suggestion for adding
<inheritdoc/>when implementing or overriding members, as not adding it would hide documentation from the base symbol.
There are many ways of checking for
null values and there are many preferences with our users for what style of
null checks should be used when generating code. We have added a new options page, Null checking, where the priority of
null checking patterns used by quick-fixes, context actions and code generation actions can be configured:
ReSharper – Web
A lot of work in the latest ReSharper Ultimate 2017.2 EAP build was done on the TypeScript side:
- We improved support for mapped type members in Find Usages and in the Rename refactoring (Ctrl+R, R). For example, the
nameproperty from our
IDoginterface will be found in mapped and derived types now:
- For TypeScript 2.3, we added the contextual
thisfor object literals and the
--strictoption.
- TypeScript 2.4 enums with string values (or mixed string/number values) are now supported by ReSharper. And when referenced via a mapped type property, string values are correctly found/renamed.
- TypeScript 2.4 support for generic inference from contextual type returns and generic contextual signatures.
We made several JSON improvements as well, for example when working in
package.json. ReSharper knows about the file type and when we invoke Quick Documentation (Ctrl+Shift+F1) on a package name, we can see additional package details as well as links to the home page, tarball and issue tracker:
While we’re in
package.json: completion for scoped NPM packages like “@angular/core” now also works:
ReSharper – More!
When generating a constructor using the Generate action (Alt+Insert), parameters for that constructor can be made optional:
ReSharper Build reduces the time it takes to build our solution by applying heuristics to only build projects that need updating. This latest ReSharper Ultimate 2017.2 EAP build adds .NET Core support to ReSharper Build.
dotPeek
Several other improvements and fixes went into dotPeek. We now have proper decompilation of assemblies that used
nameof() in their original source code. We made various improvements and fixes for displaying and navigating in IL code.
SourceLink is a new way of embedding infomation about an assembly’s original source code into the PortablePDB format. Both our standalone decompiler as well as ReSharper now support SourceLink: when an assembly is compiled with the Roslyn compiler flag
/sourcelink:<file> (and a
source_link.json is generated using, for example, Cameron Taggart’s SourceLink tools), dotPeek will now download sources referenced in the PortablePDB or use the embedded source files when available.
Speaking of PortablePDB – we added some more features to the Metadata tree:
-_9<<
The Go to String (Ctrl+Alt+T) navigation is now integrated into Go to Everything (Ctrl+T). Additionally:
- It searches for strings in attributes, making it easier to find occurences of a given string in a (decompiled) code base.
- Improved presentation of long and multiline strings.
- When searching for a substring in such string, dotPeek now navigates to the substring position instead of jumping to the start of that long or multiline string.
dotTrace and dotMemory
We have been working hard improving the profiler engine powering both dotTrace and dotMemory. First of all, we added support for profiling .NET Standard 2.0 applications, on our own machine or remote.
The profiler core engine now supports setting a directory where temporary files, diagnostics and snapshots are stored. This is especially handy when profiling remote applications: if the profiler has no write access on the system drive, dotTrace and dotMemory can still profile the application.
Several bugfixes went in as well. We fixed a crash of the CLR running the application being profiled when a forced garbage collection happens during garbage collector initialization. A deadlock when the profiler shuts down during forced garbage collection was fixed, too.
ReSharper C++ improvements
A number of changes and new features went into ReSharper C++, including performance improvements – for example on switching build configurations.
Let’s have a look at what else is new.
Code analysis and quick-fixes
An analyzer was added to check when a local variable can be defined as a constant. ReSharper C++ will inform us about that and display a suggestion in the editor.
From the ReSharper settings under Code Editing | C++ | Naming Style, we could already edit the naming styles for generating new entities. We now added an inspection that hints when existing code does not conform to these naming styles. The inspection can be enabled or disabled as well:
An inspection for unused return values shows us when we forgot to return the value. Using a quick-fix, ReSharper C++ can solve things for us:
Other inspections and quick-fixes that were added:
- A quick-fix to add
std::movewhen cannot bind rvalue reference to lvalue.
- An inspection that shows unused entities with internal linkage.
- Quick-fix to add an
#ifndef/
#define/
#endifinclude guard for the Missing include guard inspection.
Editor formatting
Here’s an overview of enhancement to the editor formatter:
- Support for line wrapping.
- The formatter supports Clang-format style configuration files (in addition to EditorConfig).
- Several code formatting settings were added:
- Option to insert line breaks after template headers and function return types.
- Options for indentation of parentheses in function declarations, method calls,
if/
while/
forstatements.
Language support
The ReSharper C++ team continuously works on adding additional support for the C and C++ languages. For example:
- Find usages (Shift+F12) and the Rename refactoring (Ctrl+R, R) are now supported for user-defined literals.
- Anonymous nested structures are now supported in C code .
- Virtual methods that can be overridden are shown in completion inside class bodies.
- The type traits
std::is_trivially_constructible,
std::is_trivially_copy_assignable
and
std::is_trivially_move_assignableare now supported.
- More C++17 support!
usingfor attribute namespaces.
- Code inspections honor
[[nodiscard]]and
[[maybe_unused]]attributes.
That about wraps it up. We’re looking forward to any feedback you may have on the latest builds of ReSharper, ReSharper C++, dotCover, dotTrace, dotMemory, dotPeek, as well as various command-line packages included in this EAP.
Download the latest ReSharper Ultimate 2017.2 EAP and give it a try!
Just an additional suggestion with “Go to Everything”.
Are you able to include brackets to cause the list to filter by a method?
When searching for: “PersonAdd” it might find 10 results for example
If I Search for: “PersonAdd(” it says nothing found.
It would be much more beneficial if it matched any methods named PersonAdd(…)
Also: “Person(” should match PersonAdd(..), PersonDelete(..), PersonFind(…)
Thanks for your suggestion! Just logged it in our tracker –
Can this be installed on VS2017 preview?
Absolutely, that should work.
It works, yes, unfortunately, the .net core 2 support still isn’t great.
From a .Net Core 2.0 project, types that are described in a .net standard 2.0 assembly still cannot be resolved by ReSharper.
Any plans to support it before the next RTM of Visual Studio hits the shelves ?
That is unfortunate. Would you be able to share a project with us where you are seeing this? That can help us debug the issue. Feel free to email me at maarten.balliauw at jetbrains dot com.
Hi,
when do you plan supporting running tests written in Typescript?
For full stack developer it is very impotant feature to have one consistent test runner – it was really cool to have this feature for javascript – right now after switching to Angular 4 and Typescript I feel how important this feature was and how it is missing.
Hi, we have some known bugs in this area, for instance,.
I created a new issue. If it is possible, please provide some additional details about your project configuration:. Thanks!
Hi,
you can easy reproduct this issue by using standard .net core 2.0 single page application with angular from freshly released VS 2017.3. Then try to run tests from for example ClientApp\app\components\counter\counter.component.spec.ts – all skipped.
This was tested on latest EAP 12
Pingback: Der Weg zu ReSharper Ultimate 2017.2 – entwickler.de
Will refactoring feature parity between ReSharper and Rider be maintained?
Pingback: Dew Drop - July 21, 2017 (#2525) - Morning Dew
Will R# be able to detect certain common innocent bugs but very hard to troubleshoot?
Case in point, we had this code in our codebase:
//Incorrect code:
if(DateTime.Now.Subtract(transaction.CreatedDate).Minutes > TEN_MINUTES) {
…
}
//The correct code should have been:
if(DateTime.Now.Subtract(transaction.CreatedDate).TotalMinutes > TEN_MINUTES) {
…
}
The incorrect code caused occasional ‘random’ issues with our ticketing system… we only detect it more than 2 years later after we analysed our code base with PVS Studio ()
I found ReSharper TOO SLOW…
May be an accessible button to switch on/off Reshaper?
Now I’m using Visual Studio 2017 PRO. And no CODE MAP
Why Architecture Tools doesn’t draw complete classes with methods, properties and fields included?
I think there are a lot of improvements/possibilities in this area.
There is a on off button to do that, If you go to the Tools->Options menu then scroll drown to the “Resharper” option in the list there is a button to “Suspend Now” which turns off Resharper completely.
You can even bind this functionality to a keybinding, search your keybindings for “ReSharper_ToggleSuspended”. | https://blog.jetbrains.com/dotnet/2017/07/20/whats-new-latest-resharper-2017-2-eap-builds/?replytocom=498277 | CC-MAIN-2019-51 | refinedweb | 2,151 | 56.55 |
Not all I/O ASIC versions have the free-running counter implemented, an
early revision used in the 5000/1xx models aka 3MIN and 4MIN did not have
it. Therefore we cannot unconditionally use it as a clock source.
Fortunately if not implemented its register slot has a fixed value so it
is enough if we check for the value at the end of the calibration period
being the same as at the beginning.
This also means we need to look for another high-precision clock source on
the systems affected. The 5000/1xx can have an R4000SC processor
installed where the CP0 Count register can be used as a clock source.
Unfortunately all the R4k DECstations suffer from the missed timer
interrupt on CP0 Count reads erratum, so we cannot use the CP0 timer as a
clock source and a clock event both at a time. However we never need an
R4k clock event device because all DECstations have a DS1287A RTC chip
whose periodic interrupt can be used as a clock source.
This gives us the following four configuration possibilities for I/O ASIC
DECstations:
1. No I/O ASIC counter and no CP0 timer, e.g. R3k 5000/1xx (3MIN).
2. No I/O ASIC counter but the CP0 timer, i.e. R4k 5000/150 (4MIN).
3. The I/O ASIC counter but no CP0 timer, e.g. R3k 5000/240 (3MAX+).
4. The I/O ASIC counter and the CP0 timer, e.g. R4k 5000/260 (4MAX+).
For #1 and #2 this change stops the I/O ASIC free-running counter from
being installed as a clock source of a 0Hz frequency. For #2 it also
arranges for the CP0 timer to be used as a clock source rather than a
clock event device, because having an accurate wall clock is more
important than a high-precision interval timer. For #3 there is no
change. For #4 the change makes the I/O ASIC free-running counter
installed as a clock source so that the CP0 timer can be used as a clock
event device.
Unfortunately the use of the CP0 timer as a clock event device relies on a
succesful completion of c0_compare_interrupt. That never happens, because
while waiting for a CP0 Compare interrupt to happen the function spins in
a loop reading the CP0 Count register. This makes the CP0 Count erratum
trigger reliably causing the interrupt waited for to be lost in all cases.
As a result #4 resorts to using the CP0 timer as a clock source as well,
just as #2. However we want to keep this separate arrangement in case
(hope) c0_compare_interrupt is eventually rewritten such that it avoids
the erratum.
Signed-off-by: Maciej W. Rozycki <macro@linux-mips.org>
---
Ralf,
As promised this is the last of the three changes in this area, please
apply.
Maciej
linux-csrc-dec-r4k.patch
Index: linux/arch/mips/dec/time.c
===================================================================
--- linux.orig/arch/mips/dec/time.c
+++ linux/arch/mips/dec/time.c
@@ -125,12 +125,16 @@ int rtc_mips_set_mmss(unsigned long nowt
void __init plat_time_init(void)
{
+ int ioasic_clock = 0;
u32 start, end;
int i = HZ / 8;
/* Set up the rate of periodic DS1287 interrupts. */
ds1287_set_base_clock(HZ);
+ /* On some I/O ASIC systems we have the I/O ASIC's counter. */
+ if (IOASIC)
+ ioasic_clock = dec_ioasic_clocksource_init() == 0;
if (cpu_has_counter) {
ds1287_timer_state();
while (!ds1287_timer_state())
@@ -147,9 +151,21 @@ void __init plat_time_init(void)
mips_hpt_frequency = (end - start) * 8;
printk(KERN_INFO "MIPS counter frequency %dHz\n",
mips_hpt_frequency);
- } else if (IOASIC)
- /* For pre-R4k systems we use the I/O ASIC's counter. */
- dec_ioasic_clocksource_init();
+
+ /*
+ * All R4k DECstations suffer from the CP0 Count erratum,
+ * so we can't use the timer as a clock source, and a clock
+ * event both at a time. An accurate wall clock is more
+ * important than a high-precision interval timer so only
+ * use the timer as a clock source, and not a clock event
+ * if there's no I/O ASIC counter available to serve as a
+ * clock source.
+ */
+ if (!ioasic_clock) {
+ init_r4k_clocksource();
+ mips_hpt_frequency = 0;
+ }
+ }
ds1287_clockevent_init(dec_interrupt[DEC_IRQ_RTC]);
}
Index: linux/arch/mips/include/asm/dec/ioasic.h
===================================================================
--- linux.orig/arch/mips/include/asm/dec/ioasic.h
+++ linux/arch/mips/include/asm/dec/ioasic.h
@@ -33,6 +33,6 @@ static inline u32 ioasic_read(unsigned i
extern void init_ioasic_irqs(int base);
-extern void dec_ioasic_clocksource_init(void);
+extern int dec_ioasic_clocksource_init(void);
#endif /* __ASM_DEC_IOASIC_H */
Index: linux/arch/mips/kernel/csrc-ioasic.c
===================================================================
--- linux.orig/arch/mips/kernel/csrc-ioasic.c
+++ linux/arch/mips/kernel/csrc-ioasic.c
@@ -37,7 +37,7 @@ static struct clocksource clocksource_de
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
-void __init dec_ioasic_clocksource_init(void)
+int __init dec_ioasic_clocksource_init(void)
{
unsigned int freq;
u32 start, end;
@@ -56,8 +56,14 @@ void __init dec_ioasic_clocksource_init(
end = dec_ioasic_hpt_read(&clocksource_dec);
freq = (end - start) * 8;
+
+ /* An early revision of the I/O ASIC didn't have the counter. */
+ if (!freq)
+ return -ENXIO;
+
printk(KERN_INFO "I/O ASIC clock frequency %dHz\n", freq);
clocksource_dec.rating = 200 + freq / 10000000;
clocksource_register_hz(&clocksource_dec, freq);
+ return 0;
} | http://www.linux-mips.org/archives/linux-mips/2013-09/msg00071.html | CC-MAIN-2015-35 | refinedweb | 823 | 62.38 |
Return Oriented Programming on ARM (32-bit)
Anirudh
Originally published at
icyphox.sh
on
・5 min read
Before we start anything, you’re expected to know the basics of ARM assembly to follow along. I highly recommendAzeria’s series on ARM Assembly Basics. Once you’re comfortable with it, proceed with the next bit — environment setup.
Setup
Since we’re working with the ARM architecture, there are two options to go forth with:
- Emulate — head over to qemu.org/download and install QEMU. And then download and extract the ARMv6 Debian Stretch image from one of the links here. The scripts found inside should be self-explanatory.
- Use actual ARM hardware, like an RPi.
For debugging and disassembling, we’ll be using plain old
gdb, but you may use
radare2, IDA or anything else, really. All of which can be trivially installed.
And for the sake of simplicity, disable ASLR:
$ echo 0 > /proc/sys/kernel/randomize_va_space
Finally, the binary we’ll be using in this exercise is Billy Ellis’roplevel2.
Compile it:
$ gcc roplevel2.c -o rop2
With that out of the way, here’s a quick run down of what ROP actually is.
A primer on ROP
ROP or Return Oriented Programming is a modern exploitation technique that’s used to bypass protections like the NX bit (no-execute bit) and code sigining. In essence, no code in the binary is actually modified and the entire exploit is crafted out of pre-existing artifacts within the binary, known as gadgets.
A gadget is essentially a small sequence of code (instructions), ending with a
ret, or a return instruction. In our case, since we’re dealing with ARM code, there is no
ret instruction but rather a
pop {pc} or a
bx lr. These gadgets are chained together by jumping (returning) from one onto the other to form what’s called as a ropchain. At the end of a ropchain, there’s generally a call to
system(), to acheive code execution.
In practice, the process of executing a ropchain is something like this:
- confirm the existence of a stack-based buffer overflow
- identify the offset at which the instruction pointer gets overwritten
- locate the addresses of the gadgets you wish to use
- craft your input keeping in mind the stack’s layout, and chain the addresses of your gadgets
LiveOverflow has a beautiful video where he explains ROP using “weird machines”. Check it out, it might be just what you needed for that “aha!” moment :)
Still don’t get it? Don’t fret, we’ll look at actual exploit code in a bit and hopefully that should put things into perspective.
Exploring our binary
Start by running it, and entering any arbitrary string. On entering a fairly large string, say, “A” × 20, we see a segmentation fault occur.
Now, open it up in
gdb and look at the functions inside it.
There are three functions that are of importance here,
main,
winner and
gadget. Disassembling the
main function:
We see a buffer of 16 bytes being created (
sub sp, sp, #16), and some calls to
puts()/
printf() and
scanf(). Looks like
winner and
gadget are never actually called.
Disassembling the
gadget function:
This is fairly simple, the stack is being initialized by
pushing
{r11}, which is also the frame pointer (
fp). What’s interesting is the
pop {r0, pc}instruction in the middle. This is a gadget.
We can use this to control what goes into
r0 and
pc. Unlike in x86 where arguments to functions are passed on the stack, in ARM the registers
r0 to
r3are used for this. So this gadget effectively allows us to pass arguments to functions using
r0, and subsequently jumping to them by passing its address in
pc. Neat.
Moving on to the disassembly of the
winner function:
Here, we see a calls to
puts(),
system() and finally,
exit(). So our end goal here is to, quite obviously, execute code via the
system()function.
Now that we have an overview of what’s in the binary, let’s formulate a method of exploitation by messing around with inputs.
Messing around with inputs :)
Back to
gdb, hit
r to run and pass in a patterned input, like in the screenshot.
We hit a segfault because of invalid memory at address
0x46464646. Notice the
pc has been overwritten with our input. So we smashed the stack alright, but more importantly, it’s at the letter ‘F’.
Since we know the offset at which the
pc gets overwritten, we can now control program execution flow. Let’s try jumping to the
winner function.
Disassemble
winner again using
disas winner and note down the offset of the second instruction —
add r11, sp, #4. For this, we’ll use Python to print our input string replacing
FFFF with the address of
winner. Note the endianness.
$ python -c 'print("AAAABBBBCCCCDDDDEEEE\x28\x05\x01\x00")' | ./rop2
The reason we don’t jump to the first instruction is because we want to control the stack ourselves. If we allow
push {rll, lr} (first instruction) to occur, the program will
popthose out after
winner is done executing and we will no longer control where it jumps to.
So that didn’t do much, just prints out a string “Nothing much here…”. But it does however, contain
system(). Which somehow needs to be populated with an argument to do what we want (run a command, execute a shell, etc.).
To do that, we’ll follow a multi-step process:
gadget, again the 2nd instruction. This will
pop
r0and
pc.
- Push our command to be executed, say “
/bin/sh” onto the stack. This will go into
r0.
- Then, push the address of
system(). And this will go into
pc.
The pseudo-code is something like this:
string = AAAABBBBCCCCDDDDEEEE gadget = # addr of gadget binsh = # addr of /bin/sh system = # addr of system() print(string + gadget + binsh + system)
Clean and mean.
The exploit
To write the exploit, we’ll use Python and the absolute godsend of a library —
struct. It allows us to pack the bytes of addresses to the endianness of our choice. It probably does a lot more, but who cares.
Let’s start by fetching the address of
/bin/sh. In
gdb, set a breakpoint at
main, hit
r to run, and search the entire address space for the string “
/bin/sh”:
(gdb) find &system, +9999999, "/bin/sh"
One hit at
0xb6f85588. The addresses of
gadget and
system() can be found from the disassmblies from earlier. Here’s the final exploit code:
import struct binsh = struct.pack("I", 0xb6f85588) string = "AAAABBBBCCCCDDDDEEEE" gadget = struct.pack("I", 0x00010550) system = struct.pack("I", 0x00010538) print(string + gadget + binsh + system)
Honestly, not too far off from our pseudo-code :)
Let’s see it in action:
Notice that it doesn’t work the first time, and this is because
/bin/sh terminates when the pipe closes, since there’s no input coming in from STDIN. To get around this, we use
cat(1) which allows us to relay input through it to the shell. Nifty trick.
Conclusion
This was a fairly basic challenge, with everything laid out conveniently. Actual ropchaining is a little more involved, with a lot more gadgets to be chained to acheive code execution.
Hopefully, I’ll get around to writing about heap exploitation on ARM too. That’s all for now. | https://dev.to/icyphox/return-oriented-programming-on-arm-32-bit-436m | CC-MAIN-2019-47 | refinedweb | 1,227 | 72.97 |
hi every body...
i have problem in my project,and i need help to solve it
the problem is ::
i have string variable and i want to store two values in it
one value is string that insert it by the user and another value is integer that is generated by the system...
the problem is in the integr value how can i append it to the string??
i think ,it must convert the integr and store it in array of characters ,then append the array to the string
see my code:::
that convert the integer into array of character the number consists three digits..
is it correct or not and what is the possible solutions???
thank you...
#include <iostream> #include<string> #include<iomanip> using namespace std; int main() { char x[3]; int n,j=100,i=0; cout<<"Enter"; cin>>n; while(j>=1) { x[i]=n/j; n=n%j; j=j/10; i++; } return 0; } | https://www.daniweb.com/programming/software-development/threads/96332/convert-integer-to-array-of-character | CC-MAIN-2017-09 | refinedweb | 158 | 64.85 |
Red Hat Bugzilla – Bug 972429
BodhiClient is not working properly if running in thread and from interative interpreter
Last modified: 2013-06-09 11:27:55 EDT
Created attachment 758721 [details]
Bodhi reproducer
Description of problem:
BodhiClient is not working when it's invoked from python interactive interpreter and running in Thread
Version-Release number of selected component (if applicable):
python-fedora-0.3.32.3-1.fc18.noarch
python-fedora-0.3.32.3-1.fc17.noarch
How reproducible:
always
Steps to Reproduce:
Try to run attached file as:
$ python bodhiqthread.py
Then firstly run python interpreter and then import bodhiqthread
$ python
>>> import bodhiqthread
Actual results:
If running in interactive python interpreter, Bodhi never return results.
Expected results:
Some results from Bodhi.
Additional info:
I've tested this on F17 and F18 as well.
It is also reproducable if you create new python file and fill it with:
import bodhiqthread
So the problem is not with interactive interpreter but when it's imported as library.
We ran through some debugging over IRC and think we figured this out. The python stdlib threading docs say this:.
What we think is happening in the example is that bodhiqthread() is spawning the thread as a side effect. Removing the call to Starter() from bodhiqthread() and instead calling bodhiqthread.Starter() from the python prompt works. It should be possible to restructure the program so that the new thread is only spawned from a function or method call, not as a side effect of importing.
Feel free to reopen if you find that this is not what's happening. | https://bugzilla.redhat.com/show_bug.cgi?id=972429 | CC-MAIN-2018-34 | refinedweb | 265 | 52.9 |
The Aether project provides a library to interact with artifact repositories. In this context, artifact refers to some arbitrary file. Interaction refers to the acts of downloading artifacts and potentially their transitive dependencies from repositories for consumption by a local task and uploading local artifacts to repositories for sharing with others.
The project is currently divided into three codebases:
For Aether Core, a set of JARs will be published in the Eclipse download area for users to manually pull down and integrate into their applications. Additionally, these JARs will be published to the Central Repository for both users and build tooling to fetch. While the JARs of Aether Core contain OSGi-enabled manifests, there are currently no plans to publish a P2 update site until the community expresses strong interest in this distribution form.
Aether Demo will never be part of a release deliverable, the only purpose of this codebase is to serve as runnable documentation which users are expected to checkout directly from the project's Git repository.
Aether Ant Tasks depends on parts of Apache Maven that extend Aether Core to work with Maven repositories. Until the Apache Maven project has released a new version that incorporates Aether Core, Aether Ant remains unbuildable/unreleasable.
Release milestones will be published as committer time allows.
Aether consists of pure Java code and is expected to run on any JVM that supports Java SE 5 or newer.
Aether Ant Tasks target Apache Ant 1.7 or newer.
None of the Aether deliverables are internationalized, any log and exception messages use English.
API Contract Compatibility:
To comply with Eclipse Foundation requirements, all Aether Java types/packages have been
moved into the
org.eclipse.aether
namespace. No compatibility layer will be provided for users of Sonatype Aether.
Source Compatibility:
To comply with Eclipse Foundation requirements, all Aether Java types/packages have been
moved into the
org.eclipse.aether
namespace. While the API has undergone some refactoring and cleanup during the move to Eclipse, it is
expected that
typical clients mainly need to update their imports and make minor code changes to successfully build against the
new Aether API.
With the move of the code into the
org.eclipse.aether
namespace being a breaking change anyways, this provided an opportunity to remove deprecated code.
Additionally, the API has been refactored in some places to ease future evolution and to improve its
usuability.
Aether's component system has been enriched with annotations to support JSR-330 compliant dependency injection. Furthermore, Aether automatically wires itself to the popular SLF4J logging if this is available at runtime and the client application did not configure another logging mechanism. Last but not least, the Aether JARs are equipped with OSGi metadata to facilitate direct usage in OSGi-based applications.
Apache Ant, Ant, Apache Maven, Maven and Apache are trademarks of the Apache Software Foundation.
Back to the top | http://www.eclipse.org/projects/project-plan.php?planurl=/aether/plan/current.xml | CC-MAIN-2014-49 | refinedweb | 479 | 53.41 |
Performance we move on to the details, let’s recall how the plugin is used for tracking performance in CI builds:
- Write an integration test that runs some performance-critical functionality in your application.
- In the plugin, set a performance threshold for this test, which is the execution time value in ms or value taken from previous successful builds. Now, if the test exceeds its threshold, the plugin will fail the build and save the collected performance snapshot to build artifacts.
- Open the snapshot in dotTrace and find the exact cause of the performance issue.
This simplified workflow description is missing one obvious yet very important step: plugin configuration. The initial plugin required a number of preparatory steps on the build agent side: installing the console unit test runner and creating a rather complex XML configuration file (containing various profiling options, like profiling target, type, and so on). The new release addresses this issue: you no longer need to install the runner or create the configuration file. The trick is that the plugin is now made a part of unit testing build steps. Thus, after installing the plugin, all these build steps (Visual Studio Tests, NUnit, MSpec, and others) get the additional option Run build step under dotTrace profiler.
Moving profiling under unit testing build steps is also beneficial in one more way. From now on, when the plugin is enabled, you can not only check performance of tests but also track test results as usual (it’s still a “normal” unit testing build step).
Below, we’ll provide the detailed plugin usage example that you can use as a step-by-step guidance for the new dotTrace Plugin for TeamCity.
1. Install the plugin and dotTrace Console Profiler
IMPORTANT! If you use the previous plugin version, uninstall it before proceeding to this step.
- On your TeamCity server, download and copy dotTrace.zip to the plugins directory located in your TeamCity data directory. Use guest / guest credentials for download.
- Restart the TeamCity Server service.
- As the dotTrace console profiling tool is required for the plugin, download dotTrace Command Line Tools and unzip to any directory on a TeamCity build agent.
2. Write an integration test
Suppose we have an application with a killer feature called Foo. For example, we have a
Foo class with the
Foo() method which, in turn, uses a
Goo class. It creates a
Goo instance and runs its
Goo() method, which also runs some methods. We assume the execution time of the Foo feature is crucial for user experience. So we add a performance NUnit* test that runs the feature:
* The plugin supports all TeamCity .NET unit test runners, but we will use NUnit in our example.
namespace IntegrationTests { [TestFixture] public class PerformanceTests { [Test] public void TestFooFeature() { Foo foo = new Foo(); foo.Foo(); } } }
3. Create a build configuration
The next step is to create a build configuration dedicated to performance testing in TeamCity.
IMPORTANT! To help ensure consistency of profiling results, you should assign the build configuration that uses the plugin to a specific build agent (a hardware agent is strongly recommended). For further instructions please refer to TeamCity documentation.
Suppose we already have a project called My Project. Let’s add to that project a configuration consisting of two steps: building the application and running performance tests. To save time, let’s proceed right to configuring the second build step.
- In build configuration settings, go to Build Steps and click Add build step.
- In Runner type, select NUnit. (If you use a different testing framework, you would select the appropriate runner type, e.g. MSTest or Visual Studio Tests.)
- Set options for NUnit. The main one here is Run tests from — the relative path to the DLL with tests.
- Select Run build step under dotTrace profiler.
- Set the following plugin options and then click Save:
- Path to dotTrace ConsoleProfiler.exe: the path to the directory that you have unzipped dotTrace Command Line Tools into. In our example, it’s C:\Console Profiler
- Measure type: the type of profiling you want to use. We strongly recommend that you use only the Sampling type as it gives the most realistic time values. Note that the plugin does not support Timeline profiling.
- Performance snapshot artifacts path: set the path relative to the artifacts folder for storing the collected performance snapshot. Keep in mind that, depending on application complexity, the snapshot may take up hundreds of MB of disk space. We recommend updating your artifact cleanup policy so that after some time TeamCity would delete the snapshot folder from artifacts.
- Threshold values : specify the list of methods whose performance you want to check. The pattern is Namespace.Class.Method TotalTime OwnTime, where
- TotalTime is the method’s execution time, including its own time and the time of the method’s call subtree, in milliseconds;
- OwnTime is the method’s own execution time, in milliseconds.
(Setting a value to zero will make the plugin ignore the threshold.)
If we want to check the method’s time against the corresponding time in previous successful builds, we have three options: a) we can take values for comparison from the first successful build, b) take them from the last successful build, or c) compare against the average value calculated for all successful builds. If so, instead of the absolute threshold value in milliseconds, we should use one of the following prefixes:
a) F – take value from the first successful build,
b) L – take value from the last successful build, or
c) A – take average value based on all prior successful builds
Then, set the tolerance to indicate by how much the time value may be exceeded, as a percentage.
In our example, we want to track the total execution time of the Foo feature, so we add a threshold for the total time of the
TestFooFeature() test. F15 means that the value for comparison (with up to 15% tolerance) must be taken from the first successful build. E.g., if during the first successful build dotTrace measures 1000 ms total time for the method, the method’s threshold for all following builds will equal 1150 ms (1000 + 1000*0.15).
In our example, we also want to check the total time of the
Goo() method as it strongly impacts the performance of the Foo feature. Checking the method’s execution time during the build simplifies our job: in case of performance issues with Foo, we will know right away if
Goo() is the one to blame. As a threshold for the method, we also use the value from the first successful build, plus 15% tolerance.
4. Set a failure condition
If we want the build step to fail when a test exceeds its performance threshold, we should set a failure condition.
- In Build Configuration Settings, go to Failure Conditions.
- In Fail build if, select an error message is logged by build runner.
5. Run the build
Now it’s time to run the build! As we decided to use values from the first successful build for the thresholds, the first build won’t fail in any case — it is used only to set the baselines for the
TestFooFeature() and
Goo() methods. The time values from this build will become the “golden standard” for all subsequent builds.
- Run the build.
As TeamCity had no data on the methods’ execution times before the first build, the build passes successfully (the expected values equal 0).
- Suppose now that someone has edited the
Goo()method and made it slower. We’ll emulate this using
Thread.Sleep(200)and re-run the build. Now, the test still passes, but the build fails due to an error:
If we now click on the build, we’ll see the following build results:
As we instructed the plugin to save a performance snapshot, it has stored the archive with the snapshot in the artifacts Snapshots folder:
Note that the snapshot consists of a number of files. Now, we can analyze the snapshot and find the exact cause of the performance flaw:
- As all values are reported as TeamCity statistic values, so you can build trend graphs for the measured time values if you like. To do this, open the Parameters tab of any build and switch to Reported statistic values:
Click View trend for a particular parameter to see its diagram of changes:
Summary
As this post has illustrated, the updated dotTrace plugin for TeamCity no longer requires complex configuration, which makes it easier to use. To check it out on your own, please download the plugin (remember to use guest / guest credentials to download). As always, we’d be happy to hear any feedback from you. Feel free to ask any questions in the comments to this post.
Profile with pleasure!
14 Responses to Performance profiling in Continuous Integration: an updated dotTrace plugin to TeamCity
Dew Drop – February 17, 2016 (#2190) | Morning Dew says:February 17, 2016
[…] Performance profiling in Continuous Integration: an updated dotTrace plugin to TeamCity (Alexey Totin) […]
19-02-2016 - Freaking friday link pack! - Magnus Udbjørg says:February 19, 2016
[…] Performance Profiling In Continuous Integration: An Updated Dottrace Plugin To Teamcity […]
Sviataslau Seviaryn says:March 18, 2016
Hi!
Is there any way to set a ‘global’ threshold for all test methods instead of specifying separate values for every test?
Alexey Totin says:March 22, 2016
Hi,
No, it’s not possible.
Tony Fabris says:July 12, 2016
Request please: A way to have the profiling tool globally track all tests run from a given build step, and be able to set global threshold values for those tests.
Radoslav Cap says:August 29, 2016
+1
Shubham gupta says:June 1, 2017
Yes. This feature will make the use of the plugin really helpful!
Hariharan S says:April 22, 2016
That’s the great way to integrate performance tests as part of CI.
However, we use a custom test runner to suit our needs. Running tests step runs a batch file which calls our custom test runner.
Can dotTrace work with customer test runner?
Alexey Totin says:July 15, 2016
Hi, Hariharan
Sorry, I somehow missed your question back in April.
You may try to use the first version of the plugin. It implies that you manually create profiling configuration via xml file. There you can specify your custom runner as a profiling target.
JA says:March 1, 2017
Feature request: is it possible to store the results per-agent to reduce the need to limit the build configuration to a single agent? Or otherwise to limit the step to run (or report failure) on only one build agent in the pool? Of course, I can set up a separate build configuration purely for performance tests, but I’d rather get the feedback during the 1st stage of CI.
Shagin Sasi says:March 27, 2017
Hi
We integrated Performance profiling in Continuous Integration using dotTrace plugin to TeamCity. But we facing issue Opening Snapshot in dotTrace Perfromance Viewer as it showing “Cannot read snapshot file”. We are using JetBeans dotTrace Performance Viewer 2016.3.2 version and the plugin from location.
Alexey Totin says:March 28, 2017
Hi,
is it possible that you’re trying to open not the .dtp file, but, say, .dtp.0000 or .dtp.0001? If this is not the case, could you please contact dotTrace support and attach the snapshot to the ticket?
Roger says:September 14, 2017
Hi
Two feature requests…
* Would like ONE snapshot file instead. At least have them zipped. This way it’s simpler for TC user to download/run it in their local dottrace.
* For some reason it seems mandatory to set at least one threshold value. We don’t want that, we simply want a snapshot produced.
Thanks!
/Roger
Parth Aggarwal says:April 3, 2019
In my case, this isn’t reported as TeamCity statistic values thus I can’t do any analysis of the comparisons. | https://blog.jetbrains.com/dotnet/2016/02/16/performance-profiling-in-continuous-integration-an-updated-dottrace-plugin-to-teamcity/ | CC-MAIN-2021-04 | refinedweb | 1,987 | 61.87 |
View Source IEx (IEx v1.14.0-dev)
Elixir's interactive shell.
Some of the functionalities described here will not be available depending on your terminal. In particular, if you get a message saying that the smart terminal could not be run, some of the features described here won't work.
helpers
Helpers
IEx provides a bunch of helpers. They can be accessed by typing
h() into the shell or as a documentation for the
IEx.Helpers module.
autocomplete
Autocomplete
To discover a module's public functions or other modules, type the module name followed by a dot, then press tab to trigger autocomplete. For example:
Enum.
A module may export functions that are not meant to be used directly:
these functions won't be autocompleted by IEx. IEx will not autocomplete
functions annotated with
@doc false,
@impl true, or functions that
aren't explicitly documented and where the function name is in the form
of
__foo__.
Autocomplete may not be available on some Windows shells. You may need
to pass the
--werl option when starting IEx, such as
iex --werl
(or
iex.bat --werl if using PowerShell).
--werl may be permanently
enabled by setting the
IEX_WITH_WERL environment variable to
1.
encoding-and-coloring
Encoding and coloring
IEx expects inputs and outputs to be in UTF-8 encoding. This is the
default for most Unix terminals but it may not be the case on Windows.
If you are running on Windows and you see incorrect values printed,
you may need change the encoding of your current session by running
chcp 65001 before calling
iex (or before calling
iex.bat if using
PowerShell).
Similarly, ANSI coloring is enabled by default on most Unix terminals. They are also available on Windows consoles from Windows 10, although it must be explicitly enabled for the current user in the registry by running the following command:
reg add HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1
After running the command above, you must restart your current console.
shell-history
Shell history
It is possible to get shell history by passing some options that enable it in the VM. This can be done on a per-need basis when starting IEx:
iex --erl "-kernel shell_history enabled"
If you would rather enable it on your system as a whole, you can use
the
ERL_AFLAGS environment variable and make sure that it is set
accordingly on your terminal/shell configuration.
On Unix-like / Bash:
export ERL_AFLAGS="-kernel shell_history enabled"
On Windows:
set ERL_AFLAGS "-kernel shell_history enabled"
On Windows 10 / PowerShell:
$env:ERL_AFLAGS = "-kernel shell_history enabled"
expressions-in-iex
Expressions in IEx
As an interactive shell, IEx evaluates expressions. This has some interesting consequences that are worth discussing.
The first one is that the code is truly evaluated and not compiled. This means that any benchmarking done in the shell is going to have skewed results. So never run any profiling nor benchmarks in the shell.
Second, IEx allows you to break an expression into many lines, since this is common in Elixir. For example:
iex(1)> "ab ...(1)> c" "ab\nc"
In the example above, the shell will be expecting more input until it finds the closing quote. Sometimes it is not obvious which character the shell is expecting, and the user may find themselves trapped in the state of incomplete expression with no ability to terminate it other than by exiting the shell.
For such cases, there is a special break-trigger (
#iex:break) that when
encountered on a line by itself will force the shell to break out of any
pending expression and return to its normal state:
iex(1)> ["ab ...(1)> c" ...(1)> " ...(1)> ] ...(1)> #iex:break ** (TokenMissingError) iex:1: incomplete expression
pasting-multiline-expressions-into-iex
Pasting multiline expressions into IEx
IEx evaluates its input line by line in an eager fashion. If at the end of a line the code seen so far is a complete expression, IEx will evaluate it at that point.
iex(1)> [1, [2], 3] [1, [2], 3]
To prevent this behaviour breaking valid code where the subsequent line
begins with a binary operator, such as
|>/2 or
++/2 , IEx automatically
treats such lines as if they were prepended with
IEx.Helpers.v/0, which
returns the value of the previous expression, if available.
iex(1)> [1, [2], 3] [1, [2], 3] iex(2)> |> List.flatten() [1, 2, 3]
The above is equivalent to:
iex(1)> [1, [2], 3] [1, [2], 3] iex(2)> v() |> List.flatten() [1, 2, 3]
If there are no previous expressions in the history, the pipe operator will fail:
iex(1)> |> List.flatten() ** (RuntimeError) v(-1) is out of bounds
If the previous expression was a match operation, the pipe operator will also fail, to prevent an unsolicited break of the match:
iex(1)> x = 42 iex(2)> |> IO.puts() ** (SyntaxError) iex:2:1: pipe shorthand is not allowed immediately after a match expression in IEx. To make it work, surround the whole pipeline with parentheses ('|>') | 2 | |> IO.puts() | ^
Note however the above does not work for
+/2 and
-/2, as they
are ambiguous with the unary
+/1 and
-/1:
iex(1)> 1 1 iex(2)> + 2 2
the-break-menu
The BREAK menu
Inside IEx, hitting
Ctrl+C will open up the
BREAK menu. In this
menu you can quit the shell, see process and ETS tables information
and much more.
exiting-the-shell
Exiting the shell
There are a few ways to quit the IEx shell:
- via the
BREAKmenu (available via
Ctrl+C) by typing
q, pressing enter
- by hitting
Ctrl+C,
Ctrl+C
- by hitting
Ctrl+\
If you are connected to remote shell, it remains alive after disconnection.
prying-and-breakpoints
Prying and breakpoints
IEx also has the ability to set breakpoints on Elixir code and "pry" into running processes. This allows the developer to have an IEx session run inside a given function.
IEx.pry/0 can be used when you are able to modify the source
code directly and recompile it:
def my_fun(arg1, arg2) do require IEx; IEx.pry() ... implementation ... end
When the code is executed, it will ask you for permission to be introspected.
Alternatively, you can use
IEx.break!/4 to setup a breakpoint
on a given module, function and arity you have no control of.
While
IEx.break!/4 is more flexible, it does not contain
information about imports and aliases from the source code.
the-user-switch-command
The User switch command
Besides the
BREAK menu, one can type
Ctrl+G to get to the
User switch command menu. When reached, you can type
h to
get more information.
In this menu, developers are able to start new shells and alternate between them. Let's give it a try:
User switch command --> s 'Elixir.IEx' --> c
The command above will start a new shell and connect to it.
Create a new variable called
hello and assign some value to it:
hello = :world
Now, let's roll back to the first shell:
User switch command --> c 1
Now, try to access the
hello variable again:
hello ** (UndefinedFunctionError) undefined function hello/0
The command above fails because we have switched shells. Since shells are isolated from each other, you can't access the variables defined in one shell from the other one.
The
User switch command can also be used to terminate an existing
session, for example when the evaluator gets stuck in an infinite
loop or when you are stuck typing an expression:
User switch command --> i --> c
The
User switch command menu also allows developers to connect to
remote shells using the
r command. A topic which we will discuss next.
remote-shells
Remote shells
IEx allows you to connect to another node in two fashions. First of all, we can only connect to a shell if we give names both to the current shell and the shell we want to connect to.
Let's give it a try. First, start a new shell:
$ iex --sname foo iex(foo@HOST)1>
The string between the parentheses in the prompt is the name
of your node. We can retrieve it by calling the
node/0
function:
iex(foo@HOST)1> node() :"foo@HOST" iex(foo@HOST)2> Node.alive?() true
For fun, let's define a simple module in this shell too:
iex(foo@HOST)3> defmodule Hello do ...(foo@HOST)3> def world, do: "it works!" ...(foo@HOST)3> end
Now, let's start another shell, giving it a name as well:
$ iex --sname bar iex(bar@HOST)1>
If we try to dispatch to
Hello.world/0, it won't be available
as it was defined only in the other shell:
iex(bar@HOST)1> Hello.world() ** (UndefinedFunctionError) undefined function Hello.world/0
However, we can connect to the other shell remotely. Open up
the
User switch command prompt (Ctrl+G) and type:
User switch command --> r 'foo@HOST' 'Elixir.IEx' --> c
Now we are connected into the remote node, as the prompt shows us, and we can access the information and modules defined over there:
iex(foo@HOST)1> Hello.world() "it works!"
In fact, connecting to remote shells is so common that we provide a shortcut via the command line as well:
$ iex --sname baz --remsh foo@HOST
Where "remsh" means "remote shell". In general, Elixir supports:
- remsh from an Elixir node to an Elixir node
- remsh from a plain Erlang node to an Elixir node (through the ^G menu)
- remsh from an Elixir node to a plain Erlang node (and get an
erlshell there)
Connecting an Elixir shell to a remote node without Elixir is not supported.
the-iex-exs-file
The .iex.exs file
When starting, IEx looks for a local
.iex.exs file (located in the current
working directory), then a global one (located at
~/.iex.exs) and loads the
first one it finds (if any).
The code in the chosen
.iex.exs file is evaluated line by line in the shell's
context, as if each line were being typed in the shell. For instance, any modules
that are loaded or variables that are bound in the
.iex.exs file will be available
in the shell after it has booted.
Take the following
.iex.exs file:
# Load another ".iex.exs" file import_file("~/.iex.exs") # Import some module from lib that may not yet have been defined import_if_available(MyApp.Mod) # Print something before the shell starts IO.puts("hello world") # Bind a variable that'll be accessible in the shell value = 13
Running IEx in the directory where the above
.iex.exs file is located
results in:
$ iex Erlang/OTP 24 [...] hello world Interactive Elixir - press Ctrl+C to exit (type h() ENTER for help) iex(1)> value 13
It is possible to load another file by supplying the
--dot-iex option
to IEx. See
iex --help.
In case of remote nodes, the location of the
.iex.exs files are taken
relative to the user that started the application, not to the user that
is connecting to the node in case of remote IEx connections.
configuring-the-shell
Configuring the shell
There are a number of customization options provided by IEx. Take a look
at the docs for the
IEx.configure/1 function by typing
h IEx.configure/1.
Those options can be configured in your project configuration file or globally
by calling
IEx.configure/1 from your
~/.iex.exs file. For example:
# .iex.exs IEx.configure(inspect: [limit: 3])
Now run the shell:
$ iex Erlang/OTP 24 [...] Interactive Elixir - press Ctrl+C to exit (type h() ENTER for help) iex(1)> [1, 2, 3, 4, 5] [1, 2, 3, ...]
Link to this section Summary
Functions
Returns registered
after_spawn callbacks.
Registers a function to be invoked after the IEx process is spawned.
Macro-based shortcut for
IEx.break!/4.
Sets up a breakpoint in
module,
function and
arity with
the given number of
stops.
Returns
string escaped using the specified
color.
Returns IEx configuration.
Configures IEx.
Returns the options used for inspecting.
Returns
true if IEx was started,
false otherwise.
Link to this section Functions
after_spawn()View Source
Returns registered
after_spawn callbacks.
after_spawn(fun)View Source
Registers a function to be invoked after the IEx process is spawned.
break!(ast, stops \\ 1)View Source (since 1.5.0) (macro)
Macro-based shortcut for
IEx.break!/4.
break!(module, function, arity, stops \\ 1)View Source (since 1.5.0)
@spec break!(module(), atom(), arity(), non_neg_integer()) :: IEx.Pry.id()
Sets up a breakpoint in
module,
function and
arity with
the given number of
stops.
This function will instrument the given module and load a new version in memory with breakpoints at the given function and arity. If the module is recompiled, all breakpoints are lost.
When a breakpoint is reached, IEx will ask if you want to
pry
the given function and arity. In other words, this works similar
to
IEx.pry/0 as the running process becomes the evaluator of
IEx commands and is temporarily changed to have a custom group
leader. However, differently from
IEx.pry/0, aliases and imports
from the source code won't be available in the shell.
IEx helpers includes many conveniences related to breakpoints.
Below they are listed with the full module, such as
IEx.Helpers.breaks/0,
but remember it can be called directly as
breaks() inside IEx.
They are:
IEx.Helpers.break!/2- sets up a breakpoint for a given
Mod.fun/arity
IEx.Helpers.break!/4- sets up a breakpoint for the given module, function, arity
IEx.Helpers.breaks/0- prints all breakpoints and their IDs
IEx.Helpers.continue/0- continues until the next breakpoint in the same shell
IEx.Helpers.open/0- opens editor on the current breakpoint
IEx.Helpers.remove_breaks/0- removes all breakpoints in all modules
IEx.Helpers.remove_breaks/1- removes all breakpoints in a given module
IEx.Helpers.reset_break/1- sets the number of stops on the given ID to zero
IEx.Helpers.reset_break/3- sets the number of stops on the given module, function, arity to zero
IEx.Helpers.respawn/0- starts a new shell (breakpoints will ask for permission once more)
IEx.Helpers.whereami/1- shows the current location
By default, the number of stops in a breakpoint is 1. Any follow-up call won't stop the code execution unless another breakpoint is set.
Alternatively, the number of stops can be increased by passing the
stops
argument.
IEx.Helpers.reset_break/1 and
IEx.Helpers.reset_break/3
can be used to reset the number back to zero. Note the module remains
"instrumented" even after all stops on all breakpoints are consumed.
You can remove the instrumentation in a given module by calling
IEx.Helpers.remove_breaks/1 and on all modules by calling
IEx.Helpers.remove_breaks/0.
To exit a breakpoint, the developer can either invoke
continue(),
which will block the shell until the next breakpoint is found or
the process terminates, or invoke
respawn(), which starts a new IEx
shell, freeing up the pried one.
examples
Examples
The examples below will use
break!, assuming that you are setting
a breakpoint directly from your IEx shell. But you can set up a break
from anywhere by using the fully qualified name
IEx.break!.
The following sets up a breakpoint on
URI.decode_query/2:
break! URI, :decode_query, 2
This call will setup a breakpoint that stops once. To set a breakpoint that will stop 10 times:
break! URI, :decode_query, 2, 10
IEx.break!/2 is a convenience macro that allows breakpoints
to be given in the
Mod.fun/arity format:
break! URI.decode_query/2
Or to set a breakpoint that will stop 10 times:
break! URI.decode_query/2, 10
This function returns the breakpoint ID and will raise if there is an error setting up the breakpoint.
patterns-and-guards
Patterns and guards
IEx.break!/2 allows patterns to be given, triggering the
breakpoint only in some occasions. For example, to trigger
the breakpoint only when the first argument is the "foo=bar"
string:
break! URI.decode_query("foo=bar", _)
Or to trigger it whenever the second argument is a map with more than one element:
break! URI.decode_query(_, map) when map_size(map) > 0
Only a single break point can be set per function. So if you call
IEx.break! multiple times with different patterns, only the last
pattern is kept.
Note that, while patterns may be given to macros, remember that macros receive ASTs as arguments, and not values. For example, if you try to break on a macro with the following pattern:
break! MyModule.some_macro(pid) when pid == self()
This breakpoint will never be reached, because a macro never receives
a PID. Even if you call the macro as
MyModule.some_macro(self()),
the macro will receive the AST representing the
self() call, and not
the PID itself.
breaks-and-mix-test
Breaks and
mix test
To use
IEx.break!/4 during tests, you need to run
mix inside
the
iex command and pass the
--trace to
mix test to avoid running
into timeouts:
iex -S mix test --trace iex -S mix test path/to/file:line --trace
color(color, string)View Source
Returns
string escaped using the specified
color.
ANSI escapes in
string are not processed in any way.
configuration()View Source
Returns IEx configuration.
configure(options)View Source
Configures IEx.
The supported options are:
:colors
:inspect
:width
:history_size
:default_prompt
:continuation_prompt
:alive_prompt
:alive_continuation_prompt
:parser
They are discussed individually in the sections below.
colors
Colors
A keyword list that encapsulates all color settings used by the
shell. See documentation for the
IO.ANSI module for the list of
supported colors and attributes.
List of supported keys in the keyword list:
:enabled- boolean value that allows for switching the coloring on and off
:eval_result- color for an expression's resulting value
:eval_info- ... various informational messages
:eval_error- ... error messages
:eval_interrupt- ... interrupt messages
:stack_info- ... the stacktrace color
:blame_diff- ... when blaming source with no match
:ls_directory- ... for directory entries (ls helper)
:ls_device- ... device entries (ls helper)
When printing documentation, IEx will convert the Markdown documentation to ANSI as well. Colors for this can be configured via:
:doc_code- the attributes for code blocks (cyan, bright)
:doc_inline_code- inline code (cyan)
:doc_headings- h1 and h2 (yellow, bright)
:doc_title- the overall heading for the output (reverse, yellow, bright)
:doc_bold- (bright)
:doc_underline- (underline)
IEx will also color inspected expressions using the
:syntax_colors
option. Such can be disabled with:
IEx.configure(colors: [syntax_colors: false])
You can also configure the syntax colors, however, as desired:
IEx.configure(colors: [syntax_colors: [atom: :red]])
Configuration for most built-in data types are supported:
:atom,
:string,
:binary,
:list,
:number,
:boolean,
:nil, and others.
The default is:
[number: :magenta, atom: :cyan, string: :green, boolean: :magenta, nil: :magenta]
inspect
Inspect
A keyword list containing inspect options used by the shell when printing results of expression evaluation. Defaults to pretty formatting with a limit of 50 entries.
To show all entries, configure the limit to
:infinity:
IEx.configure(inspect: [limit: :infinity])
See
Inspect.Opts for the full list of options.
width
Width
An integer indicating the maximum number of columns to use in output.
The default value is 80 columns. The actual output width is the minimum
of this number and result of
:io.columns. This way you can configure IEx
to be your largest screen size and it should always take up the full width
of your current terminal screen.
history-size
History size
Number of expressions and their results to keep in the history. The value is an integer. When it is negative, the history is unlimited.
prompt
Prompt
This is an option determining the prompt displayed to the user when awaiting input.
The value is a keyword list with two possible keys representing prompt types:
:default_prompt- used when
Node.alive?/0returns
false
:continuation_prompt- used when
Node.alive?/0returns
falseand more input is expected
:alive_prompt- used when
Node.alive?/0returns
true
:alive_continuation_prompt- used when
Node.alive?/0returns
trueand more input is expected
The following values in the prompt string will be replaced appropriately:
%counter- the index of the history
%prefix- a prefix given by
IEx.Server
%node- the name of the local node
parser
Parser
This is an option determining the parser to use for IEx.
The parser is a "mfargs", which is a tuple with three elements:
the module name, the function name, and extra arguments to
be appended. The parser receives at least three arguments, the
current input as a string, the parsing options as a keyword list,
and the buffer as a string. It must return
{:ok, expr, buffer}
or
{:incomplete, buffer}.
If the parser raises, the buffer is reset to an empty string.
inspect_opts()View Source
Returns the options used for inspecting.
pry()View Source (macro)
Pries into the process environment.
This is useful for debugging a particular chunk of code
when executed by a particular process. The process becomes
the evaluator of IEx commands and is temporarily changed to
have a custom group leader. Those values are reverted by
calling
IEx.Helpers.respawn/0, which starts a new IEx shell,
freeing up the pried one.
When a process is pried, all code runs inside IEx and has
access to all imports and aliases from the original code.
However, the code is evaluated and therefore cannot access
private functions of the module being pried. Module functions
still need to be accessed via
Mod.fun(args).
Alternatively, you can use
IEx.break!/4 to setup a breakpoint
on a given module, function and arity you have no control of.
While
IEx.break!/4 is more flexible, it does not contain
information about imports and aliases from the source code.
examples
Examples
Let's suppose you want to investigate what is happening
with some particular function. By invoking
IEx.pry/0 from
the function, IEx will allow you to access its binding
(variables), verify its lexical information and access
the process information. Let's see an example:
import Enum, only: [map: 2] defmodule Adder do def add(a, b) do c = a + b require IEx; IEx.pry() end end
When invoking
Adder.add(1, 2), you will receive a message in
your shell to pry the given environment. By allowing it,
the shell will be reset and you gain access to all variables
and the lexical scope from above:
pry(1)> map([a, b, c], &IO.inspect(&1)) 1 2 3
Keep in mind that
IEx.pry/0 runs in the caller process,
blocking the caller during the evaluation cycle. The caller
process can be freed by calling
respawn/0, which starts a
new IEx evaluation cycle, letting this one go:
pry(2)> respawn() true Interactive Elixir - press Ctrl+C to exit (type h() ENTER for help)
Setting variables or importing modules in IEx does not affect the caller's environment. However, sending and receiving messages will change the process state.
pry-and-macros
Pry and macros
When setting up Pry inside a code defined by macros, such as:
defmacro __using__(_) do quote do def add(a, b) do c = a + b require IEx; IEx.pry() end end end
The variables defined inside
quote won't be available during
prying due to the hygiene mechanism in quoted expressions. The
hygiene mechanism changes the variable names in quoted expressions
so they don't collide with variables defined by the users of the
macros. Therefore the original names are not available.
pry-and-mix-test
Pry and
mix test
To use
IEx.pry/0 during tests, you need to run
mix inside
the
iex command and pass the
--trace to
mix test to avoid running
into timeouts:
iex -S mix test --trace iex -S mix test path/to/file:line --trace
started?()View Source
Returns
true if IEx was started,
false otherwise.
width()View Source
@spec width() :: pos_integer()
Returns the IEx width for printing.
Used by helpers and it has a default maximum cap of 80 chars. | https://hexdocs.pm/iex/master/IEx.html | CC-MAIN-2022-27 | refinedweb | 3,978 | 65.01 |
Would it be possible to add string as an option for the feature parameter of expandSelectionTo? It would function similar to brackets, selecting the text between the quotes. This makes it easy to replace the content of string literals without having to manually select everything.
You get a similar feature by pressing CTRL+SHIFT+SPACE BAR inside quoted strings. Does that help?
Ah, I guess you mean "programmatically".
ctrl+shift+space class calls expandSelectionTo scope, which has two differences compared to the proposed addition:1) it selects the quotes as well, which means you can't just start typing to replace the string2) if your cursor happens to be in a subscope inside the string, say a character literal, it will only select that as opposed to the entire string.
+1
Unfortunately, sublimator's code isn't entirely bugfree. For instance, in the test string "This doesn't work", selectString fails if the cursor is positioned anywhere after the single quote. This problem isn't easy. Consider something likefoo("lorem ipsum ' dolor ", sit, 'amet'),with the cursor positioned in dolor. We know the correct behaviour would be to select lorem...dolor, but to the algorithm dolor...sit is equally plausible since it has no awareness of scope. Perhaps this problem could be solved by also taking information from the syntax highlighter into account.
Here's a first stab at using syntax info for doing this. The obvious downside is that it doesn't work in plain text files or syntax schemes that don't adhere to the convention of naming strings string.quoted.double/single. Still, it should work for most languages (tried C, C++, C#, Java, Ruby, Python, Haskell and PHP).
import re
import sublime, sublimeplugin
class QuoteSelectCommand(sublimeplugin.TextCommand):
def run(self, view, args):
for region in view.sel():
syntax = view.syntaxName(region.begin())
if re.match(".*string.quoted.double", syntax): self.select(view, region, '"')
if re.match(".*string.quoted.single", syntax): self.select(view, region, "'")
def select(self, view, region, char):
begin = region.begin() - 1
end = region.begin()
while view.substr(begin) != char or view.substr(begin - 1) == '\\': begin -= 1
while view.substr(end) != char or view.substr(end - 1) == '\\': end += 1
view.sel().subtract(region)
view.sel().add(sublime.Region(begin + 1, end))
If anyone finds any cases where it doesn't work, please let me know. | https://forum.sublimetext.com/t/expandselectionto-string/856/3 | CC-MAIN-2016-36 | refinedweb | 391 | 52.76 |
BuildOrBuyTerms
Should I use somebody else's vocabulary of terms or make my own?
- Yes. ;-) see also: DontWorryBeCrappy. Perhaps more helpfully, see VocabularyMarket.
-. (discussion with respect to WWW2004 photo annotation project)
Comment: I suppose an obvious thing is that you should be able to suggest/specify in a specification and associated namespace what terms you would like/want someone to use from other vocabularies...
is cyc too big? Can I use just part of it without buying into all of it?
is cyc's license too scary?
will foaf go poof?
I worry about using RDFS, swap/contact, and the like; I think a HashURI is for referring to a part of a document, so GoodURIs for RDF properties shouldn't use them. What should I do?
I worry about foaf, dublin core, XMP, and the like; I think http URIs without fragment identifiers are for web pages (and things you can POST to), so GoodURIs for RDF properties should use fragment identifiers. What should I do? | https://www.w3.org/wiki/BuildOrBuyTerms | CC-MAIN-2016-50 | refinedweb | 167 | 66.33 |
This is part of a series I started in March 2008 - you may want to go back and look at older parts if you're new to this series.
I published the last article in this series in June 2010, after a long break. At the time of finally making a serious start to this part, it was April 2013, and as of the time I am editing and putting the final touches on this, it is July 2013, and I assume most of you have probably given up waiting by now.
I've kept meaning to publish more parts, and other parts of life have kept stopping it.
Incidentally, my son doesn't drool on the laptop anymore (see part 25) - now he hogs it to watch Youtube videos, particularly of anything Lego (which he then kindly requests that I build, often suggesting I build 2000-piece buildings with a pile of 50 or so bricks), since it's a great way of ensuring I give him my full attention when I can't use the laptop.
So my hacking is still limited in time, but I've finally managed to claw back enough to restart this series.
Anyway. I actually started writing several parts, before I finally got started on this one. As of publishing this article, I have 6 finished parts, and one halfway complete, in order to give me a buffer to prevent further gaps as long as this.
My intention is to post new parts every 5-6 weeks. I may adjust that up or down a bit as I see how regularly I manage to write additional parts to the series.
This article also represents a bit of a step to the side from the
define_method stuff I
was in the middle of doing last time. Partly because I want to start with a bit of a clean
slate, partly because better debugging support is long overdue, and partly because in
retrospect,
define_method was a big bite to chew over too soon - it requires a surprising
amount of scaffolding unless you want to do it in exceedingly hacky ways.
In fact, arguably going for
define_method was a mistake, especially given this series
original focus on "bottom up" development. We need a number of lower level features in place,
and I got too excited about going straight for a full Ruby compiler. Pretty much exactly
the type of complexity I wanted to avoid when I first set out by starting at the bottom.
I'll be back to
define_method and its pre-requisites later, but my current plan is
to seriously deal with it again somewhere around 8-10 parts out... Yeah.
If you've toyed with what has been covered in previous parts, you might at one point or other have despaired over how to debug the compiler output. Some debugger support would be nice. ANY debugger support.
Especially given that it's easy to make it output programs that will crash...
STABS is a debugging information format supported by GDB.
It's fairly simple to generate, and flexible enough to allow us to add enough information to generate reasonable stack backtraces.
Unfortunately, it's not easy to decipher by looking at gcc output. So we'll take a stab at adding some basic stabs information to an intentionally crashing C program, with the aid of some GDB documentation
#include <stdio.h> int foo() { int v; printf ("bar"); v = *(long *)0; } int main() { foo(); }
Compiling this with
gcc -gstabs -S -o test1.s test.c on a 32 bit Linux system gives a
reasonable baseline. We'll strip it down as far as we can, and then add support for
the few bits remaining to the Ruby compiler.
We want to do the minimum possible to make it possible to at least get a decent GDB backtrace, but not (for now) bother with all the complexities of proper type handling etc. that is needed for full gdb integration.
this is an example output from a GDB session with the above program:
$ gdb ./test nGNU gdb 6.8-debian Copyright (C) 2008 Free Software Foundation, Inc."... (gdb) run Starting program: /home/vidarh/src/compiler-experiments/test Program received signal SIGSEGV, Segmentation fault. 0x080483bb in foo () at test.c:8 v = *(long *)0; (gdb) bt #0 0x080483bb in foo () at test.c:8 #1 0x080483d8 in main () at test.c:12 (gdb)
This is pretty much the extent of what we'll aim for in the first round.
So lets start by looking at bits and pieces of the output of gcc with
-gstabs:
.file "test.c" .stabs "test.c",100,0,2,.Ltext0 .text .Ltext0:
It is pretty obvious that this tells us that the source file is test.c
But what does the 100,0,2,.Ltext0 mean? A lot can be said about Stabs, but "user friendly" does not spring to mind. Thankfully the documentation is quite decent, and some experimentation supplies the rest.
The .Ltext0 is simply a reference to the first address in the binary that stems from "test.c".
100 is the stabs symbol "
N_SO" which contains the name and path of the source
file.
The "2" is
N_SO_C - it designates the source language. C in this case. I
don't think there is one for Ruby, but we can either specify 0 for no
language, or, as we will adhere to C calling conventions for the most part,
we can use 2 in case it buys us anything extra from gcc (I honestly don't
know - I'm new to stabs too).
.stabs "int:t(0,1)=r(0,1);-2147483648;2147483647;",128,0,0,0
The next interesting entry is a bunch of these. They define types to allow the debugger to more precisely manipulate data from the program.
We're going to ignore these for now, since our initial focus is just getting the backtrace so we at least know where we're crashing.
Then this:
.stabs "/usr/include/stdio.h",130,0,0,0
130 is
N_BINCL. It marks the start of an include file.
N_BINCL is paired with
N_EINCL:
.stabn 162,0,0,0
N_BINCL and
N_EINCL can be nested. These are interesting for us since we'll
(for now at least) not entertain the idea of handling separate compilation
units, but rather generate a single static executable. As such, all "require"'d
files that we resolve at compile time (sigh, there we have an ugly beast
rearing it's head - figuring out what to load at compile time vs. runtime,
but that's for some later time) will be treated as include files.
In this case, all that gets included is type definitions.
Finally, after lots more type definitions and the string "bar", we get the
function
foo(), which looks like this full of stabs:
.stabs "foo:F(0,1)",36,0,0,foo .globl foo .type foo, @function foo: .stabn 68,0,3,.LM0-.LFBB1 .LM0: .LFBB1: pushl %ebp movl %esp, %ebp subl $24, %esp .stabn 68,0,5,.LM1-.LFBB1 .LM1: movl $.LC0, (%esp) call printf .stabn 68,0,7,.LM2-.LFBB1 .LM2: movl $0, %eax movl (%eax), %eax movl %eax, -4(%ebp) .stabn 68,0,8,.LM3-.LFBB1 .LM3: leave ret .size foo, .-foo .stabs "v:(0,1)",128,0,0,-4 .stabn 192,0,0,.LFBB1-.LFBB1
gdb will happily(?) rely on the "basic" function prolog we're already using, so we can ignore most of the new stubs, though it means gdb won't have information about the number of arguments.
The critical bit for us to get a basic backtrace is this:
foo: .stabn 68,0,3,.LM0-.LFBB1 .LM0: .LFBB1:
What this does is indicate line numbers. In this case the line number is 3.
The
.LM0 and
.LFBB1 nonsense is there to generate a relative file number.
.LFBB1 is a marker for the start of the function, and
.LM0 in this case
refers to the start of the line the stabs entry refers to.
This is really all we care about.
You will find all of these changes and the remaining bits and pieces on Github
The first step we take is to add a new node in the AST:
required. This node
is used to allow us to easily identify the inclusion of files later, during
processing of the AST, so that we can indicate the correct source filename
in the stabs:
def require q return true if @@requires[q] STDERR.puts "NOTICE: Statically requiring '#{q}'" # FIXME: Handle include path paths = rel_include_paths(q) f = nil paths.detect { |path| f = File.open(path) rescue nil } error("Unable to load '#{q}'") if !f s = Scanner.new(f) - @@requires[q] = Parser.new(s, @opts).parse(false) + pos = position + expr = Parser.new(s, @opts).parse(false) + @@requires[q] = E[pos,:required, expr] end
We also add the "required" node to the
@@keywords set of the
Compiler
class, and add a method to process it:
def compile_required(scope,exp) @e.include(exp.position.filename) do compile_exp(scope,exp) end end
We add the
include method to the
Emitter class to indicate just
that:
def include(filename) @section += 1 @out.emit(".stabs \"#{filename}\",130,0,0,0") ret = yield @out.emit(".stabn 162,0,0,0") @section -= 1 comment ("End include \"#{filename}\"") ret end
We also call this from
output_functions in the
Compiler
class, which is where we spit out all the functions we generate from
various methods etc:
# FIXME: Would it be better to output these grouped by source file? if func.body.is_a?(AST::Expr) @e.include(func.body.position.filename) do @e.func(name, func.rest?, func.body.position) { compile_eval_arg(FuncScope.new(func), func.body) } end else @e.func(name, func.rest?, nil) { compile_eval_arg(FuncScope.new(func), func.body) } end end
This bit ensures that we output the suitable
BINCL and
EINCL tags around function
definitions too.
However, we need more. This handles inclusion. But we also want line numbers.
We handle that in two different places. First in
compile_eval_arg
def compile_eval_arg(scope, arg) if arg.respond_to?(:position) && arg.position != nil pos = arg.position.inspect if pos != @lastpos @e.lineno(arg.position)
Notice that we only call this if a cached
@lastpos doesn't change. I'm not
sure if I'm happy with this. It intermingles the language handling with debugging.
There are a few alternatives here: * Move it into the Emitter. I see that as a bad idea because the Emitter will change per CPU target if I ever choose to retarget it. * Add a policy object that gets called every time, and that can be swapped out * "Just" move the logic to a separate method. * Add an intermediary between the lower level code generation of the Emitter, and higher level concerns, such as debug output etc.
I'm not yet decided, so I leave it at this for now.
We also add a similar line to
compile_exp:
@e.lineno(exp.position) if exp.respond_to?(:position) && exp.position Note in this case we always send the line number if we know if from the parser.
And there's where most of the mess you'll find in this parts commit comes from:
We want to ensure that the AST nodes store the position wherever possible. That means
moving more of the parser code from standard Array instances to
AST::Expr, or
E as it is aliases most places in the compiler.
This took some experimentation to get right, since it was by no means clear to me from the documentation exactly how it was meant to work, but gcc seems happy enough with this:
def lineno(position) @lineno ||= nil @linelabel ||= 0 if position.lineno != @lineno # Annoyingly, the linenumber stabs use relative addresses inside include sections # and absolute addresses outside of them. # if @section == 0 @out.emit(".stabn 68,0,#{position.lineno},.LM#{@linelabel}") else @out.emit(".stabn 68,0,#{position.lineno},.LM#{@linelabel} -.LFBB#{@curfunc}") end @out.label(".LM#{@linelabel}") @linelabel += 1 @lineno = position.lineno end end
To wrap everything up, we add some bookkeeping to the
func method of the Emitter, indicating the line numbers
of the function, as mentioned earlier:
+ def func(name, save_numargs = false, position = nil) + @out.emit(".stabs \"#{name}:F(0,0)\",36,0,0,#{name}") export(name, :function) if name.to_s[0] != ?. label(name) + + @funcnum ||= 1 + @curfunc = @funcnum + @funcnum += 1 + + lineno(position) if position + @out.label(".LFBB#{@curfunc}") + pushl(:ebp) movl(:esp, :ebp) pushl(:ebx) if save_numargs yield leave ret emit(".size", name.to_s, ".-#{name}") + @scopenum ||= 0 + @scopenum += 1 + label(".Lscope#{@scopenum}") + @out.emit(".stabs \"\",36,0,0,.Lscope#{@scopenum}-.LFBB#{@curfunc}") + @curfunc = nil end
And to
Emitter#main to indicate the source file:
- def main + def main(filename) + @funcnum = 1 + @curfunc = 0 if @basic_main return yield end + @out.emit(".file \"#{filename}\"") + @out.emit(".stabs \"#{File.dirname(filename)}/\",100,0,2,.Ltext0") + @out.emit(".stabs \"#{File.basename(filename)}\",100,0,2,.Ltext0") @out.emit(".text")
There are a bunch of additional things in the commit, and unfortunately I've not committed this piecemeal, as this change was made over a period of a year (!) while I was trying to get time to continue this serious, and repeatedly shelved it.
I'm happy to answer questions in the comments if there are things that are unclear. Thank you for the kind encouragement over my hiatus...
As for what is next, the next four parts will cover replacing
runtime.c with code
generation and method implementations, partly because I want to get rid of
runtime.c, partly because functionally, the more complete method dispatch
and the more we try to write code in Ruby, the current handling of it fails
horribly because we try to intermingle code in the low level s-expression
based intermediate representation and higher level Ruby code.
Replacing it should suddenly make quite a bit more code work, and make further
extensions easier to make without constantly dipping down into the murky land
of
%s()...
</http:> | https://hokstad.com/compiler/26-stabs | CC-MAIN-2021-21 | refinedweb | 2,327 | 63.9 |
Ahh thanks everyone for helping me i guess i am done here because i got it to fully function :)
Ahh thanks everyone for helping me i guess i am done here because i got it to fully function :)
Ok thanks guys i got it all figured out. So wonder if i can ask another question here instead of making another thread?
If so here goes,
Assuming that i typed something into a textfield...
As you can see from the desired outcome picture, i am supposed to write codes that will eventually lead to exactly the same thing as the picture.
So basically when i run, many things like the...
Umm no. Those are just part of the codes. What i am showing you there are the codes that are causing problems.
This is the full one:
import javax.swing.*;
import java.awt.*;
import...
Hey guys this is my first time here. I was recommended by my friends to visit this site should i have any problems with Java programming and
here i am and i need some help regarding my codes. I cant... | http://www.javaprogrammingforums.com/search.php?s=97bcbe69367f9ba1a2d239fff1b97685&searchid=1365146 | CC-MAIN-2015-06 | refinedweb | 183 | 78.48 |
0
Hi there,
So I am trying to make a program that will allow me to input multiple users and be able to store data under their names.
My problem is that I don't know how to make it so that the user can input as many names as he/she wants to.
I created a while loop that stated that until the user typed in "n", it would keep asking to add names but I don't know where or how I would be able to store those names.
Here is the code that I have so far (I know it's not finished and there are still some mistakes):
import java.util.Scanner; public class SheetCounter { static Scanner userin = new Scanner (System.in); public static void Main (String[] args) { System.out.println("Welcome to the -----"); System.out.println("Please input the name of a user you wish to add:"); String EmployeeA = userin.nextLine(); int a = 0; while (a == 0) { System.out.println("Please input the name of another user you wish to user"); System.out.println("If you do not have any more user to add, please type n:"); String EmployeeB = userin.nextLine(); if (EmployeeB.equals("n")) { a = 1; } } System.out.println("Ok, so you have added"); } } | https://www.daniweb.com/programming/software-development/threads/461656/java-program-help | CC-MAIN-2018-13 | refinedweb | 210 | 75.1 |
GP.
Developing GPIO Zero
Nearly two years ago, I started the GPIO Zero project as a simple wrapper around the low-level RPi.GPIO library. I wanted to create a simpler way to control GPIO-connected devices in Python, based on three years’ experience of training teachers, running workshops, and building projects. The idea grew over time, and the more we built for our Python library, the more sophisticated and powerful it became.
One of the great things about Python is that it’s a multi-paradigm programming language. You can write code in a number of different styles, according to your needs. You don’t have to write classes, but you can if you need them. There are functional programming tools available, but beginners get by without them. Importantly, the more advanced features of the language are not a barrier to entry.
Become a more advanced programmer
As a beginner to programming, you usually start by writing procedural programs, in which the flow moves from top to bottom. Then you’ll probably add loops and create your own functions. Your next step might be to start using libraries which introduce new patterns that operate in a different manner to what you’ve written before, for example threaded callbacks (event-driven programming). You might move on to object-oriented programming, extending the functionality of classes provided by other libraries, and starting to write your own classes. Occasionally, you may make use of tools created with functional programming techniques.
Take control of the buttons in your life
It’s much the same with GPIO Zero: you can start using it very easily, and we’ve made it simple to progress along the learning curve towards more advanced programming techniques. For example, if you want to make a push button control an LED, the easiest way to do this is via procedural programming using a
while loop:
from gpiozero import LED, Button led = LED(17) button = Button(2) while True: if button.is_pressed: led.on() else: led.off()
But another way to achieve the same thing is to use events:
from gpiozero import LED, Button from signal import pause led = LED(17) button = Button(2) button.when_pressed = led.on button.when_released = led.off pause()
You could even use a declarative approach, and set the LED’s behaviour in a single line:
from gpiozero import LED, Button from signal import pause led = LED(17) button = Button(2) led.source = button.values pause()
You will find that using the procedural approach is a great start, but at some point you’ll hit a limit, and will have to try a different approach. The example above can be approach in several programming styles. However, if you’d like to control a wider range of devices or a more complex system, you need to carefully consider which style works best for what you want to achieve. Being able to choose the right programming style for a task is a skill in itself.
Source/values properties
So how does the
led.source = button.values thing actually work?
Every GPIO Zero device has a
.value property. For example, you can read a button’s state (
True or
False), and read or set an LED’s state (so
led.value = True is the same as
led.on()). Since LEDs and buttons operate with the same value set (
True and
False), you could say
led.value = button.value. However, this only sets the LED to match the button once. If you wanted it to always match the button’s state, you’d have to use a
while loop. To make things easier, we came up with a way of telling devices they’re connected: we added a
.values property to all devices, and a
.source to output devices. Now, a loop is no longer necessary, because this will do the job:
led.source = button.values
This is a simple approach to connecting devices using a declarative style of programming. In one single line, we declare that the LED should get its values from the button, i.e. when the button is pressed, the LED should be on. You can even mix the procedural with the declarative style: at one stage of the program, the LED could be set to match the button, while in the next stage it could just be blinking, and finally it might return back to its original state.
These additions are useful for connecting other devices as well. For example, a PWMLED (LED with variable brightness) has a value between 0 and 1, and so does a potentiometer connected via an ADC (analogue-digital converter) such as the MCP3008. The new GPIO Zero update allows you to say
led.source = pot.values, and then twist the potentiometer to control the brightness of the LED.
But what if you want to do something more complex, like connect two devices with different value sets or combine multiple inputs?
We provide a set of device source tools, which allow you to process values as they flow from one device to another. They also let you send in artificial values such as random data, and you can even write your own functions to generate values to pass to a device’s source. For example, to control a motor’s speed with a potentiometer, you could use this code:
from gpiozero import Motor, MCP3008 from signal import pause motor = Motor(20, 21) pot = MCP3008() motor.source = pot.values pause()
This works, but it will only drive the motor forwards. If you wanted the potentiometer to drive it forwards and backwards, you’d use the
scaled tool to scale its values to a range of -1 to 1:
from gpiozero import Motor, MCP3008 from gpiozero.tools import scaled from signal import pause motor = Motor(20, 21) pot = MCP3008() motor.source = scaled(pot.values, -1, 1) pause()
And to separately control a robot’s left and right motor speeds with two potentiometers, you could do this:
from gpiozero import Robot, MCP3008 from signal import pause robot = Robot(left=(2, 3), right=(4, 5)) left = MCP3008(0) right = MCP3008(1) robot.source = zip(left.values, right.values) pause()
GPIO Zero and Blue Dot
Martin O’Hanlon created a Python library called Blue Dot which allows you to use your Android device to remotely control things on your Raspberry Pi. The API is very similar to GPIO Zero, and it even incorporates the value/values properties, which means you can hook it up to GPIO devices easily:
from bluedot import BlueDot from gpiozero import LED from signal import pause bd = BlueDot() led = LED(17) led.source = bd.values pause()
We even included a couple of Blue Dot examples in our recipes.
Read more in this source/values tutorial from The MagPi, and on the source/values documentation page.
Remote GPIO control
GPIO Zero supports multiple low-level GPIO libraries. We use RPi.GPIO by default, but you can choose to use RPIO or pigpio instead. The pigpio library supports remote connections, so you can run GPIO Zero on one Raspberry Pi to control the GPIO pins of another, or run code on a PC (running Windows, Mac, or Linux) to remotely control the pins of a Pi on the same network. You can even control two or more Pis at once!
If you’re using Raspbian on a Raspberry Pi (or a PC running our x86 Raspbian OS), you have everything you need to remotely control GPIO. If you’re on a PC running Windows, Mac, or Linux, you just need to install gpiozero and pigpio using pip. See our guide on configuring remote GPIO.
There are a number of different ways to use remote pins:
- Set the default pin factory and remote IP address with environment variables:
$ GPIOZERO_PIN_FACTORY=pigpio PIGPIO_ADDR=192.168.1.2 python3 blink.py
- Set the default pin factory in your script:
import gpiozero from gpiozero import LED from gpiozero.pins.pigpio import PiGPIOFactory gpiozero.Device.pin_factory = PiGPIOFactory(host='192.168.1.2') led = LED(17)
- The
pin_factorykeyword argument allows you to use multiple Pis in the same script:)
This is a really powerful feature! For more, read this remote GPIO tutorial in The MagPi, and check out the remote GPIO recipes in our documentation.
GPIO Zero on your PC
GPIO Zero doesn’t have any dependencies, so you can install it on your PC using pip. In addition to the API’s remote GPIO control, you can use its ‘mock’ pin factory on your PC. We originally created the mock pin feature for the GPIO Zero test suite, but we found that it’s really useful to be able to test GPIO Zero code works without running it on real hardware:
$
You can also use the pinout command line tool if you set your pin factory to ‘mock’. It gives you a Pi 3 diagram by default, but you can supply a revision code to see information about other Pi models. For example, to use the pinout tool for the original 256MB Model B, just type
pinout -r 2.
GPIO Zero documentation and resources
On the API’s website, we provide beginner recipes and advanced recipes, and we have added remote GPIO configuration including PC/Mac/Linux and Pi Zero OTG, and a section of GPIO recipes. There are also new sections on source/values, command-line tools, FAQs, Pi information and library development.
You’ll find plenty of cool projects using GPIO Zero in our learning resources. For example, you could check out the one that introduces physical computing with Python and get stuck in! We even provide a GPIO Zero cheat sheet you can download and print.
There are great GPIO Zero tutorials and projects in The MagPi magazine every month. Moreover, they also publish Simple Electronics with GPIO Zero, a book which collects a series of tutorials useful for building your knowledge of physical computing. And the best thing is, you can download it, and all magazine issues, for free!
Check out the API documentation and read more about what’s new in GPIO Zero on my blog. We have lots planned for the next release. Watch this space.
Get building!
The world of physical computing is at your fingertips! Are you feeling inspired?
If you’ve never tried your hand on physical computing, our Build a robot buggy learning resource is the perfect place to start! It’s your step-by-step guide for building a simple robot controlled with the help of GPIO Zero.
If you have a gee-whizz idea for an electronics project, do share it with us below. And if you’re currently working on a cool build and would like to show us how it’s going, pop a link to it in the comments. | https://www.raspberrypi.org/blog/gpio-zero-update/?replytocom=1313472 | CC-MAIN-2017-43 | refinedweb | 1,794 | 60.95 |
Program the Cloud with 12 Pulumi Pearls
In this post, we’ll look at 12 “pearls” – bite-sized code snippets – that demonstrate some fun ways you can program the cloud using Pulumi. In my introductory post, I mentioned a few of my “favorite things”. Now let’s dive into a few specifics, from multi-cloud to cloud-specific, spanning containers, serverless, and infrastructure, and generally highlighting why using familiar languages is so empowering for cloud scenarios. Since Pulumi lets you do infrastructure-as-code from the lowest-level to the highest, we will cover a lot of interesting ground in short order.
If you want to follow along and try some of this out, Pulumi is
open source on GitHub, free to download
and use, and the quickstart will acquaint you with the CLI. Most of
the examples are directly runnable and available in our examples repo, and are just a
pulumi up away, unlike other approaches that
require you to point-and-click around in your cloud’s console, and/or
author reams of yucky YAML. And you get to use familiar languages!
Here is an index of the pearls in case you want to dive straight into one in particular:
- Declare cloud infra using a familiar language (with loops!)
- Make a reusable component out of your cloud infra
- Go serverless without the YAML
- Capture state in your serverless funcs, like real lambdas
- Simple serverless cron jobs
- Run Express-like serverless SPAs and REST APIs at near zero cost
- Deploy production containers without the fuss
- Use containers without Dockerfiles
- Invoke a long-running container as a task
- Use code to avoid hard-coding config
- Use config to enable multi-instantiation and code reuse
- Give your components runtime APIs
Even if you’re uninterested in low-level infrastructure, it can be fun to work through these examples; it’s “turtles all the way down” with Pulumi and doing so can help understand how the system works. And similarly, it can be fun to see the high-level scenarios these building blocks facilitate, even if you just want to stand up containers and functions.
And with that, let’s dive in.
Infrastructure
Familiar Languages
[ Runnable Example ]
Pulumi gives you a way to express infrastructure configuration using your favorite programming language. In this article, we’ll use TypeScript on Node.js, as it delivers great productivity by blending dynamic and static typing with the NPM ecosystem of reusable packages.
At the lowest layer, there are packages for all major cloud providers –
AWS,
Azure,
Google Cloud – in addition to
Kubernetes and
OpenStack. So, if you want
an EC2 instance, Azure CosmosDB, or Kubernetes Pod, you just
new up an object. From there, Pulumi uses an
infrastructure-as-code approach similar to using AWS CloudFormation,
Azure Resource Manager, Google Resource Manager, Kubernetes or Helm
YAML, or Terraform – just without the YAML DSLs.
The strength of using a language truly begins to shine when you go
beyond
new, however. Using a language gives you
control structures, like for loops and if branches. This is easy to take
for granted, but compared to existing YAML DSLs, it is very powerful.
For example, let’s create three EC2 VMs and export their IP addresses. Normally you’d need to copy-and-paste, however for loops to the rescue!
index.ts:
import * as aws from "@pulumi/aws"; let webSg = new aws.ec2.SecurityGroup("web-secgrp", { ingress: [ { protocol: "tcp", fromPort: 80, toPort: 80, cidrBlocks: ["0.0.0.0/0"] }, ], }); let webServers = []; for (let i = 0; i < 3; i++) { webServers.push(new aws.ec2.Instance(`web-server-${i}`, { instanceType: "t2.micro", ami: "ami-6869aa05", // us-east-1-only securityGroups: [ webSg.name ], userData: `#!/bin/bashn` + `echo 'Hello, World #${i}!' > index.htmln` + `nohup python -m SimpleHTTPServer 80 &n`, })); } export let publicHostnames = webServers.map(s => s.publicDns);
This provisions three web servers, each of which runs a simple Python webserver.
Of course, this can unlock far more sophisticated scenarios. For example, our own AWS Infrastructure package offers core AWS infrastructure components using AWS’s own best practices, and a community member built an AWS Virtual Private Cloud (VPC) component that automatically distributes subnets across all availability zones in a region, including smartly calculating the CIDR addresses, hiding lots of the messy details of AWS networking.
Reusable Components
[ Runnable Example ]
Speaking of components, this is another benefit of using familiar languages: abstraction. This includes the ability to hide uninteresting details through encapsulation, and create bigger things out of smaller things, a key to how we’ve become so productive with programming languages generally over the years. Applied to infrastructure, this enables some powerful scenarios.
For instance, perhaps you want a standard base class for all servers in your organization, enforcing security policy or even just naming conventions. Or maybe you want to ensure there is an Envoy proxy sidecar for all of your Kubernetes pods. No matter the scenario, we call these things “components” and Pulumi has a rich model that supports parents and children.
To stick with the running example, let’s make a WebServer class that internally creates the EC2 VM so that callers don’t need to know messy details like how to create and configure a SecurityGroup and choosing the right image:
web.ts:
import * as aws from "@pulumi/aw: "ami-6869aa05", // us-east-1-only securityGroups: [ webSg.name ], userData: `#!/bin/bashn` + `echo 'Hello from ${name}!' > index.htmln` + `nohup python -m SimpleHTTPServer 80 &n`, }); } }
Now we can go back to our original program and tidy it up a bit:
index.ts:
import { WebServer } from "./web"; let webServers = []; for (let i = 0; i < 3; i++) { webServers.push(new WebServer(`web-server-${i}`)); } export let publicHostnames = webServers.map(s => s.vm.publicDns);
Not only is the result simpler, but we now have a way to divvy up responsibilities within a team, helping Dev and DevOps to work better together.
This example used purely local components, but you can of course publish and consume any old packages from your favorite package manager – including private registries for your own team.
We will return to these examples later on and improve them to be more reusable through configuration, however let’s first tour some fun serverless and container pearls.
Serverless
No YAML
[ Runnable Example ]
Let’s shift gears and jump into serverless. Pulumi is unique in that its goal is to be a platform for all aspects of modern cloud programming, so that includes serverless, in addition to the abovementioned infrastructure examples and the soon-to-be-mentioned container ones. Most real-world examples we see in fact mix all of these things together in the same program.
Because of the way it uses familiar languages, there are great benefits to serverless programming in Pulumi. No YAML required – just write lambdas in your favorite language, and our compiler/runtime magic will deal with them. But first, let’s start simple.
The AWS Serverless
package provides event sources for all of the possible AWS Lambda
triggers. This leverages the
aws.serverless.Function abstraction that takes a
lambda in your language and translates it into a package suitable for
uploading to AWS. No need to embed code in YAML files, manually upload
to S3, etc. Pulumi handles all of this including versioning.
Let’s look at a simple example that simply posts a Slack message for every new message that arrives in an SQS queue (a new capability recently added to AWS). The way you express serverless functions in Pulumi is by writing ordinary lambdas and the way you hook them up to event sources is by using an event-driven style on your existing cloud resources:
index.ts:;
The code and instructions for running this example are available in our examples repo.
Serverless programs written in this style feel just like your favorite event-driven frameworks, and – because these are just ordinary lambdas in your language of choice – they compose in all the usual ways, unlocking some fascinating future possibilities (like serverless Spark and/or RxJS). Behind the scenes, Pulumi is doing the hard work to extract out the body of the function, rewrite it minimally but as needed to wire it up to AWS Lambda, and package it up. Subsequent deployments are as easy as the first one, as Pulumi does diffing to compute the minimal deltas.
Not everybody will want to mix infrastructure definitions and runtime code like this. Because these are just ordinary programs, you are free to split code into submodules and structure your workspace as you see fit. In fact, you can create distinct stacks for the different pieces.
This example is AWS-specific, however the Pulumi Cloud Framework offers several multi-cloud serverless (and container) capabilities. We will see some examples of that package in action below, however being able to target your cloud of choice directly means you can use all of its underlying features.
Real Lambdas
[ Runnable Example ]
Pulumi also lets you capture state in your serverless functions. This is one of the major advantages to this approach; normally you’d need to awkwardly arrange for such state to be passed into your function through some sideband mechanism, such as environment variables.
In Pulumi, we just capture state. Just like in your favorite language.
Let’s say we want the Slack information above to be configurable – a good idea, since the Slack token is a secret that should be configured using the –secret flag. To do so, first let’s create a config module:
config.ts:
import * as pulumi from "@pulumi/pulumi"; let config = new pulumi.Config(pulumi.getProject()); export let slackChannel = config.get("slackChannel") || "#general", export let slackToken: config.require("slackToken");
And now let’s go back to our above program, and use the config module for these properties. Notice that we simply capture a reference to the config module – that’s it!
index.ts:
import * as config from "./config";;
We often call this “capture by serialization” because, of course, the captured state is marshaled into the serverless function’s package, and then unmarshaled at runtime at the time of use. The semantics of capture are specific to each language, but for JavaScript, we do a deep serialization of the object, including its prototype chain, so that the full structure is preserved.
Because of this, functions are even available. We use this capability to let you capture resources by-value that internally have references to a live cloud resource. We will see that next in our serverless cron job example.
Cron Jobs
[ Runnable Example ]
Pulumi’s Cloud Framework has an ultra-straightforward:
index.ts:()}`); });
To make things slightly more interesting, let’s write a serverless timer that fetches the Hacker News homepage every hour and stashes it into a document database:
index.ts:(); });
We are using the ability to capture a reference to our
cloud.Table and call functions on it, like
insert. Of course, the body of that function can
do absolutely anything that you’d like.
REST APIs
[ Runnable Example ]
Us Node.js programmers love web frameworks, whether that be serving static content using a single page application (SPA) built using React.js, Vue.js, or Angular.js, a program built using dynamic server-side logic using Express.js, or some combination thereof. Serverless offers a way to run these programs at incredible density and low cost, often reducing a VM- or container-based solution to 1/10th its cost (or better). The problem is, this usually means abandoning productive frameworks, and resorting to YAML, hand-authoring Swagger files, and configuring complex API Gateway machinery – all foreign concepts when you just want to run a website.
Pulumi lets you just write code to host both static and dynamic content
simply, using its cross-cloud framework’s cloud.API abstraction. It has
been designed to have a familiar Node.js feel. The following example
serves all static content underneath my www directory at the root, and
provides a simple GET endpoint at
/hello that
returns a
{ hello: "World!" } JSON object:
index.ts:
import * as cloud from "@pulumi/cloud"; // Create a new API endpoint: let app = new cloud.API("my-app"); // Serve static files from the `www` folder (using AWS S3): app.static("/", "www"); // Serve a simple REST API on `GET /hello` (using AWS Lambda): app.get("/hello", (req, res) => res.json({ hello: "World!" })); // Export the public URL for the HTTP service: export let url = app.publish().url;
All of the usual verbs are available –
patch, etc. – as is support for middleware.
The structure of my local filesystem will demonstrate how some of this ties together:
. ├── Pulumi.yaml ├── index.ts ├── package.json └── www ├── favicon.png └── index.html 1 directory, 5 files
Again, all we need to do is
pulumi up, and Pulumi
will figure out what has changed. So, if we are building an SPA using
React.js, etc., then we would simply have a build step that updates the
content, and the next time we run
pulumi up, it
will figure out what has changed and make the minimal set of updates.
Similarly, if we edit a dynamic function, it will update just the
function.
As you can imagine, things get fun when you start mixing scenarios. Say we wanted a web frontend to our Hacker News timer fetcher above. Thanks to the way we can simply capture a reference to the snapshots database and use it in the body of our API, this is extremely trivial.
Per the earlier conversation around mixing infrastructure and application code, some folks prefer to split the routes from the application code. This is a fine convention, and easy to do:
index.ts:
import * as cloud from "@pulumi/cloud"; import * as routes from "./app/routes"; // Create an API like before, but use a routes module instead of defining inline: let app = new cloud.API("my-app"); app.get("/hello", routes.hello); export let url = app.publish().url;
For now, Pulumi only offers an AWS implementation of these APIs, but more clouds are on their way!
Containers
Easy Deployment
[ Runnable Example ]
Let’s shift gears again and take a look at containers. Pulumi supports programming against raw container orchestrators – Amazon’s ECS, Azure’s ACS, Google Cloud’s GKE, Kubernetes directly, and so on – using the cloud resources directly. In this mode, Pulumi is entirely unopinionated about how containers are built, published, and deployed to your orchestrator.
It is important that Pulumi supports that low-level approach, and is what distinguishes it compared to PaaS-like offerings. This entails significant spelunking at a level that is only loosely connected to the task of standing up a container, however, which can be time-consuming and frustrating for many developers. To make this common case easier, Pulumi also offers higher-level abstractions to make these common cases easier, similar in spirit to Docker Compose, except that you can mix these abstractions with all your other cloud resources.
For example, to create a load balanced Nginx container using an image from the Docker Hub:
index.ts:
import * as cloud from "@pulumi/cloud"; let nginx = new cloud.Service("nginx", { image: "nginx", ports: [{ port: 80 }], replicas: 2, }); export let url = nginx.defaultEndpoint;
This is all you need to run Nginx with 2 load balanced replicas
listening on port 80. By default, this will run in Fargate when
targeting AWS, which means you can skip the complications of configuring
an orchestrator. After running
pulumi up, the
auto-assigned URL will be printed.
The image directive supports any normal Docker image URL, so private registries work just as well as the default public Docker Hub. And there are a number of other supported properties for memory and CPU constraints, advanced port mapping, and volumes.
Now things get a bit more interesting. Let’s say we wanted to build our own custom container instead. Normally that would mean defining a Dockerfile, provisioning a private registry, and manually building and publishing your image to the registry, and then consuming that container image from the registry. That’s a lot of boilerplate scripting!
Pulumi unifies all container building, publishing, and consumption
underneath a simple
pulumi up:
index.ts:
import * as cloud from "@pulumi/cloud"; let nginx = new cloud.Service("nginx", { build: ".", ports: [{ port: 80 }], replicas: 2, }); export let url = nginx.defaultEndpoint;
Dockerfile:
FROM nginx COPY ./www /usr/share/nginx/html
This is trivial Dockerfile that derives from the nginx base image and copies the ./www directory into the Nginx HTML target so that it will be served up. This is our directory structure:
. ├── Dockerfile ├── Pulumi.yaml ├── index.ts ├── package.json └── www ├── favicon.png └── index.html 1 directory, 5 files
Of course, this Dockerfile could be arbitrarily complex, using any Docker image.
No Dockerfiles
[ Runnable Example ]
The above example showed you how to create services that use Docker containers, either via a pre-built image stored in a registry like the Docker Hub, or by building one from a Dockerfile. The cloud.Service class supports a third possibility, which is really fun, as it takes advantage of Pulumi’s serverless programming model earlier to define a container and its service.
Imagine we want to define a simple Node.js webserver rather than using Nginx like this. Perhaps it uses Express.js. For this blog post, however, let’s stick with the most basic http-module-based webserver:
index.ts:
import * as cloud from "@pulumi/cloud"; let www = new cloud.Service("www", { function: () => { let rand = Math.random(); require("http").createServer((req, res) => { res.end(`Hello, world! (from ${rand})`); }).listen(80); }, ports: [{ port: 80 }] memory: 128, replicas: 2, }); export let url =;
This code defines a load balanced service, backed by a container that
Pulumi builds on your behalf out of the body of the function provided in
the program, all done with a simple
pulumi up
gesture. This function, of course, can close over other state just like
the earlier serverless examples, including cloud resources, making it as
easy as can be to connect your microservices.
Long Running Containers as Tasks
[ Runnable Example ]
The above examples are great if what you want is a load balanced, long-running service. Sometimes a container is useful simply for executing a long-running task, or one that has very specific requirements about its execution environment (such as a specific base image).
For those cases, a cloud.Task is just what the doctor ordered. Task supports all the same construction techniques as Service, so you can give it a pre-built image, a build directive, or an inline function. For purposes of illustration, let’s build a custom Dockerfile that performs an FFMPEG transformation, to extract a thumbnail anytime someone adds a video to a bucket:
index.ts:;
Dockerfile:
FROM jrottenberg/ffmpeg RUN apt-get update && apt-get install python-dev python-pip -y && apt-get clean RUN pip install awscli WORKDIR /tmp/workdir ENTRYPOINT echo "Starting ffmpeg task... " && echo "Copying video from s3://${S3_BUCKET}/${INPUT_VIDEO} to ${INPUT_VIDEO}..." && aws s3 cp s3://${S3_BUCKET}/${INPUT_VIDEO} ./${INPUT_VIDEO} && ffmpeg -v error -i ./${INPUT_VIDEO} -ss ${TIME_OFFSET} -vframes 1 -f image2 -an -y ${OUTPUT_FILE} && echo "Copying thumbnail to S3://${S3_BUCKET}/${OUTPUT_FILE} ..." && aws s3 cp ./${OUTPUT_FILE} s3://${S3_BUCKET}/${OUTPUT_FILE}
Notice that, just like before, this is backed by an ordinary Dockerfile. This example actually showcases serverless and containers living alongside one another in harmony. Notice how we kick off the task – simply by capturing a reference to the Task from the serverless event handler, and invoking its run method. This leverages Pulumi’s ability to give resources like Tasks custom APIs that can be invoked at runtime, something we will return to again later on.
General Tips and Tricks
Avoid Hard-Coding Config
Let’s return to our webserver example from earlier. Unfortunately, this
code will only work in one region, because we hard-coded the
"ami-6869aa05" image name (AMI). (Image names in
AWS are region-specific.) In general, we prefer to build Pulumi programs
that can be multi-instantiated across different regions. Pulumi’s stacks
model streamlines this workflow, making it easy to spin up fresh copies
of your entire application and/or infrastructure when you need to scale,
while also reducing friction during development and testing. Such
hard-coding is a definite code smell and impediment, however.
Because we are using a familiar language, we can do anything that general-purpose languages can do. That includes dynamically querying sources of information which, in this case, can be used to avoid hard-coding. We can even use the AWS SDK, which gives us full access to all AWS functionality:
ami.ts:
import * as aws from "@pulumi/aws"; export function getLinuxAmi(): Promise<string> { return new Promise<string>((resolve, reject) => { let ec2 = new (require("aws-sdk")).EC2({ region: aws.config.requireRegion() }); ec2.describeImages( { Owners: [ "amazon" ], Filters: [{ Name: "name", Values: [ "amzn-ami-hvm-????.??.?.x86_64-gp2" ], }], }, (err: any, data: any) => { if (err) { reject(err); } else { let newestImage: string | undefined; let newestImageDate: number | undefined; for (let image of data.Images) { let imageDate = Date.parse(image.CreationDate); if (!newestImage || !newestImageDate || imageDate > newestImageDate) { newestImage = image.ImageId; newestImageDate = imageDate; } } if (newestImage) { console.log(`AMI: ${newestImage} (${newestImageDate})`); resolve(newestImage); } else { reject("No Linux AMI found for the current region"); } } }, ); }); }
I’ll be the first to admit that this is code that only a mother could love. Even better would be to wrap it up in a reusable NPM package that others can use without the boilerplate! Either way, it’s very powerful to have the full capabilities of a language at our fingertips, as this sort of thing simply isn’t possible in other infra-as-code solutions.
Now that we have this function, we can revisit the way we set the AMI property on our VMs:
web.ts:
import * as aws from "@pulumi/aws"; import { getLinuxAmi } from "./am: getLinuxAmi(), securityGroups: [ webSg.name ], userData: `#!/bin/bashn` + `echo 'Hello from ${name}!' > index.htmln` + `nohup python -m SimpleHTTPServer 80 &n`, }); } }
Given this change, we can safely deploy our WebServer to any AWS region.
Multi-Instantiation and Code Reuse
In the webserver example, we used the
aws.config.requireRegion() function to obtain the
configured AWS region. Using configuration in this manner lets us
multi-instantiate stacks; in other words, to easily stand up multiple
copies of a service, application, or infrastructure.
We can even make the quantity configurable using Pulumi’s config system:
index.ts:
import { WebServer } from "./web"; import { Config, getProject } from "@pulumi/pulumi"; let config = new Config(getProject()); let webServers = []; let webServersCount = config.getNumber("count") || 3; for (let i = 0; i < webServersCount; i++) { webServers.push(new WebServer(`web-server-${i}`)); } export let publicHostnames = webServers.map(s => s.vm.publicDns);
Given this specific program, we can easily change the number of servers created from the default of three, to something larger:
$ pulumi config set count 7
There are plenty of opportunities for configuration like this, like the machine size. By making such settings configurable, different environments can easily have different settings, while still sharing the same code beneath them, eliminating copy-and-paste and its associated pitfalls.
Give Components Runtime APIs
[ Runnable Example ]
As our final example, let’s see how to give your own components APIs that can be invoked at runtime. We’ve already seen this a few times now, such as managing data in a cloud.Table that has been captured in a lambda, and cloud.Task’s run method. Pulumi is built to be extensible, so you can define your own abstractions just like these with APIs too.
For this example, let’s take a simple Redis cache service and turn it
into a component. After doing so, we can then add simple
get/
set APIs on it that let
you interact with the cache at runtime in simple ways. By providing this
sort of abstraction, we open up interesting possibilities. For instance,
our default implementation can use a custom container-backed service,
via
cloud.Service, but opt to use a simpler hosted
solution when running in a public cloud – AWS ElastiCache, Azure Redis
Cache, or Memorystore in Google Cloud.
To make our component, we will simply allocate a
cloud.Service in the constructor, taking an
optional memory parameter to control its memory reservation. We are
using configuration to read the Redis password using Pulumi’s built-in
secrets mechanism. To give that component APIs, we just define methods
on the class that access Redis through its own NPM package, and that’s
it! The way lambda capture works will ensure that these functions are
accessible:
cache.ts:
import * as cloud from "@pulumi/cloud"; import * as config from "./config"; // A simple cache abstraction that wraps Redis. export class Cache { public readonly get: (key: string) => Promise<string>; public readonly set: (key: string, value: string) => Promise<void>; private readonly redis: cloud.Service; constructor(name: string, memory: number = 128) { this.redis = new cloud.Service(name, { image: "redis:alpine", memory: memory, ports: [{ port: 6379 }], command: ["redis-server", "--requirepass", config.redisPassword], }); } public async get(key: string): Promise<string> { let client = await this.createRedisClient(); return new Promise<string>((resolve, reject) => { client.get(key, (err: any, v: any) => { if (err) reject(err); else resolve(v); }); }); } public async set(key: string, value: string): Promise<void> { let client = await this.createRedisClient(); return new Promise<void>((resolve, reject) => { client.set(key, value, (err: any, v: any) => { if (err) reject(err); else resolve(); }); }); } private async createRedisClient(): Promise<any> { let ep = (await this.redis.defaultEndpoint).get(); return require("redis").createClient( ep.port, ep.hostname, { password: config.redisPassword }); } } }
Because this is just a class, we have all the standard programming facilities available to us. If we wanted to specialize it to use our cloud’s hosted Redis services, we could do that using the standard techniques, including conditional code or, slightly more elegantly, using concrete subclasses for the different options.
Now that we’ve defined our cache, we can create an instance, and then use it from within a callback, such as a serverless API implementation. This is a fairly complex application that acts as a URL shortener, with both GET and POST endpoints, but really shows off the power of combining many of the techniques we’ve seen throughout this post:
index.ts:
import * as cloud from "@pulumi/cloud"; import * as cache from "./cache"; // Create a URL shortener app and a table to hold shortened URLs. let app = new cloud.API("shortener"); let urlTable = new cloud.Table("urls", "name"); // Use our cache component to cache frequently accessed URLs. let urlCache = new cache.Cache("urlcache"); // GET /url lists all URLs currently registered. endpoint.get("/url", async (req, res) => { try { res.status(200).json(await urlTable.scan()); } catch (err) { res.status(500).json(err.stack); } }); // GET /url/{name} redirects to the target URL based on a short-name. endpoint.get("/url/{name}", async (req, res) => { let name = req.params["name"]; try { // First try the Redis cache. If we miss, consult the table. let url = await urlCache.get(name); if (url) { res.setHeader("X-Powered-By", "redis"); } else { let value = await urlTable.get({ name }); if (value && value.url) { url = value.url; urlCache.set(name, url); // cache for next time. } } // If we found an entry, 301 redirect to it; else, 404. if (url) { res.setHeader("Location", url); res.status(302); res.end(""); } else { res.status(404); res.end(""); } } catch (err) { res.status(500).json(err.stack); } }); // POST /url registers a new URL with a given short-name. endpoint.post("/url", async (req, res) => { let url = req.query["url"]; let name = req.query["name"]; try { // Insert into the table and our URL cache. await urlTable.insert({ name, url }); await urlCache.set(name, url); res.json({ shortenedURLName: name }); } catch (err) { res.status(500).json(err.stack); } }); export let url = endpoint.publish().url;
Notice that we can capture and use our
Cache
component just like we can the
cloud.Table!
We’ve only scratched the surface of what’s possible with components and custom APIs, however hopefully you’re starting to get a sense of why this is such a powerful capability.
Winding Down
In this post, we’ve seen how Pulumi can define infrastructure, containers, and serverless cloud software, often combining many of the techniques together to build powerful distributed applications. This includes programming to specific resources that your cloud of choice provides, in addition to writing higher level cloud programs that are able to target many clouds (expect more multi-cloud progress here in the weeks to come – including Kubernetes). Each pearl is a topic unto itself; we’d love your feedback on what topics to dig into next.
Happy hacking – and have fun programming the cloud!
Posted on | https://www.pulumi.com/blog/program-the-cloud-with-12-pulumi-pearls/ | CC-MAIN-2021-25 | refinedweb | 4,733 | 56.05 |
Read Concurrency Parallelism and Goroutines for Beginners before you proceed further.
CodeRef# 1
What do you think is the Output of above code?
Output CodeRef# 2
CodeRef# 3
Output CodeRef# 3
Play with CodeRef# 3
CodeRef# 4
Output CodeRef# 4
Play with the Code
CodeRef# 5
Output CodeRef# 5
CodeRef# 6
Play with the Code
Output CodeRef# 6
The above code is self explanatory. Play around and you'll soon get the knack of it. Please share your views to improve this article.
References
CodeRef# 1
package main import "fmt" func main() { fmt.Println("A message from main function") go fmt.Println("A message from goroutine") }
What do you think is the Output of above code?
A message from main function
Play with the Above Code
In most of the cases you would get the above output. But there can be cases where you may get both the messages as output. Here we can conclude that the output of the above code is undefined.
Why didn't it always print the second message from the goroutine?
The func main() here is running in a single OS execution thread. Once the main() code has finished writing "A message from main function" it doesn't wait for the other subroutine (called using the keyword go) to finish its task.
A quick fix solution that can fix this issue is to introduce a delay in the main(). Something like:
CodeRef# 2
package main import "fmt" import "time" func main() { fmt.Println("A message from main function") go fmt.Println("A message from goroutine") time.Sleep(1 * time.Second)
}
Output CodeRef# 2
A message from main function A message from goroutine
It seems we've achieved what we expected out of that code snippet. Right?
Though we've got the expected result it is a good example of bad programming. Time based synchronization must be avoided as they are inefficient and might lead to ugly bugs. You never know if the process will take 1 second (as introduced in the above example) or more or less than 1 second. Also, the time of execution may differ on different machine configuration. Avoid it!
CodeRef# 3
package main import "fmt" import "runtime" func main() { fmt.Println("A message from main function") go fmt.Println("A message from goroutine") runtime.Gosched() }
Output CodeRef# 3
A message from main function A message from goroutine
Play with CodeRef# 3
This looks like a better solution. Here Gosched() has switched the execution context so that the other goroutine can finish its task. Gosched() yields the processor, allowing other goroutines to run.
What are Channels?
Goroutines run concurrently as independent units and hence there must be some mechanism to synchronize the access to shared memory. This is essential to prevent deadlock like scenarios. Go has Channels to sync goroutines.
The Little Go Book by Karl Seguin describes channels as:
You can think Channel.
Remember, a channel can only transmit data-items of one datatype.
Type of Channels
- Unbuffered or Synchronous
- Buffered or Asynchronous
Declaring & Allocating Memory to Channels
intC := make(chan int) //default capacity = 0
strC := make(chan string, 3) // non-zero capacity
Channel Supports 2 operations SEND and RECEIVE
Channel <- Data // SEND 'data' to a channel
msg :- <- Channel //RECEIVE a message & Assign it to a variable msg
r := make(<-chan bool) // can only read from
w := make(chan<- []os.FileInfo) // can only write to
Note: The left arrow operator <- is used for both sending & receiving data. The arrow head of the operator points in the direction of data flow. The channel SEND & RECEIVE operations are Atomic i.e. they always complete without any interruption.
CodeRef# 4
package main
import ( "fmt" "time" ) func main() { ch := make(chan int) go iSend(ch) go iReceive(ch) time.Sleep(time.Second * 1) } func iSend(ch chan int) { ch <- 1 ch <- 3 ch <- 5 ch <- 7 } func iReceive(ch chan int) { var info int // infinite for loop, executes till 'ch' is empty for { info = <-ch fmt.Printf("%d ", info) } }
Output CodeRef# 4
1 3 5 7
Play with the Code
CodeRef# 5
Output CodeRef# 5
1 2 3 4 5 6
Play the code here
CodeRef# 6
Play with the Code
Output CodeRef# 6
1 2 4 6 8 3 5 7
The above code is self explanatory. Play around and you'll soon get the knack of it. Please share your views to improve this article.
References | http://www.golangpro.com/2016/04/ | CC-MAIN-2017-26 | refinedweb | 733 | 72.76 |
Creating APEX Class in Salesforce
Syntax of class:
Private | public | global “Virtual | abstract | with sharing | without sharing | (none)” Class implements | (none)” “extends | (none)” { // the body of the class }
To create an Apex class, go to the following path
Your Name —> SetupàApp setup—>Develop —> click on Apex classes —> click on “New” button.
*In the editor pane, enter the following code Public class Helloworld { }
Click on Quick save —> Saves the Apex Code, making it available to be executed —> it makes us to add and modify code.
Save –> savers the Apex Code, but that classes the class editor and returns to the Apex classes list.
*Add the static method to the above class Now Apex class become. Publish class Helloworld { public static void sayyou( ) { System.debug ( 'you' ); }
*Now add a instance method. Now the Apex class became public class Helloworld
{// class creation Public static void sayyou () { //adding static method to the class } Public void sayMe ( ) { //adding instance method to system debug (‘Me '); the class
Calling a class Method:
We have created the “Helloworld” class follow these steps to call its methods .
- Execute the following code in the Developer console to call the Helloworld class’s static method.
*** To call a static method, we don’t have to create an instance of the class. Helloworld say you ();
Open Raw log, then “You” appears in the USER-DEBUG log.
- Now execute the following code in Developer’s Console to call the Helloworld classes instance method.
Note:- To call an instance method, we first have to create an instance of the Helloworld class.
Helloworld h= new Helloworld ( ); h.say Me ( );
Open Raw log , then “Me” appears in the USER-DEBUG log.
Inclined towards the profession of the Saleforce? then what is the waiting for.. study Salesforce Training and Certification.
Alternation APEX Class Creation:-
We can also create new Apex classes directly in the Developer Console.
- Open the Developer Console.
- Click the repository tab.
- The setup Entity type panel lists the different items. We can view and edit in the Developer Console.
- Click on classes, and then click “New” button .
- Enter “Message” for the name of the
- new class and click “ok” bottom.
- Add the following static method to the new class
public static string hellowMessage () { return ( 'welcome to capital info solutions '): }
- Click on “Save” button.
Examples 1:-
Public class AccountCreation { Public Account createAccount(String name){ Account a= new Account(); a.Name = name; insert a; return a; } } Go to the Developer console, and execute the following code Account Creation ac = new Account Creation(); creating an instance for the above class. ac.CreateAccount('Osmania University'); calling a method system.debug(ac); check the account is created or not in the USER-DEBUG Log.
2.The following program is used fetch the Account Name from the account records by passing phone number.
Public class Fetch_Account_ Name_ From_Phone{ Public set<string> Fetch_ ACC_ Name(String P) { set <string> s1= new Set<string>(); List<Account> acc= “select id, Name from Account where phone”; for (Account a:acc) { String s=a.name; s1.add(s); } System.debug('xxxxxxxxx' +s1); return s1; } }
Go to the Developer Console, and execute the following code. FetchAccountName_ From_Phone ft= new FetchAccountName_from_Phone (); ft.FetchAccName (‘9052’);
In the User-Debug Log all the accounts will come that has the phone number is 9052.
0 Responses on Creating Apex Class" | https://tekslate.com/salesforce-creating-apex-class/ | CC-MAIN-2018-51 | refinedweb | 550 | 64.81 |
09 September 2009 18:13 [Source: ICIS news]
TORONTO (ICIS news)--The Qatargas 2 liquefied natural gas (LNG) project has started production at its Train B this week, stakeholder Total said on Wednesday.
The 7.8m tonne/year Train B, also know as "Qatargas 2 Train 5", is one of two trains making up Qatargas 2.
This brings Qatargas’ overall LNG production to 25m tonnes/year, the French energy major said.
Qatargas 2 is integrated with the South Hook re-gasification terminal in ?xml:namespace>
In addition to Total's 16.7% stake, other Train B stakeholders are Qatar Petroleum (65%) and ExxonMobil (18.3%)
For more on Total, | http://www.icis.com/Articles/2009/09/09/9246362/qatargas-2-starts-lng-production-at-train-b-total.html | CC-MAIN-2015-11 | refinedweb | 109 | 65.62 |
On Thu, Sep 24, 2009 at 1:18 PM, Simon Willison <si...@simonwillison.net> wrote:
> It's also something that's hard to do correctly. At the sprints Armin
> pointed out that I should be using hmac, not straight sha1, for
> generating signatures (something Django itself gets wrong in the few
> places that implement signing already). Having a cryptographer-
> approved implementation will save a lot of people from making the same
> mistakes.
I have no idea how hmac differs from straight sha1, but this was
raised in a django-signedcookies issue as well, and i've since
integrated it. I'm with you on this; if somebody who knows better
recommends something, I'm inclined to listen.
> I think signed cookies should either be a separate API from
> response.set_cookie or should be provided as an additional argument to
> that method. I'm not a fan of signing using middleware (as seen in
> ) since that approach
> signs everything - some cookies, such as those used by Google
> Analytics, need to remain unsigned.
I admit, I hadn't considered third-party cookies when I put it
together as a decorator. Client-side cookie access is likely
problematic as well, but that'll always be questionable anyway. You
can't validate a cookie in the client without divulging your secret
key and you can't just ignore the signature, because that defeats the
whole purpose. My app also provides a decorator, which might help in
some rare situations, but most of the time things like analytics
cookies will be in a base template and will always be included in
whatever view happens to have the decorator. I'm very surprised that
in all this time, nobody submitted a bug about the analytics problem.
> So the API could either be:
>
> response.set_signed_cookie(key, value)
>
> Or...
>
> response.set_cookie(key, value, signed=True)
>
> (I prefer the latter option)
I prefer the latter as well, for an added reason. I'd personally like
to invest some time in seeing if there are any other interesting
pitfalls in set_cookie() based on it deferring to Python's
SimpleCookie implementation. When writing Pro Django, I realized that
SimpleCookie expects everything to be strings, so #6657 came up with
secure=False resulting in a secure cookie after all. I don't know if
there are other such issues, but it might be worth looking at in
detail if we already have to add in signed cookie support.
And before anyone asks, no I don't think tying the signing behavior
into secure=True would be a good idea. Secure is meant to tell the
browser it should only send the cookie back over a secure channel,
such as HTTPS. While people who need secure cookies may also want
signed cookies, they're two separate ideas that I don't think would do
well mixed together. Of course, that leaves us with a potential
response.set_cookie(key, value, secure=True, signed=True), but I think
it's worth it to be explicit.
But I do have one other concern with either of these APIs that is at
least worth discussing: the disparity between setting a signed cookie
and retrieving one.
response.set_cookie(key, value, signed=True)
value = signed.unsign(request.COOKIES[key])
Mainly, unsigning a cookie requires importing and directly using the
signing module anyway, so the benefit of having set_cookie() handle it
transparently is fairly weak (unless, of course, I'm missing something
obvious). I'd rather just see the signing code made available and
well-documented, so that at least the change in code when adding
signed cookies is equivalent on both sides.
Another option would be to have request.COOKIES be a custom
dictionary, with an extra .get_unsigned(key) method that would work
like .get(), but validates the signature along the way. That behavior
can't be added straight to __getitem__() though, because that has no
way of knowing whether the cookie was signed to begin with.
These are the types of issues that led me to just implement it as a
middleware, so the API could be as dead simple as possible. With these
new issues in mind, I don't think dead simplicity is really an option,
so I'd rather fall back to being explicit.
>>>> signed.unsign('hello.9asVJn9dfv6qLJ_BYObzF7mmH8c')
> 'hello'
>>>> signed.unsign('hello.badsignature')
> Traceback (most recent call last):
> ...
> BadSignature: Signature failed: badsignature
>
> BadSignature is a subclass of ValueError, meaning lazy developers
> (like myself) can do the following rather than importing the exception
> itself:
>
> try:
> value = signed.unsign(signed_value)
> except ValueError:
> return tamper_error_view(request)
I'm not a big fan of this, personally. Yes, it does make things
slightly easier, by not requiring a separate import, but we already
have django.core.exceptions.SuspiciousOperation exists for a reason,
and a missing or invalid signature would certainly qualify, in my
eyes. Yeah, I suppose we could perhaps make that a subclass of
ValueError or TypeError, but I would worry about people wrapping it up
into something else that might cause problems.
try:
value = signed.unsign(signed_value).decode('utf-8')
except ValueError:
# Whoops! UnicodeDecodeError winds up here as well!
I don't know how likely this is to happen, since the only examples I
could come up with offhand are:
* Unicode errors, which could possibly be handled by automatic
Unicode translating in the signing code
* Using int() for things like user IDs, in which case a non-integer
would be evidence of tampering anyway.
Of course, you could just as easily argue that people shouldn't be
doing that, or if they do, they should import BadSignature (or
whatever) and give it its own except block ahead of ValueError so the
two can be distinguished. But of course, that expects a non-lazy
programmer, and if we're trying to make it easier for lazy
programmers, I don't think the behavior of non-lazy ones matters much.
> Potential uses
> ==============
>
> Lots of stuff:
>
> - Signed cookies (obviously)
> - Generating CSRF tokens
> - Secure /logout/ and /change-language/ links
> - Securing /login/?next=/some/path/
> - Securing hidden fields in form wizards
> - Recover-your-account links in e-mails
I think this is a big win for including signing as a separate piece
from signed cookies, because you have a much bigger list of use cases,
which can make it easier for people to understand the value. One of
the most common questions I got on my app was, "why would I want to
sign my cookies?" I think expanding the available uses signing will
help answer that question.
> So... what do people think? Is this a feature suitable for Django
> (obviously I think so)? Is this as simple as getting a cryptographer's
> input and dropping signed.py in to django.utils or are there other
> design factors we should consider?
All in all, I understand and appreciate the benefits of signing
things, and I'd like that behavior to be made available reliably and
easily, and it looks like that would require them being in core. I'm a
little worried about ease of use, though, because it seems like most
of the ways to make things easy can also make things either more
confusing or less flexible. I'm a little scattered on the moment, but
I think it's definitely worth refining into something that can go into
core.
-Gul
The behavior you mention here is exactly what django-signedcookies
does, but it can only do so because it can blindly assume that all
cookies are signed, which as you pointed out, causes other problems.
> We could fix this with a naming convention of some sort:
>
> response.set_cookie('key', 'value', sign=True)
> - results in a Set-Cookie: key__Xsigned=value header
That seems pretty ugly on the surface, but it does confine the
ugliness to somewhere most people won't bother to look. One potential
problem is if someone wants to use __Xsigned in the name of an
unsigned cookie, but a namespace clash like that should be extremely
rare in practice.
Also, does the name of a cookie factor into the cookie length limits?
My reading of RFC 2109 says yes, but it'd be worth verifying, since it
would cut down on the usable value space. With your compressed base64
stuff, that's not as big of a problem, but still something to look
into.
> request.unsign_cookie('key') might be an option, as at least that
> reflects the set_cookie / sign / unsign API a bit. Not ideal by a long
> shot though.
>> try:
>> value = signed.unsign(signed_value).decode('utf-8')
>> except ValueError:
>> # Whoops! UnicodeDecodeError winds up here as well!
>
> That's a great argument against subclassing ValueError - I hadn't
> considered the unicode case. You're right, if anything it should
> subclass SuspiciousOperation instead.
I don't know if it's completely anti-ValueError, because a ValueError
subclass does still make some sense semantically, and since you can
catch more than one exception type in a try block, it's perfectly
functional. It's just that when lazy people blindly catch ValueError
without checking for something more specific as well, things can
break.
So it really just comes down to whether we expect people to be
thorough or lazy. Hrm. Yeah, I guess that answers it. :)
-Gul
I do think that this should find it's way into trunk, as signed
cookies are important in the use cases you mention and are really easy
to get wrong... and getting it wrong can be dangerous.
I'm not going to get into the dumps/loads bit right now because
there's enough to tackle on signed cookies.
On Thu, Sep 24, 2009 at 2:54 PM, Simon Willison <si...@simonwillison.net> wrote:
> Hmm... I hadn't considered that. I was thinking that the unsigning
> could be transparent, so by the time you access request.COOKIES['key']
> the value had already been unsigned (and if the signature failed the
> cookie key just wouldn't be set at all, as if the cookie never
> existed). But as you point out, this doesn't work because you can't
> tell if the cookie was signed or not in the first place.
>
> We could fix this with a naming convention of some sort:
>
> response.set_cookie('key', 'value', sign=True)
> - results in a Set-Cookie: key__Xsigned=value header
Unfortunately, this approach won't work.
A malicious client can just send "key" rather than "key__Xsigned" and
you'll never know that the cookie hasn't gone through validation.
This also means that you can't look for cookie values that match a
specific format (ex: body.signature) because a malicious client could
just drop the signature portion.
As always, we can't trust the client. :-(
This means that unsigning can *never* be fully transparent. We need a
symmetric specification of the fact that a given cookie should,
indeed, be signed.
> But that's pretty ugly. Not sure what to do about this one -
> request.unsign_cookie('key') might be an option, as at least that
> reflects the set_cookie / sign / unsign API a bit. Not ideal by a long
> shot though.
I'm not sure what the best solution is, but here are some of the
options I've considered:.
Best,
- Ben
Also, just to throw this out there for the sake of compleness: could
the signature be stored under a separate name, rather than being
bundled with the original cookie itself?
Set-Cookie: key=value
Set-Cookie: key__Xsignature=signature_string
It seems like this could address a couple issues at once.
* There's a clear distinction between signed and unsigned cookies, so
request.COOKIES can be populated with only valid cookies
* The key/value pair remains unchanged, so things like Google
Analytics can happily ignore the signature if it was applied
unnecessarily (middleware is back on the table!)
Since there may be an upper limit on the number of allowed cookies,
though, doubling the number of cookies could present some very real
problems. RFC 2109 recommends allowing at least 20 cookies per domain
name, and it looks like at least Microsoft takes that to be a
maximum,[1] so it could present very real problems (middleware is back
off the table!).
I'm not sure how many cookies people use on a regular basis, and this
would only be for explicitly signed cookies, so maybe it'd be okay,
but it's flirting dangerously close to being completely unworkable.
Worse yet, it doesn't look like there's any predictable way to know
which cookies would get lost in the event of having too many, so this
may end up causing some very weird application errors if things go
wrong.
At least now it's been recorded for future reference. (Hello, future
me, looking up information on why we did things the way we did! Do we
have flying cars yet?)
-Gul
[1]
And you've just added another reason my followup email is invalid,
though I sent that before reading your response. (Take that, future
me!)
>.
I was wondering about this option as well, after I mentioned adding a
request.COOKIES.get_unsigned() method. I actually like this idea a
lot, personally. As you mention, it's backward compatible, and I'm not
sure it completely breaks the traditional expectation. After all,
aren't subclasses expected to customize the behavior of their parents?
It doesn't change any existing behavior, but rather just adds
something extra.
The one downside to using get() directly, as opposed to an altogether
new method, is that get() doesn't raise a KeyError when a value
doesn't exist. That means if anyone's wrapping request.COOKIES[key] in
a try block and catching KeyError, changing to the new code is more
than just a one-liner. I'm personally okay with this, but it's
definitely worth noting.
-Gul
signer = Signer(key=...)
assert signer.unsign(signer.sign(value)) == value
This way you wouldn't have to pass around key, extra_key, and
potential further arguments but a single Signer instance. Plus, you
could easyly overwrite hashing, concatenation, and serialization as
well as add functionality transparently, eg.:
sig = TimestampedSignatureFactory(ttl=3600) # sig.unsign() will raise
SigntureExpired after 3600 seconds
>.
4) A signed.Cookies object:
signed_cookies = signed.Cookies(request, key=...)
signed_cookies.set_cookie(key, value, **kwargs)
value = signed_cookies[key]
or
signed_cookies = signer.get_cookies(request)
...
__
Johannes
The problem is that you don't know which cookies are signed and which
aren't for the reasons posted earlier. So you don't know which cookies
to put in SIGNED_COOKIES and which to put in COOKIES unless accessing
COOKIES gives you raw values of ALL cookies and SIGNED_COOKIES
attempts to unsign ALL cookies. That seems really clunky.
You have to sign and unsign the cookies yourself in code which makes
the sign_cookie/unsign_cookie API make sense.
Ian
request.COOKIES.get_signed(key) makes the most sense to me since it's
clear you are dealing with cookies and as you said it looks something
like the request.POST object. Though it's a bit more verbose than
request.unsign_cookie(key), accessing cookies directly through the
request object looks wierd and unsign_cookie could be ambiguous.
Ian
Put me down as +1 in favor of adding support for signed cookies in some form.
As for the exact form that the API will take - I don't have any
particularly strong opinions at this point, and there are plenty of
big brains weighing in, so I will stay out of the discussion and let
the community evolve the idea.
By way of greasing the wheels towards trunk: if the outcome of this
mailing list thread was a wiki page that digested all the ideas,
concerns and issues into a single page, it will make the final
approval process much easier. Luke Plant's wiki page on the proposed
CSRF changes [1] is a good model to follow here - I wasn't involved in
the early stages of that discussion, but thanks to that wiki page, I
was able to come up to speed very quickly and see why certain ideas
were rejected.
[1]
Yours,
Russ Magee %-)
> SECRET_KEY considerations
> =========================
Can I add some other things I've been worrying about while we're on
the topic?
In other web apps (I think Wordpress?), there have been problems
associated with use of secret keys when the same key is used for
different purposes throughout the application.
Suppose one part of an app signs an e-mail address for the purpose of
an account confirmation link sent in an e-mail. The user won't be
able to forge the link unless they know HMAC(SECRET_KEY, email).
However, suppose another part of the website allows a user to set
their e-mail address (merely for convenience), and stores it in a
signed cookie. That means an attacker can now easily get hold of
HMAC(SECRET_KEY, email), and forge the link.
There are many places in Django that use SECRET_KEY. I'm not
currently aware of any vulnerability, because in most cases the
attacker has only *limited* control over manipulating the message that
is being signed. But I may have missed some, and without some
systematic method, it would be easy for one place to open up
vulnerabilities for all the others.
So I propose:
- we review all the Django code involving md5/sha1
- we switch to HMAC where appropriate
- we add unique prefixes to the SECRET_KEY for every different
place it is used. So for the e-mail confirmation link, we use
HMAC("email-confirmation" + SECRET_KEY, message)
- also add the ability to do SECRET_KEY rotation, as Simon
suggested. This suggests we want a utility wrapper around hmac
that looks like hmac(unique_key_prefix, key, message) and handles
all the above details for us.
The main difficulty is the way this could break compatibility with
existing signed messages, especially persistent ones like those stored
in password files etc.
Luke
--
"Smoking cures weight problems...eventually..." (Steven Wright)
Luke Plant ||
I'm not a huge fan of request.SIGNED_COOKIES. I'd rather see them all in
request.COOKIES, but the same idea could still apply:
@expects_signed_cookies('username')
def user_home(request):
...
Alternatively, is it stupid to think that the number of signed cookies
used by an application is probably small enough that keeping a list of
them in settings.py is too much book keeping? Then, when
setting/retrieving a cookie, a lookup is done in settings, and if the
key is marked as SIGNED, it does it without human intervention. Less
things to go wrong that way I'd think, and any third-party app's cookies
can be secured without hardly any code changes.
SIGNED_COOKIES = ['username']
> Do you have any further information on the WordPress problems?
No, I can't find it. It might not have been WordPress. All I remember
is that it was along the lines of what I outlined in my previous e-
mail -- one part of the application was essentially allowing the user
to retrieve MD5(secret_key + user_supplied_data) (might have been HMAC
or SHA1), which allowed them to get past another bit of security.
This was something I was concerned with when I put together my app, so
I just added the name of the cookie to the signature as well, rather
than requiring some other explicit prefix. Since the two parts of the
application would need to use different names anyway to avoid other
problems, I figured the cookie name alone would be sufficient. If we
end up with something like response.set_signed_cookie() or
response.set_cookie(..., signed=True), the cookie name would be
available to the signing code internally, without any need to add in
some other key.
Of course, it'd still be worth documenting for the case of using the
in elsewhere. I just think if we already have a name available, we
should be able to use it without any trouble at all. I wish there was
a way to sign the expiration as well, so people couldn't artificially
extend the life of the cookie, but since that doesn't come back in the
request, there'd be no way to validate it.
> So I propose:
>
> - we add unique prefixes to the SECRET_KEY for every different
> place it is used. So for the e-mail confirmation link, we use
> HMAC("email-confirmation" + SECRET_KEY, message)
I think this is good for everywhere the raw signing API is accessed,
perhaps to the point where that API can't even be used without a key
(a namespace, really - honking great idea!). Helpers on top of that
API could do without asking for that separately, if they can retrieve
a reasonable key from other forms of input, such as a cookie name or a
query-string argument name.
-Gul
Very true. I had considered baking the timestamp right into the value
portion as well, but I was concerned about the extra space it would
take. It looks like it would only be 8 characters max, if encoded as
base64, which could be shortened to 6 if we strip out the == at the
end. I think I remember reading somewhere that those can be reattached
programmatically on the other end if necessary. All in all, the space
usage isn't that bad, and since it would be an optional component
anyway, it wouldn't add any overhead to the common case.
Would expire_after on the unsign just automatically imply
timestamp=True? There's been a lot of concern raised about parity in
the API, and it reads a little weird with the two different arguments.
I'm not sure it's a problem, but it's just a little funny.
Even though Ben rightly pointed out that we can't autodetect whether a
value is signed or not, I wonder if we could at least autodetect the
presence of a timestamp within a signature, once we already know that
the value is supposed to be signed. Essentially the unsigning code
could look for two different types of signatures, one with a timestamp
and one without. The timestamp would then be the actual expiration
time, rather than the time it was signed, so the API can look like
this instead (with a key added per prior discussion).
>>> s = signed.sign('key', 'value')
>>> v = signed.unsign('key', s)
>>> s = signed.sign('key', 'value', expire_after=24 * 60 * 60)
>>> v = signed.unsign('key', s)
This does make some assumptions about the format of the signed value,
but once we explicitly establish that the value is signed (by way of
passing it into the unsigning code), it's safe to make certain
assumptions about the format of the value. Or am I missing something
obvious here?
In the cookie case, it might be appropriate to use the combination of
an explicit expiration and signed=True to imply that an expiration
timestamp should be added to the cookie as well. I think that would be
the desired behavior, but I'm not quite sure.
Aside from some of the specifics of the cookie implementation, I think
we're getting close to an API here. I just hope we can get some input
from a cryptographer to make sure we get a solid implementation before
we go too far with this.
-Gul
But that only works for signatures that do in fact use a timestamp. If
the API makes timestamps optional, then there's still the question of
what to do for signatures that aren't stamped anyawy. In those cases,
I assumed the protocol would be to simply try to most recent
SECRET_KEY and work backward if the signature failed. Once all current
and deprecated keys have been tried (which should only be a total of
two, I would think), it would raise BadSignature at that point.
If we already have that behavior for non-timestamped cookies (and
correct me if I'm wrong on that point), I don't know that it's much of
an argument in favor of which timestamp to use. As long as there's not
a huge list of valid SECRET_KEYs to choose from, the overhead of
trying them each individually should be negligible, so I'm not sure
how much of an issue it would be.
I do agree though that you do have a point about there being possible
reasons for expiring the key at a different point after the fact, but
I'd argue that in those cases, you'd want to set an explicit
expiration time. In your example, you provided expire_after=24 * 60 *
60, but that wouldn't let you expire a cookie because of an event that
happened 2 hours ago. I would think you'd want to pass in a specific
time that cookies should be considered expired instead.
Of course, that then goes back to stamping cookies with their creation
time anyway, because otherwise you couldn't really do it right. If I
say "expire as of time X" I want to expire all cookies issued prior to
that point in time, while leaving any issued after that point intact.
The only way to make that decision is to know the time it was issued,
rather than when it was originally expected to expire.
I think we're getting a bit ahead of ourselves, though. There's
nothing stopping an application timestamping its own signatures and
validating them however they like, so we're really just discussing a
reasonable default here. Heck, since the timestamp behavior is driven
entirely within an already-signed value, we don't need to provide any
behavior at all if it's not a common requirement. I think it's a good
idea, but I'd like to hear from other people before I really stand
behind including it.
-Gul
Regarding parity, let me advertise a Signer object again:
signer = signed.Signer(
key=settings.SECRET_KEY,
expire_after=3600
)
s = signer.sign(v)
v = signer.unsign(s)
signer.set_cookie(response, name, value)
signer.get_cookie(request, name)
# or:
signer.get_cookies(request)[name]
# transparently sign cookies set via response.set_cookie()
# and unsign cookies in request.COOKIES in place:
@signer.sign_cookies
def view0(request):
...
@signer.sign_cookies('cookie', 'names')
def view1(request):
...
This would make more options and customization feasible (by
subclassing):
- put signatures in separate cookies (or a single separate cookie)
- automatically include request.user.id (to prevent users from
sharing cookies)
- swap out the hash, serialization, or compression algorithm without
changing the token format
- customize when and how expiration is determined
__
Johannes
Personally, I don't see much point in specifically reporting on
incorrectly signed cookies - imo they should just be treated as if
they never existed. If someone really cared, they can look in
request.COOKIES to see if the cookie was in there but not in
SIGNED_COOKIES.
This is how a class-based API might look. It's based on django-signed.
All cookie related code is untested.
__
Johannes | https://groups.google.com/g/django-developers/c/EzUJJGyvHZE | CC-MAIN-2021-49 | refinedweb | 4,467 | 61.77 |
Have you ever thought about the possibility of using your phone’s camera for computer vision task? Yes, you can! In this article, I will walk you through how to use your phone camera with Python for computer vision.
Learn How To Use Phone Camera with Python:
Using a phone camera with Python is very useful for those who are planning to create computer vision apps that will use a smartphone camera as a part of your application. Here I am using Python on Windows 10. Hope this works for other operating systems as well, but if you are using Windows then don’t worry just follow the steps mentioned below.
The process of using a phone camera with Python:
- First, install the OpenCV library in Python; pip install opencv-python.
- Download and install the IP Webcam application on your smartphones.
- After installing the IP Webcam app, make sure your phone and PC are connected to the same network. Run the app on your phone and click Start Server.
- After that, your camera will open with an IP address at the bottom. Copy the IP address as we will need to use it in our Python code to open your phone’s camera.
Now let’s code to see how to open a phone camera with Python for the tasks of computer vision:
import cv2 import numpy as np url = "Your IP Address/video" cp = cv2.VideoCapture(url) while(True): camera, frame = cap.read() if frame is not None: cv2.imshow("Frame", frame) q = cv2.waitKey(1) if q==ord("q"): break cv2.destroyAllWindows()
In a few moments, an OpenCV window will appear and do the rest. To close the window, just press any key. This is how to connect a phone’s camera with Python for computer vision applications. The next step on how to use this feature depends on how you want to use it. Here are some of the computer vision tutorials where you can use a phone camera instead of the webcam:
I hope you liked this article on how to use a phone’s camera with Python for computer vision. Feel free to ask your valuable questions in the comments section below.
5 Comments
With a minor changes finally I get to work, Thanks
That’s great
Thank you brother, Felt happy to see your contribution, Love From Pakistan
Keep visiting
sir i found some issue please improve me
camera, frame = cap.read()
NameError: name ‘cap’ is not defined | https://thecleverprogrammer.com/2021/01/05/use-phone-camera-with-python/ | CC-MAIN-2021-43 | refinedweb | 414 | 80.92 |
This article will discuss the Jacobi Method in Python. We've already looked at some other numerical linear algebra implementations in Python, including three separate matrix decomposition methods: LU Decomposition, Cholesky Decomposition and QR Decomposition. The Jacobi method is a matrix iterative method used to solve the equation $Ax=b$ for a known square matrix $A$ of size $n\times n$ and known vector $b$ or length $n$.
Jacobi's method is used extensively in finite difference method (FDM) calculations, which are a key part of the quantitative finance landscape. The Black-Scholes PDE can be formulated in such a way that it can be solved by a finite difference technique. The Jacobi method is one way of solving the resulting matrix equation that arises from the FDM.
The algorithm for the Jacobi method is relatively straightforward. We begin with the following matrix equation:\begin{eqnarray*} Ax = b \end{eqnarray*}
$A$ is split into the sum of two separate matrices, $D$ and $R$, such that $A=D+R$. $D_{ii} = A_{ii}$, but $D_{ij}=0$, for $i\neq j$. $R$ is essentially the opposite. $R_{ii} = 0$, but $R_{ij} = A_{ij}$ for $i \neq j$. The solution to the equation, i.e. the value of $x$, is given by the following iterative equation:\begin{eqnarray*} x^{(k+1)} = D^{-1}(b-Rx^{(k)}). \end{eqnarray*}
We will make use of the NumPy library to speed up the calculation of the Jacobi method. NumPy is significantly more efficient than writing an implementation in pure Python. The iterative nature of the Jacobi method means that any increases in speed within each iteration can have a large impact on the overall calculation.
Note that this implementation uses a predetermined number of steps when converging upon the correct solution. Depending upon your needs in production, you may wish to use a residual tolerance method. For that you will need to take a look at the spectral radius.
Here is the implementation via NumPy:
from pprint import pprint from numpy import array, zeros, diag, diagflat, dot def jacobi(A,b,N=25,x=None): """Solves the equation Ax=b via the Jacobi iterative method.""" # Create an initial guess if needed if x is None: x = zeros(len(A[0])) # Create a vector of the diagonal elements of A # and subtract them from A D = diag(A) R = A - diagflat(D) # Iterate for N times for i in range(N): x = (b - dot(R,x)) / D return x A = array([[2.0,1.0],[5.0,7.0]]) b = array([11.0,13.0]) guess = array([1.0,1.0]) sol = jacobi(A,b,N=25,x=guess) print "A:" pprint(A) print "b:" pprint(b) print "x:" pprint(sol)
The output from the NumPy implementation is given below:
A: array([[ 2., 1.], [ 5., 7.]]) b: array([ 11., 13.]) x: array([ 7.11110202, -3.22220342])
We can see that after 25 iterations, the output is as given by the Wikipedia article on the Jacobi Method, up to the difference in significant. | https://www.quantstart.com/articles/Jacobi-Method-in-Python-and-NumPy | CC-MAIN-2018-05 | refinedweb | 507 | 55.03 |
Hi, trying to make my character jump but no luck. The actor falls straight through the ground when its suppossed to stop, and jump when its on the ground. here is the code:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Mario here. * * @author (your name) * @version (a version number or a date) */ public class Mario extends Actor { int acceleration = 2; int vSpeed = 0; int jumpAbility = 12; /** * Act - do whatever the Mario wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if(Greenfoot.isKeyDown("space") && onGround()) { jump(); } checkFall(); } public boolean onGround() { Actor under = getOneObjectAtOffset(0, getImage().getHeight()/2 + 2, GameGround.class); return under != null; } public void Fall() { setLocation (getX(), getY() + vSpeed); vSpeed = vSpeed += acceleration; } public void checkFall() { if (onGround()) { vSpeed = 0; } else { Fall(); } } public void jump() { vSpeed = -jumpAbility; Fall(); } } | https://www.greenfoot.org/topics/62520?pid=134197 | CC-MAIN-2019-30 | refinedweb | 146 | 67.15 |
Yep, we have updated the open source project PyMongo-Frisk (0.0.4) to now support MongoDB Replica Sets! Our library extends the PyMongo Connection class and adds an additional method called “check_health()”. This method when called returns who is the master, a list of all slave nodes, verifies read and write connectivity with the master, and finally verifies it can read from ALL slaves in the Replica Set. The intended usage for this connection class extension would be an internal monitoring page that is pinged regularly by an automated monitor and sets off an alarm if anything fails.
We created this project because we wanted to ensure that our app server had the ability to reach all failover slave nodes. We did not want to wait until a failure of the master occurred to find out the app server could not reach one of our slaves!
To use our extension of the connection class:
from pymongo_frisk import FriskConnection as Connection connection = Connection(['host1','host2','host3']) results = connection.check_health()
When called the method returns a dictionary containing info about the health of ALL nodes in a Replica Set:
{'db_master_host': 'host1:27017',
'db_slave_hosts': ['host2:27018','host3:27019'],
'db_master_can_write': True,
'db_master_can_read': True,
'db_slaves_can_read': [('host2',True),('host3',True)] }
Note, the library still supports Replica Pairs using authentication. We have moved on to using version 1.6+ of MongoDB, so we decided to make the jump recently from Replica Pairs to Replica Sets. Replica Pairs will be removed in MongoDB version 1.8. | http://myadventuresincoding.wordpress.com/category/pymongo/ | crawl-003 | refinedweb | 249 | 60.24 |
Python Programming, news on the Voidspace Python Projects and all things techie.
Ruby for Rails Review
This is a review of the Manning book, Ruby for Rails.
The review is written by Andrzej Krzywda, a colleague of mine from Resolver. In his previous job programmed in Ruby for Siemens in Poland.
Ruby.
The structure of the book is organised as follows: favourites
Let's take the following Rails code as an example:
class Edition < ActiveRecord::Base belongs_to :publisher end the important topics about Rails development and highlights the Ruby way. If you already created some Rails applications but still feel there is some magic around you definitely should read this book.
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-11-22 23:44:39 | |
Categories: Writing, General Programming
PyCon Decisions Delayed
Well the deadlines for choosing talks and tutorials for PyCon 2007 have whizzed passed with that wonderful whooshing noise they make.
I guess they're struggling due to the number of proposals this year, but no word to submitters has left me on tenterhooks...
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-11-23 18:58:05 | |
Code Objects: An Exploration
I'd like to do some bytecode hacking, to see if I can dynamically 're-scope' blocks of code. What I'd like to do is take the code object from a function and execute it in the current context. The reasons for this are two-fold. Firstly I'd like to see if I can emulate Ruby blocks by making a function body execute in the current context. Secondly I'd like to learn more about the implementation of Python scoping rules by experimenting with byte-code.
Ok, so this sounds like a hack, and I guess it is. It's interesting to note however that Aspect Oriented Programming is a well accepted technique in Java, and is mainly implemented at the bytecode level.
Functions work by using a combination of function attributes and the underlying code object to setup and execute the function. So the first thing to do is to learn a bit more about code objects. (I have a couple of other ideas I'd like to try out as well, but this entry only gets as far as exploring code objects.)
When you create a function, it has a code object (the function body) as the attribute func_code :
pass
codeObject = function.func_code
print type(codeObject)
<type 'code'>
The best reference I can find on Python code objects is: Code Objects (Unofficial Reference Wiki).
This explains what the attributes on a code object are, but it doesn't explain what they mean. For example :
-
We have six types of variables listed here. Some of them sound obvious, but why so many and what is a 'free variable' ? [1]
I'm going to create some code objects (including a nested function) and look at these values to see if I can work anything out.
def function1(a, b, c=1):
w = 2
x = 3
w += 1
print a
print b
print c
print v
print w
print x
def function2(d, e, f=4):
y = 5
z = 6
z += 1
print a
print b
print c
print v
print w
print x
print y
print z
return function2
code1 = function1.func_code
code2 = function1(4, 5).func_code
code3 = compile("""w = 2
x = 3
w += 1
print v
print w
print x\n""", '<Something>', 'exec')
for code, name in zip((code1, code2, code3), ('code1', 'code2', 'code3')):
print 'Looking at %s.' % name
for entry in dir(code):
if entry[:2] == entry[-2:] == '__':
continue
print entry, getattr(code, entry)
print '\n'
And the output (extraneous prints from calling 'function1' removed and unprintable characters replaced...) :
First the object code1 :
Looking at code1. co_argcount 3 co_cellvars ('a', 'b', 'c', 'x', 'w') co_code Unprintable stream - the code object co_consts (None, 2, 3, 1, 4, <code object function2>) co_filename bytcodetest.py co_firstlineno 2 co_flags 3 co_freevars () co_lnotab More unmentionables co_name function1 co_names ('w', 'x', 'a', 'b', 'c', 'v', 'function2') co_nlocals 6 co_stacksize 7 co_varnames ('a', 'b', 'c', 'function2', 'w', 'x')
So the 'cellvars' are all the names created in the scope of function1, including the arguments but not the nested function definition.
'freevars' is empty.
'names' is all the names used in the scope of function1.
'varnames' is all the local variables. It includes the nested function (which is local), but not 'v' which is global.
'consts' is the values used in the function, including the function object function2. The leading None means the function has no docstring.
Next the object code2 :
Looking at code2. co_argcount 3 co_cellvars () co_code Unprintable stream - the code object co_consts (None, 5, 6, 1) co_filename bytcodetest.py co_firstlineno 12 co_flags 3 co_freevars ('a', 'c', 'b', 'w', 'x') co_lnotab More unmentionables co_name function2 co_names ('y', 'z', 'a', 'b', 'c', 'v', 'w', 'x') co_nlocals 5 co_stacksize 2 co_varnames ('d', 'e', 'f', 'y', 'z')
'cellvars' is empty !?
'freevars' contains all the names used from the scope above ('function1').
'names' is all the names used in the scope of function2.
'varnames' is all the local variables for function2. It doesn't include names defined in function1.
Last, object code3 :
Looking at code3. co_argcount 0 co_cellvars () co_code Unprintable stream - the code object co_consts (2, 3, 1, None) co_filename <Something> co_firstlineno 1 co_flags 64 co_freevars () co_lnotab More unmentionables co_name ? co_names ('w', 'x', 'v') co_nlocals 0 co_stacksize 2 co_varnames ('x', 'w')
'cellvars' is empty again. (So it looks like the two code objects which don't have functions in them don't have any 'cellvars'.)
'freevars' is also empty.
'names' is all the names used in the scope of code3.
'varnames' is all the local variables. It doesn't include 'v'.
This code object does not belong to a function, so the 'flags' are different. It also has no leading None, but it has a trailing one ?
Hmmm... so next time I'll look at the bytecode and see how they use different opcodes to load values. I will probably use a tool called byteplay. By creating new code objects, and transforming some of the byte-codes, I might be able to do something interesting.
For an interesting recipe which transforms byte-codes (and inspired me to actually do this rather than just think about it occasionally) see Implementing the make statement by hacking bytecodes.
Note
Michael Hudson said :
In Python, and in a given scope, a free variable is one that is defined in some outer scope and a cell variable is one that is referenced in some inner scope (i.e. is a free var for some inner scope).
In a more formal setting, globals would be free variables too.
Kent Johnson suggested Free and Bound Variables as a good reference.
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-11-20 23:19:53 | |
Categories: Python, Hacking
ConfigObj Updates: Sometime
It looks like I will be busy for the next few months.
There are several changes to ConfigObj that have already been waiting in the wings too long. Thankfully Nicola Larosa has stepped up to shepherd the changes in.
The forthcoming changes include :
- Making ConfigObj picklable (patch supplied by Jack Kuan)
- Fixing a couple of minor bugs reported on the Sourceforge Page
- Possibly supporting multi-line list values, though probably not for unrepr mode (patch supplied Tomi Kyöstilä)
- Simpler string interpolation using PEP 292 $templates (patch supplied by Robin Munn)
- Adding a semi-private attribute _indent_size to allow control of number of spaces in indentation when writing
- Allow string interpolation from the current section
- Support IronPython by making the parser import conditional
- Ensure compatibility with Python 2.5
This will be ConfigObj 4.4, but no promises about how long it will take.
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-11-19 18:46:18 | |
Categories: Python, Projects
ConfigObj in Interesting Places
ConfigObj [1] turns up in some interesting places. The latest places it's been seen include :
A Python and wxPython PIM, being developed by the OSAFoundation [2].
A very interesting looking Debian based Live-CD which supports storing data using an encrypted harddisk; usable even by non technical users [3].
A Ubuntu tool which provides a GUI to install a host of applications.
Debian-cd-ng recommends ConfigObj for parsing the Debian-cd configuration files.
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-11-18 14:28:33 | |
Categories: Projects, Python
Python Programming Links (etc)
A recent crop of links from my Del.icio.us bookmarks.
The Parking Lot is Full Archives
An amusing online comic. Now deceased, but the archives go from 1993 - 2002.
UpMyStreet - For where you live
Provide social indicators of UK areas, by postcode.
DISLIN - Scientific Plotting Software
Another plotting / graphing library. With Python bindings, free for non-commercial use. The examples look ok, but not as professional as some of the others I've seen.
Cheap and fast newsgroup servers.
30.10.1 Python Byte Code Instructions
Python Cheese Shop : BytecodeAssembler 0.2
ByteplayDoc - PythonInfo Wiki
Code Objects ((An Unofficial) Python Reference Wiki)
Python Jobs, Average Salary for Python Skills
I've sent this to my boss. He hasn't replied yet.
Tactical 4.0 - Geek Jacket
A very cool jacket.
SourceForge.net: tk-components
Interesting components (Tile wrapper Help Browser, balloon help etc) for Tkinter, the Python GUI toolkit.
London 2.0 Community Portal
Website for the London 2.0 geek gatherings.
nLite - Deployment Tool for the bootable Unattended Windows installation
Create custom Windows installations.
Using System.Array from IronPython
Nice and clear example.
ASPN : Python Cookbook : Implementing the make statement by hacking bytecodes
A good example of bytecode hacking.
-
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-11-18 14:03:17 | |
Categories: Fun, Life, General Programming, Python, IronPython
Ultimate XP Office Tool
Announcing the ultimate tool for for pair-programming. Only for use in the most agile of programming environments, the PairOn :
We've got three on order for Resolver.
Like this post? Digg it or Del.icio.us it. Looking for a great tech job? Visit the Hidden Network Jobs Board.
Posted by Fuzzyman on 2006-11-18 13:58:18 | |
Categories: General Programming, Fun
Archives
This work is licensed under a Creative Commons Attribution-Share Alike 2.0 License.
Counter... | http://www.voidspace.org.uk/python/weblog/arch_d7_2006_11_18.shtml | crawl-002 | refinedweb | 1,815 | 65.73 |
49681/more-pythonic-counting-things-heavily-nested-defaultdict
My code currently has to count things in a heavily nested dict into another. I have items that need to be indexed by 3 values and then counted. So, before my loop, I initialize a nested defaultdict like:
from collections import defaultdict
type_to_count_dic = defaultdict(
lambda: defaultdict(
lambda: defaultdict(int)
)
)
Which allows me to count the items within a tight loop like so:
for a in ...:
for b in ...:
for c in ...:
type_to_count_dic[a][b][c] += 1
Can anyone help me with a more idiomatic/Pythonic way of doing something like this?
You can try the following, this might help you:
from collections import defaultdict
class _defaultdict(defaultdict):
def __add__(self, other):
return other
def CountTree():
return _defaultdict(CountTree)
>>> t = CountTree()
>>> t['a']
defaultdict(<function CountTree at 0x9e5c3ac>, {})
>>> t['a']['b']['c'] += 1
>>> print t['a']['b']['c']
1
Here is a simple function and some ...READ MORE
import re
a = " this is a ...READ MORE
The in-built variables and functions are defined ...READ MORE
There are several options. Here is
Try os.path.exists, and consider os.makedirs for the ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/49681/more-pythonic-counting-things-heavily-nested-defaultdict | CC-MAIN-2019-47 | refinedweb | 198 | 59.09 |
How Users Can Let Children Move Up & Move Down (Part 2)
By Geertjan.
Hi Geertjan,
me too, I had a hard time figuring out how to implement Node ordering. Let's assume you have an ArrayList keyArrayList to store the keys for your Children.Keys object. You need to permute the order of the keyArrayList content. It seems that Children.Keys.createKeys(List keys) is invoked directly after Index.Support.reorder() is called. Here's my implementation:
<code>
public class IndexImpl extends Index.Support
{
//This is where my Children.Keys stores its keys in
ArrayList keyArrayList;
Node myNode;
IndexImpl(ArrayList keyArrayList, Node myNode) {
this.keyArrayList = keyArrayList;
this.myNode = myNode;
}
@Override
public Node[] getNodes()
{
return myNode.getChildren().getNodes();
}
@Override
public int getNodesCount()
{
return myNode.getChildren().getNodesCount();
}
@Override
public void reorder(int[] perm)
{
ArrayList newOrder = new ArrayList();
for(int i = 0; i < _manips.length; i++) {
newOrder.add( keyArrayList.get(perm[i]));
}
keyArrayList.clear();
keyArrayList.addAll(newOrder);
}
}</code>
Posted by Carsten Schmalhorst on October 16, 2008 at 06:05 PM PDT #
Note: I'm posting some code here that can be difficult to read without formatting. Anyways, the comments in the program flow may be useful.
---
Strange that you should blog about this just as me and colleague was struggling with the very same problem. We have a node implementation that wraps an EMF Ecore model (which is cut loose from Eclipse) and we use EMF Commands to perform all manipulations on the model and our node implementation simply listen for changes and reflect them.
So for our Children implementation, we extended Index.KeysChildren and had to copy/paste the default implementation of Index.KeysChildren#createIndex() to return the following class:
@Override
protected Index createIndex() {
// create support instance for delegation of common tasks
return new Index.Support() {
// Copied from Index.KeysChildren#createIndex()
public Node[] getNodes() {
List<Node> l = Arrays.asList(EmfChildren.this.getNodes());
if (EmfChildren.this.nodes != null) {
l.removeAll(EmfChildren.this.nodes);
}
return l.toArray(new Node[l.size()]);
}
public int getNodesCount() {
return list.size();
}
public void reorder(int[] perm) {
EmfChildren.this.reorder(perm); // will invoke update() implicitly
fireChangeEvent(new ChangeEvent(this));
}
};
}
As you can see - reorder() doesn't call update() as in the default implementation asthis method is invoked implicitly after the underlying EMF model is updated. (
Our reorder() method in our Children implementation is as follows:
@Override
protected void reorder(int[] perm) {
// Reordering of children. Should ultimately result in the execution of a MoveCommand.
// Assumes that a single node has been moved among its siblings.
// perm[] is an array whose indexes represent the original positions of siblings, and the values represent the updated positions.
int toMoveIndex = -1;
int movedToIndex = -1;
// Detect between which positions the move has been performed.
// Moving from last position is a special case treated after the for-loop.
// When interchanging positions of neighbour nodes, we don't need to know which of the two nodes were actually moved.
for (int i = 0; i < perm.length - 1; i++) {
if (perm[i] == movedToIndex) {
toMoveIndex = i;
break;
}
if (movedToIndex == -1 && perm[i] > i) {
// Found point of change
if (i > 0 && (perm[i] - perm[i - 1]) == 2) {
// node has been moved forward.
movedToIndex = i;
} else if (i == 0 && perm[0] == 1) {
// node has been moved into first position
movedToIndex = 0;
} else {
// node has been moved backward
movedToIndex = perm[i];
toMoveIndex = i;
break;
}
}
}
if (movedToIndex != -1 && toMoveIndex == -1) {
// Moved to end of list
toMoveIndex = perm.length - 1;
}
if (toMoveIndex >= 0 && movedToIndex >= 0) {
// Execute EMF command corresponding to the detected move operation.
EObject movedObject = getNodes()[toMoveIndex].getCookie(EmfCookie.class).getObject();
EObject objectAtNewIndex = getNodes()[movedToIndex].getCookie(EmfCookie.class).getObject();
// Translate index from visual representation, to actual position in unfiltered model.
int emfIndex = ModelUtilities.getChildren(getParent()).indexOf(objectAtNewIndex);
Command moveCmd = MoveCommand.create(getProject().getEditingDomain(), getParent(), null, movedObject, emfIndex);
if (moveCmd.canExecute()) {
getProject().getEditingDomain().getCommandStack().execute(moveCmd);
}
}
}
Posted by Gunnar Reinseth on October 16, 2008 at 09:43 PM PDT #
The section "Reordering Subnodes" in NB-TDG you pointed to before does explain how to properly implement reorder, not using Index.ArrayChildren. (As always, I do not recommend any kind of children other than Children.Keys.) When reorder is called, you simply permute your data model as requested. Really your whole example is not great here because it does not make much sense to reorder system properties. If you had a true data model with a definable and mutable order, then the implementation of reordering would follow naturally.
Posted by Jesse Glick on October 17, 2008 at 03:40 AM PDT #
@Jesse: But then why do I not have a problem when I use Index.ArrayChildren? With Index.ArrayChildren, I'm able to reorder without a problem, while with Children.Keys it seems nigh impossible. (And why do you recommend using Children.Keys? What's wrong with the others?)
Posted by Geertjan Wielenga on October 17, 2008 at 06:26 AM PDT #
Index.ArrayChildren does make it trivial to reorder subnodes, but the reordering does not do anything useful: you are just shuffling around GUI elements. When you have an actual data model you are displaying, then you want to use Children.Keys to reflect that in your view. Adding an Index support is not much work if you follow the example given in NB-TDG.
Posted by Jesse Glick on October 17, 2008 at 06:48 AM PDT #
Hello, I wanted to insert a node inbetween two other nodes (the netbeans project view shows an horizontal bar between two nodes when dragging over).
the problem was that the index in the getDropType methods always returned -1. So I tried, instead of using an AbstractNode, to use an IndexedNode. Now the problem is that the bar between nodes doesn't appear anymore when dragging over.
wtf ?
Thx.
Posted by Arnaud GROSJEAN on July 18, 2010 at 06:20 AM PDT # | https://blogs.oracle.com/geertjan/entry/how_users_can_let_children1 | CC-MAIN-2014-15 | refinedweb | 965 | 50.02 |
Member since 05-15-2018
7
1
Kudos Received
0
Solutions
05-18-2018 10:59 AM
05-18-2018 10:59 AM
I'm using Nifi 1.5. I don't have the create statement for the source (it's an oracle view) but the field in question is a TIMESTAMP(6) in the source DB. The target DB is Impala; the create table for that is create table test ( id STRING, my_value DOUBLE, time_inserted TIMESTAMP, time_updated TIMESTAMP) STORED AS PARQUET LOCATION '/blah/test'; As the Avro input fields are in uppercase, the PutDatabaseRecord processor is using Translate Field Names and I've also set it to quote both column and table identifiers. Unmatched fields/columns are set to ignore. I'll have a try later with 1.6 and see if that solves it, or if not will have a go at a 1.7 build. In the meantime I've split it out into two separate QueryDatabaseTable processors, one for null and one for not null (luckily time_updated is the only nullable timestamp!) Thanks, Toby ... View more
05-17-2018 04:18 PM
05-17-2018 04:18 PM
I'm attempting to write to Implala using PutDatabaseRecord. Everything works fine until I hit a null timestamp, and it tries to cast it to a varchar(19) instead of a timestamp. The data input is from an Oracle DB via QueryDatabaseTable. This generates the following avro embedded schema: {"type":"record","name":"BLAH","namespace":"TEST","fields":[{"name":"ID","type":["null","string"]},{"name":"MY_VALUE","type":["null",{"type":"bytes","logicalType":"decimal","precision":15,"scale":4}]},{"name":"TIME_INSERTED","type":["null",{"type":"long","logicalType":"timestamp-millis"}]},{"name":"TIME_UPDATED","type":["null",{"type":"long","logicalType":"timestamp-millis"}]}]} The actual data is then: [ { "ID" : "71416037", "MY_VALUE" : 58.75, "TIME_INSERTED" : "2018-05-11T22:17:44.000Z", "TIME_UPDATED" : null }, { "ID" : "71416525", "MY_VALUE" : 267.5, "TIME_INSERTED" : "2018-05-11T22:18:25.000Z", "TIME_UPDATED" : "2018-05-15T22:09:37.385Z" } ] Taken in isolation, the second entry with no null values works fine, and the first entry with null works fine, but when trying with both together it fails. Looking at the generated SQL, it appears it's trying to cast the timestamp to a char(19) rather than a timestamp. What's a little confusing is the error talks about the expression null being of type char(19), but there's no cast around the null value. Target table 'test' is incompatible with source expressions. Expression 'null' (type: CHAR(19)) is not compatible with column 'time_updated' (type: TIMESTAMP) ), Query: INSERT INTO `test`(`id`, `my_value`, `time_inserted`, `time_updated`) VALUES (CAST('71416037' AS CHAR(8)), 58.75, '2018-05-11 18:17:44.0', null), (CAST('71416525' AS CHAR(8)), 267.5, '2018-05-11 18:18:25.0', CAST('2018-05-15 18:09:37' AS CHAR(19))).: Any ideas? It seems strange that either in isolation is fine but both together is not. ... View more
Labels:
05-16-2018 03:23 PM
05-16-2018 03:23 PM
Yes absolutely - take a look at Jolt There's a great web-based demo tool for testing transforms. Nifi has support via JoltTransformJSON ... View more
05-16-2018 12:02 PM
05-16-2018 12:02 PM
Hi, I'm using QueryDatabaseTable on an Oracle database to feed into PutKudu (Nifi 1.5) I was getting an error that the primary key did not exist; after some experimenting it's apparent that this is due to a difference in case. Both the Oracle table and the Kudu table were created with uppercase column names, but I understand Impala converts everything to lower case internally. I tried to put the column names in lower case in QueryDatabaseTable, but the results always come back in upper case as the underlying columns in Oracle are all uppercase. Given that Impala/Kudu fields will always be mapped to lowercase would it be reasonable for PutKudu to then map any input fields to lowercase similarly? Other than using ConvertAvroSchema to map every single field from upper to lower (I've got about 80 fields so this doesn't appeal!), is there any other solution to this without the above change? Many thanks, Toby ... View more
I think I've found the issue: Other than upgrading Impala to 2.11 or trying to hack PutParquet to use fixed_len_byte_array rather than binary (is that viable?), are there any ways to work around this? Edit: I'm thinking I can maybe map the avro decimal values to fixed type with some schema conversion between the QueryDatabaseTable and PutParquet processors. Would love to hear any other suggestions though. ... View more
05-15-2018 02:31 PM
05-15-2018 02:31 PM
I'm using avro-tools 1.8.2, Imapala is on 2.10.0-cdh5.13.1 I started checking the data because I was getting an error when trying to query the impala table, which was created from the parquet file produced by PutParquet. I've attached both the avro file from QueryDatabaseTable, and the parquet file produced by PutParquet. Below is the code I used to create and then query the table (paths abbreviated for conciseness): create external table test2 LIKE PARQUET '..../test/577533060432928' <br>STORED AS PARQUET <br>LOCATION '..../test' select * from test2; WARNINGS: File 'hdfs://nameservice1/.../test/577533060432928' has an incompatible Parquet schema for column 'test2.spread'. Column type: DECIMAL(10,0), Parquet schema: optional byte_array SPREAD [i:1 d:1 r:0] avro-parquet.zip ... View more
05-15-2018 02:03 PM
05-15-2018 02:03 PM
I'm attempting to use Nifi to take data from an Oracle database, and then write it as Parquet files to HDFS, from which I'll then build tables for use in Impala. I've setup a QueryDatabaseTable processor and linked it up to PutParquet. By default everything works, but all the values are Strings rather than having any dates, ints, doubles etc. After some quick research I realised I need to set the "Use Avro Logical Types" to true in the QueryDatabaseTable, so I did this. However, when I look at the Avro output from a simple test query, it doesn't look right. Running it through avro-tools tojson I get: {"TRADEID":{"string":"71416037"},"SPREAD":{"bytes":";"}} Why would bytes be showing '";"? I'm expecting a value of 58.75 here. The schema looks ok: { "type" : "record", "name" : "CDS_CTC", "namespace" : "VOL_DATA", "fields" : [ { "name" : "TRADEID", "type" : [ "null", "string" ] }, { "name" : "SPREAD", "type" : [ "null", { "type" : "bytes", "logicalType" : "decimal", "precision" : 10, "scale" : 0 } ] } ] } and without using avro logical types, I get the values I'd expect: {"TRADEID":{"string":"71416037"},"SPREAD":{"string":"58.75"}} Any suggestions please? ... View more
Labels: | https://community.cloudera.com/t5/user/viewprofilepage/user-id/53928 | CC-MAIN-2019-51 | refinedweb | 1,111 | 64.1 |
hi all
i have a question and plz i really need your help
the question is >>>>
A string of characters has balanced parenthesis if each right parentheses occurring in the string is matched with a preceding left parentheses in the same way each right brace in a C++ program is matched with a preceding left brace. Write a program that uses a stack to determine whether a string entered at the keyboard has balanced parentheses.
and this is what i did
>>>>>>>>
Code:#include <iostream> #include <string.h> using namespace std; #define SIZE 100 char C1='('; char C2=')'; class stack { private: char stackChar[SIZE]; // Holds the stack int top; public: stack() { top= 0; } void push(char ch) { if(top==SIZE) { cout << "Stack is FULL!!"<<endl; } stackChar[top] = ch; top++; } char pop(char ch) { if(top==0) { cout << "Stack is EMPTY!!" <<endl; return 0; } top--; return stackChar[top]; } bool balanced (char *ch, char s) { int count=0; while(*ch!= '\0') { if(*ch==C1) { push(C1); count++; } if(*ch==C2) { pop(C1); count--; } } if (count==0) return true; else return false; } }; int main() { stack St; char S1[SIZE]= "My name is (( lady bird ))"; char S2[SIZE]= "(Im (23) years old ))"; char *ch; cin.getline(S1,SIZE); if (St.balanced (ch, S1)) cout<<"The first string is balanced "<<endl; else cout<<"The first string is unbalanced "<<endl; cin.getline(S2,SIZE); if (St.balanced (ch, S2)) cout<<"The second string is balanced "<<endl; else cout<<"The second string is unbalanced "<<endl; return 0; } | http://cboard.cprogramming.com/cplusplus-programming/121581-plzzz-help-stack.html | CC-MAIN-2015-35 | refinedweb | 249 | 77.06 |
Reshaping a data from long to wide in python pandas is done with pivot() function. Pivot() function in pandas is one of the efficient function to transform the data from long to wide format. pivot() Function in python pandas depicted with an example.
Let’s create a simple data frame to demonstrate our reshape example in python pandas
Create dataframe:
import pandas as pd import numpy as np #Create a DataFrame d = { 'countries':['A','B','C','A','B','C'], 'metrics':['population_in_million','population_in_million','population_in_million', 'gdp_percapita','gdp_percapita','gdp_percapita'], 'values':[100,200,120,2000,7000,15000] } df = pd.DataFrame(d,columns=['countries','metrics','values']) df
The dataframe will be like
Reshape long to wide in pandas python with pivot function:
We will reshape the above data frame from long to wide format in R. The above data frame is already in long format.
This can be accomplished with below code
# reshape from long to wide in pandas python df2=df.pivot(index='countries', columns='metrics', values='values') df2
- Pivot function() reshapes the data from long to wide in Pandas python. Countries column is used on index.
- Values of Metrics column is used as column names and values of value column is used as its value.
So the resultant reshaped dataframe will be
| https://www.datasciencemadesimple.com/reshape-long-wide-pandas-python-pivot-function/ | CC-MAIN-2021-17 | refinedweb | 209 | 54.93 |
CodePlexProject Hosting for Open Source Software
Hi,
I just got the 1.6.1 release but I can't compile because the ReCaptcha dll is missing (The type or namespace name 'Recaptcha' could not be found). When I get that from the reCaptcha site I still can't compile because there's no object called RecaptchaLogItem.
Am I missing something fundamental here?
Steven
oops. I forgot to merge the AppCode folder. Sorry.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://blogengine.codeplex.com/discussions/214063 | CC-MAIN-2017-26 | refinedweb | 108 | 85.28 |
Bigtop and Gantry provide limited support for rpc style SOAP.
There is a small but complete working RPC style SOAP example in the RPCSoap subdirectory of the keyword_cookbook directory. It was originally built with the example.bigtop in this directory, but has had code added to make the service work. See the README in that directory for how to run the working example.
The
soap_name keyword controls the base of all WSDL names when ask Gantry to generate WSDL files for you.
While largely intended as documentation,
that name may matter to your clients and should include something specific to your application.
Examples of names that will begin with the
soap_name:
wsdl:definitions name attribute portType name attribute binding name attributes etc.
See wsdl.tt in Gantry's root directory for all the details.
Specify domain information with the
namespace_base controller keyword.
Build the example with:
bigtop -c example.bigtop all
Change to the new Kids directory and look in lib/Kids/GEN/Soap.pm for 'KidSOAPName'.
NOTE: the example built in this way will not work properly, since bigtop makes a stub of the service, leaving you to fill in code. See the RPCSoap subdirectory of the keyword_cookbook directory for a working example. | http://search.cpan.org/~philcrow/Bigtop/docs/keyword_cookbook/controller/soap_name/discussion | CC-MAIN-2014-10 | refinedweb | 204 | 58.28 |
Description
A library for creating command-line applications and running shell commands in Swift.
Features
- run commands, and handle the output. - run commands asynchronously, and be notified when output is available. - access the context your application is running in, like environment variables, standard input, standard output, standard error, the current directory and the command line arguments. - create new such contexts you can run commands in. - handle errors. - read and write files.
SwiftShell alternatives and similar libraries
Based on the "Command Line" category.
Alternatively, view SwiftShell alternatives based on common mentions on social networks and blogs.
Swift Argument ParserStraightforward, type-safe argument parsing for Swift
Commander7.7 3.6 L2 SwiftShell VS CommanderCompose beautiful command line interfaces in Swift
CommandLine7.5 0.0 L2 SwiftShell VS CommandLineA pure Swift library for creating command-line interfaces.
Swiftline7.3 0.0 L5 SwiftShell VS SwiftlineSwiftline is a set of tools to help you create command line applications.
guaka7.1 0.0 L5 SwiftShell VS guakaThe smartest and most beautiful (POSIX compliant) Command line framework for Swift 🤖
SwiftCLI6.5 0.0 L4 SwiftShell VS SwiftCLIA powerful framework for developing CLIs in Swift
Progress.swift4.3 0.0 L5 SwiftShell VS Progress.swift:hourglass: Add beautiful progress bars to your loops.
SwiftyTextTable4.2 0.0 L5 SwiftShell VS SwiftyTextTableA lightweight library for generating text tables.
nef3.9 2.5 SwiftShell VS nef💊 steroids for Xcode Playgrounds
Overlook3.2 0.0 L5 SwiftShell VS OverlookThe Judge, Jury and Executioner for the file system
LineNoise2.6 0.0 SwiftShell VS LineNoiseA pure Swift replacement for readline
TextTable2.4 0.0 L5 SwiftShell VS TextTableSwift package for easily rendering text tables. Inspired by the Python tabulate library.
Ashen1.6 2.6 SwiftShell VS AshenA framework for writing terminal applications in Swift.
🌳 Environment0.7 0.0 SwiftShell VS 🌳 EnvironmentType-safe environment variables in Swift.
Phiole0.4 0.0 L5 SwiftShell VS PhioleAllow to write or read from standards stream or files for script or CLI application
SwiftArgs0.2 0.0 L4 SwiftShell VS SwiftArgsA minimal, pure Swift library for making command-line tools / interfaces.
Appwrite - The Open Source Firebase alternative introduces iOS support
* Code Quality Rankings and insights are calculated and provided by Lumnify.
They vary from L1 to L5 with "L5" being the highest.
Do you think we are missing an alternative of SwiftShell or a related project?
README
Run shell commands | Parse command line arguments | Handle files and directories
Swift 5.1 - 5.3 | Swift 4 | Swift 3 | Swift 2
SwiftShell
A library for creating command-line applications and running shell commands in Swift.
Features
- [x] run commands, and handle the output.
- [x] run commands asynchronously, and be notified when output is available.
- [x] access the context your application is running in, like environment variables, standard input, standard output, standard error, the current directory and the command line arguments.
- [x] create new such contexts you can run commands in.
- [x] handle errors.
- [x] read and write files.
See also
- API Documentation.
- A description of the project on skilled.io.
<!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
Table of Contents
- Example
- Context
- Streams
- Commands
- Setup
- License
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
Example
Print line numbers
#!/usr/bin/env swiftshell import SwiftShell do { // If there is an argument, try opening it as a file. Otherwise use standard input. let input = try main.arguments.first.map {try open($0)} ?? main.stdin input.lines().enumerated().forEach { (linenr,line) in print(linenr+1, ":", line) } // Add a newline at the end. print("") } catch { exit(error) }
Launched with e.g.
cat long.txt | print_linenumbers.swift or
print_linenumbers.swift long.txt this will print the line number at the beginning of each line.
Others
- Test the latest commit (using make and/or Swift).
- Run a shell command in the middle of a method chain.
- Move files to the trash.
Context
All commands (a.k.a. processes) you run in SwiftShell need context: environment variables, the current working directory, standard input, standard output and standard error (standard streams).
public struct CustomContext: Context, CommandRunning { public var env: [String: String] public var currentdirectory: String public var stdin: ReadableStream public var stdout: WritableStream public var stderror: WritableStream }
You can create a copy of your application's context:
let context = CustomContext(main), or create a new empty one:
let context = CustomContext(). Everything is mutable, so you can set e.g. the current directory or redirect standard error to a file.
Main context
The global variable
main is the Context for the application itself. In addition to the properties mentioned above it also has these:
public var encoding: String.EncodingThe default encoding used when opening files or creating new streams.
public let tempdirectory: StringA temporary directory you can use for temporary stuff.
public let arguments: [String]The arguments used when launching the application.
public let path: StringThe path to the application.
main.stdout is for normal output, like Swift's
main.stderror is for error output, and
main.stdin is the standard input to your application, provided by something like
somecommand | yourapplication in the terminal.
Commands can't change the context they run in (or anything else internally in your application) so e.g.
main.run("cd", "somedirectory") will achieve nothing. Use
main.currentdirectory = "somedirectory" instead, this changes the current working directory for the entire application.
Example
Prepare a context similar to a new macOS user account's environment in the terminal (from kareman/testcommit):
import SwiftShell import Foundation extension Dictionary where Key:Hashable { public func filterToDictionary <C: Collection> (keys: C) -> [Key:Value] where C.Iterator.Element == Key, C.IndexDistance == Int { var result = [Key:Value](minimumCapacity: keys.count) for key in keys { result[key] = self[key] } return result } } // Prepare an environment as close to a new OS X user account as possible. var cleanctx = CustomContext(main) let cleanenvvars = ["TERM_PROGRAM", "SHELL", "TERM", "TMPDIR", "Apple_PubSub_Socket_Render", "TERM_PROGRAM_VERSION", "TERM_SESSION_ID", "USER", "SSH_AUTH_SOCK", "__CF_USER_TEXT_ENCODING", "XPC_FLAGS", "XPC_SERVICE_NAME", "SHLVL", "HOME", "LOGNAME", "LC_CTYPE", "_"] cleanctx.env = cleanctx.env.filterToDictionary(keys: cleanenvvars) cleanctx.env["PATH"] = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" // Create a temporary directory for testing. cleanctx.currentdirectory = main.tempdirectory
Streams
The protocols ReadableStream and WritableStream in
Context above can read and write text from/to commands, files or the application's own standard streams. They both have an
.encoding property they use when encoding/decoding text.
You can use
let (input,output) = streams() to create a new pair of streams. What you write to
input you can read from
output.
WritableStream
When writing to a WritableStream you normally use
main.stdout.print("everything is fine") main.stderror.print("no wait, something went wrong ...") let writefile = try open(forWriting: path) // WritableStream writefile.print("1", 2, 3/5, separator: "+", terminator: "=")
If you want to be taken literally, use
.write instead. It doesn't add a newline and writes exactly and only what you write:
writefile.write("Read my lips:")
You can close the stream, so anyone who tries to read from the other end won't have to wait around forever:
writefile.close()
ReadableStream
When reading from a ReadableStream you can read everything at once:
let readfile = try open(path) // ReadableStream let contents = readfile.read()
This will read everything and wait for the stream to be closed if it isn't already.
You can also read it asynchronously, that is read whatever is in there now and continue without waiting for it to be closed:
while let text = main.stdin.readSome() { // do something with ‘text’... }
.readSome() returns
String? - if there is anything there it returns it, if the stream is closed it returns nil, and if there is nothing there and the stream is still open it will wait until either there is more content or the stream is closed.
Another way to read asynchronously is to use the
lines method which creates a lazy sequence of Strings, one for each line in the stream:
for line in main.stdin.lines() { // ... }
Or instead of stopping and waiting for any output you can be notified whenever there is something in the stream:
main.stdin.onOutput { stream in // ‘stream’ refers to main.stdin }
Data
In addition to text, streams can also handle raw Data:
let data = Data(...) writer.write(data: data) reader.readSomeData() reader.readData()
Commands
All Contexts (
CustomContext and
main) implement
CommandRunning, which means they can run commands using themselves as the Context. ReadableStream and String can also run commands, they use
main as the Context and themselves as
.stdin. As a shortcut you can just use
run(...) instead of
main.run(...)
There are 4 different ways of running a command:
Run
The simplest is to just run the command, wait until it's finished and return the results:
let result1 = run("/usr/bin/executable", "argument1", "argument2") let result2 = run("executable", "argument1", "argument2")
If you don't provide the full path to the executable, then SwiftShell will try to find it in any of the directories in the
PATH environment variable.
run returns the following information:
/// Output from a `run` command. public final class RunOutput { /// The error from running the command, if any. let error: CommandError? /// Standard output, trimmed for whitespace and newline if it is single-line. let stdout: String /// Standard error, trimmed for whitespace and newline if it is single-line. let stderror: String /// The exit code of the command. Anything but 0 means there was an error. let exitcode: Int /// Checks if the exit code is 0. let succeeded: Bool }
For example:
let date = run("date", "-u").stdout print("Today's date in UTC is " + date)
Print output
try runAndPrint("executable", "arg")
This runs a command like in the terminal, where any output goes to the Context's (
main in this case)
.stdout and
.stderror respectively. If the executable could not be found, was inaccessible or not executable, or the command returned with an exit code other than zero, then
runAndPrint will throw a
CommandError.
The name may seem a bit cumbersome, but it explains exactly what it does. SwiftShell never prints anything without explicitly being told to.
Asynchronous
let command = runAsync("cmd", "-n", 245).onCompletion { command in // be notified when the command is finished. } command.stdout.onOutput { stdout in // be notified when the command produces output (only on macOS). } // do something with ‘command’ while it is still running. try command.finish() // wait for it to finish.
runAsync launches a command and continues before it's finished. It returns
AsyncCommand which contains this:
public let stdout: ReadableStream public let stderror: ReadableStream /// Is the command still running? public var isRunning: Bool { get } /// Terminates the command by sending the SIGTERM signal. public func stop() /// Interrupts the command by sending the SIGINT signal. public func interrupt() /// Temporarily suspends a command. Call resume() to resume a suspended command. public func suspend() -> Bool /// Resumes a command previously suspended with suspend(). public func resume() -> Bool /// Waits for this command to finish. public func finish() throws -> Self /// Waits for command to finish, then returns with exit code. public func exitcode() -> Int /// Waits for the command to finish, then returns why the command terminated. /// - returns: `.exited` if the command exited normally, otherwise `.uncaughtSignal`. public func terminationReason() -> Process.TerminationReason /// Takes a closure to be called when the command has finished. public func onCompletion(_ handler: @escaping (AsyncCommand) -> Void) -> Self
You can process standard output and standard error, and optionally wait until it's finished and handle any errors.
If you read all of command.stderror or command.stdout it will automatically wait for the command to close its streams (and presumably finish running). You can still call
finish() to check for errors.
runAsyncAndPrint does the same as
runAsync, but prints any output directly and it's return type
PrintedAsyncCommand doesn't have the
.stdout and
.stderror properties.
Parameters
The
run* functions above take 2 different types of parameters:
(_ executable: String, _ args: Any ...)
If the path to the executable is without any
/, SwiftShell will try to find the full path using the
which shell command, which searches the directories in the
PATH environment variable in order.
The array of arguments can contain any type, since everything is convertible to strings in Swift. If it contains any arrays it will be flattened so only the elements will be used, not the arrays themselves.
try runAndPrint("echo", "We are", 4, "arguments") // echo "We are" 4 arguments let array = ["But", "we", "are"] try runAndPrint("echo", array, array.count + 2, "arguments") // echo But we are 5 arguments
(bash bashcommand: String)
These are the commands you normally use in the Terminal. You can use pipes and redirection and all that good stuff:
try runAndPrint(bash: "cmd1 arg1 | cmd2 > output.txt")
Note that you can achieve the same thing in pure SwiftShell, though nowhere near as succinctly:
var file = try open(forWriting: "output.txt") runAsync("cmd1", "arg1").stdout.runAsync("cmd2").stdout.write(to: &file)
Errors
If the command provided to
runAsync could not be launched for any reason the program will print the error to standard error and exit, as is usual in scripts. The
runAsync("cmd").finish() method throws an error if the exit code of the command is anything but 0:
let someCommand = runAsync("cmd", "-n", 245) // ... do { try someCommand.finish() } catch let CommandError.returnedErrorCode(command, errorcode) { print("Command '\(command)' finished with exit code \(errorcode).") }
The
runAndPrint command can also throw this error, in addition to this one if the command could not be launched:
} catch CommandError.inAccessibleExecutable(let path) { // ‘path’ is the full path to the executable }
Instead of dealing with the values from these errors you can just print them:
} catch { print(error) }
... or if they are sufficiently serious you can print them to standard error and exit:
} catch { exit(error) }
When at the top code level you don't need to catch any errors, but you still have to use
try.
Setup
Stand-alone project
If you put Misc/swiftshell-init somewhere in your $PATH you can create a new project with
swiftshell-init <name>. This creates a new folder, initialises a Swift Package Manager executable folder structure, downloads the latest version of SwiftShell, creates an Xcode project and opens it. After running
swift build you can find the compiled executable at
.build/debug/<name>.
Script file using Marathon
First add SwiftShell to Marathon:
marathon add
Then run your Swift scripts with
marathon run <name>.swift. Or add
#!/usr/bin/env marathon run to the top of every script file and run them with
./<name>.swift.
Swift Package Manager
Add
.package(url: "", from: "5.1.0") to your Package.swift:
// swift-tools-version:5.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "ProjectName", platforms: [.macOS(.v10_13)], dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "", from: "5.1.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "ProjectName", dependencies: ["SwiftShell"]), ] )
and run
swift build.
Carthage
Add
github "kareman/SwiftShell" >= 5.1 to your Cartfile, then run
carthage update and add the resulting framework to the "Embedded Binaries" section of the application. See Carthage's README for further instructions.
CocoaPods
Add
SwiftShell to your
Podfile.
pod 'SwiftShell', '>= 5.1.0'
Then run
pod install to install it.
License
Released under the MIT License (MIT),
Kåre Morstøl, NotTooBad Software
*Note that all licence references and agreements mentioned in the SwiftShell README section above are relevant to that project's source code only. | https://swift.libhunt.com/swiftshell-alternatives | CC-MAIN-2022-40 | refinedweb | 2,598 | 58.28 |
strtol - convert string to a long integer
#include <stdlib.h> long int strtol(const char *str, char **endptr, int base);
The strtol() function converts the initial portion of the string pointed to by str to a type long int representation. First it decomposes the input string into three parts: an initial, possibly empty, sequence of white-space characters (as specified by isspace()); a subject sequence interpreted as an integer represented in some radix determined by the value of base; and a final string of one or more unrecognised characters, including the terminating null byte of the input string. Then it attempts to convert the subject sequence to anol() function will not change the setting of errno if successful.
Because 0, LONG_MIN and LONG_MAX are returned on error and are also valid returns on success, an application wishing to check for error situations should set errno to 0, then call strtol(), then check errno.
Upon successful completion strtol() returns the converted value, if any. If no conversion could be performed, 0 is returned and errno may be set to [EINVAL].
If the correct value is outside the range of representable values, LONG_MAX or LONG_MIN is returned (according to the sign of the value), and errno is set to [ERANGE].
The strtol() function will fail if:
- [ERANGE]
- The value to be returned is not representable.
The strtol() function may fail if:
- [EINVAL]
- The value of base is not supported.
None.
None.
None.
isalpha(), scanf(), strtod(), <stdlib.h>.
Derived from Issue 1 of the SVID. | http://pubs.opengroup.org/onlinepubs/007908799/xsh/strtol.html | CC-MAIN-2013-20 | refinedweb | 252 | 58.92 |
20 September 2012 11:39 [Source: ICIS news]
SINGAPORE (ICIS)--Idemitsu Kosan’s 40,000 tonne/year methyl ethyl ketone (MEK) plant at Tokuyama in ?xml:namespace>
The plant was taken off line on 15 September and is expected to resume operation on 5 November, the company source said.
The company will reduce its exports in October from around 1,000 tonnes/month to less than 500 tonnes, a source close to the company said.
“They [Idemitsu Kosan] have the option not to export next month if prices are not attractive. They can focus on domestic sales,” the source said.
MEK spot prices in northeast Asia were at $1,325/tonne (€1,020) CFR (cost and freight) NE (northeast)
( | http://www.icis.com/Articles/2012/09/20/9597084/japans-idemitsu-kosan-mek-plant-in-tokuyama-shut-for-maintenance.html | CC-MAIN-2014-49 | refinedweb | 119 | 70.13 |
This article was originally published on my blog at
useEffect is meant to handle any sort of "side effect" (making a change in some external system, logging to the console, making an HTTP request, etc...) that is triggered by a change in your component's data or in reaction to the component rendering. It replaces
componentDidMount,
componentDidUnmount, and
componentDidReceiveProps, or some code that is run any time your state changes. It can be challenging to grasp the nuances of its use, but by understanding when it runs and how to control that, it can become a little bit easier to wrap your head around.
In this article we'll look at how to get an effect to run after every render, just once, or when a particular piece of data changes. We'll also look at the difference between the effect itself, and how to clean up after itself.
The code referenced in this article can be found at
Run the effect on every render
For the smallest example possible, we have the typical example of the
useEffect which logs to the console the value of
count after every render. It is important to note:
useEffect is run after the render. Always think: First render, then effect.
import React, { useState, useEffect } from "react"; export default function Counter() { const [count, setCount] = useState(0); useEffect(() => { console.log(`The count is ${count}`); }); return ( <div> <p>Count is {count}</p> <button onClick={() => { setCount(count + 1); }} > increase </button> </div> ); }
Why does this example run after every render? The reason is because no arguments were passed as the 2nd argument to
useEffect. React uses the 2nd argument to determine whether or not it needs to execute the function passed to useEffect... by passing nothing, React will run the effect every time.
This may cause performance issues or just be a tad overkill, so let's see how to add a little extra control to when our effect functions are run.
Run the effect only once
Let's say we only wanted the effect to run a single time... think of this as a replacement for
componentDidMount. To do this, pass a
[] as the 2nd argument to useEffect:
import React, { useEffect } from "react"; export default function Mounted() { useEffect(() => { console.log("mounted"); }, []); return <div>This component has been mounted.</div>; }
Run the effect when data changes
If what you really want is to run the effect only when a specific value changes... say to update some local storage or trigger an HTTP request, you'll want to pass those values you are watching for changes as the 2nd argument. This example will write the user's name to local storage after every time it is updated (triggered by the onChange of the input).
import React, { useState, useEffect } from "react"; export default function Listen() { const [name, setName] = useState(""); useEffect( () => { localStorage.setItem("name", name); }, [name] ); return ( <div> <input type="text" onChange={e => { setName(e.target.value); }} value={name} /> </div> ); }
Cleaning up from your effect
Sometimes you need to undo what you've done... to clean up after yourself when the component is to be unmounted. To accomplish this you can return a function from the function passed to
useEffect... that's a mouthful but let's see a real example, of what would be both
componentDidMount and
componentDidUnmount combined into a single effect.
import React, { useEffect } from "react"; export default function Listen() { useEffect(() => { const listener = () => { console.log("I have been resized"); }; window.addEventListener("resize", listener); return () => { window.removeEventListener("resize", listener); }; }, []); return <div>resize me</div>; }
Avoid setting state on unmounted components
Because effects run after the component has finished rendering, and because they often contain asynchronous code, it's possible that by the time the asynchronous code resolves, the component is no longer even mounted! When it gets around to calling the
setData function to update the state, you'll receive an error that you can't update state on an unmounted component.
The way we can solve the stated (no pun intended) issue above, is by using a local variable and taking advantage of the "cleanup" function returned from our effect function. By starting it off as
true, we can toggle it to
false when the effect is cleaned up, and use this variable to determine whether we still want to call the
setData function or not.
import React, { useState, useEffect } from "react"; import Axios from "axios"; export default function Fetcher({ url }) { const [data, setData] = useState(null); useEffect( () => { // Start it off by assuming the component is still mounted let mounted = true; const loadData = async () => { const response = await Axios.get(url); // We have a response, but let's first check if component is still mounted if (mounted) { setData(response.data); } }; loadData(); return () => { // When cleanup is called, toggle the mounted variable to false mounted = false; }; }, [url] ); if (!data) { return <div>Loading data from {url}</div>; } return <div>{JSON.stringify(data)}</div>; }
Cancelling an Axios call when component unmounts
With the example above, you may have asked yourself... why even bother waiting for a response if we know for a fact we don't even need it. It turns out Axios has a way to cancel a request. We can use the same method as above, using a local variable along with an effect cleanup function, but this time the local variable will be an Axios cancellation source/token, allowing us to call
source.cancel() to stop Axios in its tracks.
Just keep in mind that this will raise an exception that we should catch. Axios provides us a way using
Axios.isCancel(error) to determine if what we caught was because of our own cancellation or some other unexpected error.
import React, { useState, useEffect } from "react"; import Axios from "axios"; export default function Fetcher({ url }) { const [data, setData] = useState(null); useEffect( () => { // Set up a cancellation source let source = Axios.CancelToken.source(); const loadData = async () => { try { const response = await Axios.get(url, { // Assign the source.token to this request cancelToken: source.token }); setData(response.data); } catch (error) { // Is this error because we cancelled it ourselves? if (Axios.isCancel(error)) { console.log(`call for ${url} was cancelled`); } else { throw error; } } }; loadData(); return () => { // Let's cancel the request on effect cleanup source.cancel(); }; }, [url] ); if (!data) { return <div>Loading data from {url}</div>; } return <div>{JSON.stringify(data)}</div>; }
Conclusion
I hope that this article was able to shed some light on a few different ways to take advantage of effects, what causes them to be executed, and how to deal with the issue of an effect possibly executing code after the component has already been unmounted. With
useEffect we're able to combine both the setup and the cleanup together, where in class based components you'd be required to split the functionality across the
componentDidMount and
componentDidUnmount lifecycle events.
Discussion (3)
Thank you, Leigh for the article~
I only knew about
Avoid setting state on unmounted componentsway of not setting a state when a component unmounts.
Surprising that Axios provides a way to cancel a request, which would be more efficient 😮
No prob, Sung! Thanks for reading. Fetch also provides a way to cancel a request, I made a video about it here if you're interested: youtu.be/JGASDKLZcdw
Thanks Leigh~
I see so many videos on your page, as well. 😮
youtube.com/user/leighhalliday | https://dev.to/leighhalliday/using-the-useeffect-hook-3193 | CC-MAIN-2021-43 | refinedweb | 1,214 | 53 |
How to use add_subplot() in matplotlib
In this post, we will discuss one of the most used functions in matplotlib. At the end of this article, you will know how to use add_subplot() in matplotlib. If there is a need for you to be here, it is good to assume that you have already installed matplotlib on your machine.
However, a short description of the installation is provided. Feel free to skip it if you have already installed matplotlib.
Installation of matplotlib
It is often a good idea to use the Python package manager pip for installing packages so you don’t have version conflicts. To install matplotlib, run the following command on your command prompt.
pip install matplotlib
This should install everything that’s necessary. Import the package on your Python shell to check if it was installed correctly.
The use of matplotlib add_subplot()
First, let’s see what a subplot actually means. A subplot is a way to split the available region into a grid of plots so that we will be able to plot multiple graphs in a single window. You might need to use this when there’s is a need for you to show multiple plots at the same time.
The add_subplot() has 3 arguments. The first one being the number of rows in the grid, the second one being the number of columns in the grid and the third one being the position at which the new subplot must be placed.
Example usage for the above is:
from matplotlib import pyplot as plt fig = plt.figure() # Adds a subplot at the 1st position fig.add_subplot(2, 2, 1) plt.plot([1, 2, 3], [1, 2, 3]) # Adds a subplot at the 4th position fig.add_subplot(2, 2, 4) plt.plot([3, 2, 1], [1, 2, 3]) fig.show()
The output for the above code is:
It is to be noted that fig.add_subplot(2, 2, 1) is equivalent to fig.add_subplot(221). The arguments can be specified as a sequence without separating them by commas. You can plot the subplots by using the plot function of pyplot. The subplots will be filled in the order of plotting.
I hope you found this article helpful for understanding add_subplot() in matplotlib.
See also: | https://www.codespeedy.com/use-add_subplot-in-matplotlib/ | CC-MAIN-2021-17 | refinedweb | 377 | 74.39 |
77.7k●88●690●1201
accept rate:
24%.
"This is something the software must do"
But how must the software do it? It seems that the order of the ways in the relation/members field is still not correct, from time to time it gives me discontinuous graphs. I read everywhere that ways do not need to be sorted, and sure, I can plot 16 lines separately to make a trail, but what if I want to offer a relation as a GPX file? Those need to be sorted, right?
Maybe the question is: Is the proper way to sort the nodes in a relation anywhere in the relation object? If so, where is it? Or do I need to write some code to find the closed "first node of a way" to the other "last node of a way" and sort based on that? Is that what the software must do?
Some more info on what I'm trying to do:
Reading your stackoverflow post, I am not sure if you are distinguishing between ordering the member ways, and ordering the nodes within each way.
E.g. suppose a relation runs from east to west and all members are correctly sorted from east to west. Within any given member way, the nodes might happen to run from east to west or west to east, as ways (unless they are one way streets) have an arbitrary direction. So if you are trying to order nodes within a member way you need to pick the right one of the two possible directions. That information is not contained in the relation itself. (Apologies if you already know all this).
Other things to bear in mind
There may be nodes or ways with specific roles, e.g. guidepost, that you probably would not want to try to sort.
Recreational trails in the real world are not always "sortable", there may be spurs, alternate routes etc. Recently there has been a trend to try to identify these with roles within relations (), but you can't rely on that being the case.
While recreational routes ideally should be sorted by mappers who input them to OSM, not everybody does this, and there is nothing in the editors that forces them to do so. Even if a route is sorted initially, the sorting can get broken quite easily for large relations, often by mappers editing member ways for reasons unrelated to the route relation. I often find hiking relations I have carefully sorted in the past have been "unsorted" by subsequent edits.
Ok,thanx, clear, the data model is just what it is. I do wonder how GPX trails are generated by some websites then. They probably do some math to sort based on last/first coordinates of trails.
If you look at the output that some tools like generate, you can see how it's arranging various pieces of relations.
If you have the constituent geometries in a PostGIS database as linestrings, then ST_LineMerge can usually do a pretty good job of piecing them together to make continuous lines.
Once you sign in you will be able to subscribe for any updates here
Answers
Answers and Comments
Markdown Basics
learn more about Markdown
This is the support site for OpenStreetMap.
Question tags:
import ×187
ways ×153
extract ×79
question asked: 21 Jul '16, 12:20
question was seen: 2,774 times
last updated: 17 Jul, 11:30! | https://help.openstreetmap.org/questions/51019/does-order-of-ways-on-relation-members-is-random?sort=oldest | CC-MAIN-2021-43 | refinedweb | 572 | 68.91 |
Problem with JWindow
2015-10-11 Views:0
I have a very important question....
I created a small application and when i launch it, i'd like to have a JWindow displayed on my screen only during 5 seconds.... So i run my application, my JWindow is displayed during 5 seconds and then the application "really" begins.
But how do i have to proceed to have my JWindow displayed only during 5 seconds and then close automatically???
Thanx very much for helping....
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
public class SplashWindow
public static void main(String[] args)
JFrame f = new JFrame();
showSplash(f);
JPanel panel = new JPanel();
panel.setBackground(Color.red);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(panel);
f.setSize(400,300);
f.setLocationRelativeTo(null);
private static void showSplash(final Component c)
JLabel label = new JLabel("hang on, it's coming...", JLabel.CENTER);
final JWindow w = new JWindow();
w.getContentPane().add(label);
w.setSize(200,200);
w.setLocationRelativeTo(null);
w.setVisible(true);
final Timer timer = new Timer(5000, new ActionListener()
public void actionPerformed(ActionEvent e)
w.dispose();
c.setVisible(true);
timer.setRepeats(false);
timer.start();
}
Jpopupmenu visibility problem with JWindows
Category:DefaultRelease time:2015-10-11Views:130
Hello, BACKGROUND: I am attempting to implement a feature similar to one found in the netbeans IDE for a programming editor I am helping to write. The feature is an autocomplete/function suggestion based on the current word being typed, and an api po[More]
Two very STRANGE problems with JWindow and JTextField
Category:DefaultRelease time:-0001-11-30Views:130
I am having some trouble in the program that I am making. It is a Swing based GUI. I have a JWindow with a JPanel in it that holds JTextFields and JLabels. problem1----I can't see a caret in any of the textfields but I can still enter text. problem2-[More]
Problems with JWindow
Category:DefaultRelease time:-0001-11-30Views:130
Hello! I was trying to make a splash screen with JWindow class. But nothing but a blank JWindow is shown after the program is run. I've already searched the forum for solution to this kind of problem and I found that few had similar problems. Accordi[More]
AlwaysOnTop problem for JWindows
Category:DefaultRelease time:-0001-11-30Views:130
Hello everyone.I have the following problem I got an application that allows user to create multiple JWindows under one JFrame. The parent JFrame itself is not set to be AlwaysOnTop, neither are JWindows. This is optional. Each JWindow can be set to[More]
Problem with JWindow
Category:DefaultRelease time:2015-10-11Views:130[More]
Problem with Mnemonic Alt F4 with JWindow in solaris OS urgent!......
Category:DefaultRelease time:-0001-11-30Views:130
hi all I have a problem with JWindow i created a menu where in i have all menuitems as i needed with a close MenuItem with Mnemonic ALT F4 i could not able to close the JWindow in solaris as iam not able to catch th e ALT F4 event please help guys an[More]
Multiple Threads Problem
Category:DefaultRelease time:2015-10-11Views:130
Hi, I am new to Java Threading and the current program that I am working is having problems. The program basically paints lines and dots or onto a JPanel which displays an image. There exists a thread here to suspend and resume the drawing at the use[More]
Help in jwindow
Category:DefaultRelease time:-0001-11-30Views:130
hi there i want to build an application with jwindow but i have a problem , the jwindow doesn't have a taskbar button how can i create oneI am not sure if there is no way (I am not an expert) but I would think that it might be easier to change JFrame[More]
JApplet to create Messenger like alert window
Category:DefaultRelease time:-0001-11-30Views:130
Hi, I have a JApplet which allow users to perform daily business process, mostly using the whole container, without any JFrame and JWindow. JDK used: 1.5.0_09 Now, I need to implement some sort of Collaboration system, to alert the user whenever ther[More]
Using JWindow problem..
Category:DefaultRelease time:2015-10-11Views:130
Hi I am using JWindow for showing a splash window before the application starts. First i use a JPasswordField for Login but i unable i type in it then i use progress bar and still it is unable to get any value for update. when i use JFrame it all wor[More]
I am having a crash problem
Category:DefaultRelease time:2015-10-11Views:130
and it seems to be getting worse. Specifically, I have a G4 AGP, with 8xxRAM 1.3giggle cpu three firewire devices, Maxtor HD, buffalo HD and lacie dvd burner (multi recorder). I upgraded the internal DVD to a Samsung burner a long while ago. This pro[More]
- 1 Adobe air install crashes
- 2 How do I share music between two iTunes accounts?
- 3 Vendor Change in item conditions for ME21N
- 4 Getting Date in the form in JSP
- 5 How do you change the date recieved to reflect the correct time & date?
- 6 Desktop disfunctional following Inkwell fix
- 7 How do I get Itunes to recognize my new Ipod 5?
- 8 Save variant
- 9 Advanced Printing Setup in Reader 9.5.5
- 10 Technical Name of Cube
- PC/64/Windows 7/XIStandard recently installed/unable to put footer into document because I can't move to the bottom of the image when in footer application mode. Display is at recommended 1920x1080. Is there a solution or is it a flaw in the program?
- Is there a way to keep apps from running in the background?
- How do I get the music from my iPod classic onto my computer if it came from a different iTunes account?
- Year End Transactions
- Macbook Air second thoughts. PLEASE RESPOND.
- OBI EE 10 1.3.3.O
- URL never changes regardless of which page I am on, is there a fix?
- Outlook and BB - items deleted from outlook calendar not shown as deleted in blackberry?? WHY?
- HT4461 Error 1004 please try again later?
- Why are the new iPhones much more expensive in Canada? | http://www.amicuk.com/problem-with-jwindow/ | CC-MAIN-2018-51 | refinedweb | 1,036 | 52.8 |
yp, as shown below:
Also have a look at this NBViewer example..
Asynchronous flow
It's also possible to use
ipypb for tracking tasks that are executed asyncrhonously or in parallel. The major use case is when the order of executed tasks from a task pool doesn't correspond to the desired order for displaying a progress. In this case, you can instruct
ipypb to preserve the desired order by submitting a description of the progress hierarchy. Below is an example for simple heirarchy consisting of three levels:
i <-- j <-- k. Progress on each parent level depends on full exectunion of its sublevels. Note how levels
k:1 and
k:2 get moved to the group
j:0 they belong to, even though initially they appear in the end, below the
j:1 group:
Note: this feature is currently in provisional state, which means that its API main change in future releases. In order to test it, do
from ipypb import chain
Install
pip install --upgrade ipypb
Requirements
Python 3.6+ and IPython v.5.6+ excluding v.6.1 and v.6.2
Limitations
- The feature to erase progressbar when loop is over is not yet supported.
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/ipypb/ | CC-MAIN-2022-27 | refinedweb | 227 | 64.51 |
Provided by: manpages-dev_4.16-1_all
NAME
flock - apply or remove an advisory lock on an open file
SYNOPSIS
#include <sys/file.h> int flock(int fd, int operation);
DESCRIPTION
Apply or remove an advisory lock on the open file specified by fd. The argument.
CONFORMING TO
4.4BSD (the flock() call first appeared in 4.2BSD). A version of flock(), possibly implemented in terms of fcntl(2), appears on most UNIX systems.
NOTES.).) NFS details. Since Linux 2.6.37, the kernel supports a compatibility mode that allows flock() locks (and also fcntl(2) byte region locks) to be treated as local; see the discussion of the local_lock option in nfs(5).
SEE ALSO
flock(1), close(2), dup(2), execve(2), fcntl(2), fork(2), open(2), lockf(3), lslocks(8) Documentation/filesystems/locks.txt in the Linux kernel source tree (Documentation/locks.txt in older kernels)
COLOPHON
This page is part of release 4.16 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. | http://manpages.ubuntu.com/manpages/cosmic/man2/flock.2.html | CC-MAIN-2019-47 | refinedweb | 184 | 59.4 |
1.1 anton 1: \ count execution of control-flow edges 2: 1.5 ! anton 3: \ Copyright (C) 2004: 21: \ relies on some Gforth internals 22: 23: \ !! assumption: each file is included only once; otherwise you get 24: \ the counts for just one of the instances of the file. This can be 25: \ fixed by making sure that every source position occurs only once as 26: \ a profile point. 27: 1.2 anton 28: true constant count-calls? \ do some profiling of colon definitions etc. 29: 1.3 anton 30: \ for true COUNT-CALLS?: 31: 32: \ What data do I need for evaluating the effectiveness of (partial) inlining? 33: 34: \ static and dynamic counts of everything: 35: 36: \ original BB length (histogram and average) 37: \ BB length with partial inlining (histogram and average) 38: \ since we cannot partially inline library calls, we use a parameter 39: \ that represents the amount of partial inlining we can expect there. 40: \ number of tail calls (original and after partial inlining) 41: \ number of calls (original and after partial inlining) 42: \ reason for BB end: call, return, execute, branch 43: 44: \ how many static calls are there to a word? How many of the dynamic 45: \ calls call just a single word? 46: 1.1 anton 47: struct 48: cell% field profile-next 49: cell% 2* field profile-count 50: cell% 2* field profile-sourcepos 51: cell% field profile-char \ character position in line 1.2 anton 52: count-calls? [if] 1.3 anton 53: cell% field profile-colondef? \ is this a colon definition start 1.2 anton 54: cell% field profile-calls \ static calls to the colon def 55: cell% field profile-straight-line \ may contain calls, but no other CF 56: cell% field profile-calls-from \ static calls in the colon def 57: [endif] 1.1 anton 58: end-struct profile% \ profile point 59: 60: variable profile-points \ linked list of profile% 61: 0 profile-points ! 1.2 anton 62: variable next-profile-point-p \ the address where the next pp will be stored 63: profile-points next-profile-point-p ! 64: count-calls? [if] 65: variable last-colondef-profile \ pointer to the pp of last colon definition 66: [endif] 67: 1.1 anton 68: : new-profile-point ( -- addr ) 69: profile% %alloc >r 70: 0. r@ profile-count 2! 71: current-sourcepos r@ profile-sourcepos 2! 72: >in @ r@ profile-char ! 1.2 anton 73: [ count-calls? ] [if] 74: r@ profile-colondef? off 75: 0 r@ profile-calls ! 76: r@ profile-straight-line on 77: 0 r@ profile-calls-from ! 78: [endif] 79: 0 r@ profile-next ! 80: r@ next-profile-point-p @ ! 81: r@ profile-next next-profile-point-p ! 1.1 anton 82: r> ; 83: 84: : print-profile ( -- ) 85: profile-points @ begin 86: dup while 87: dup >r 88: r@ profile-sourcepos 2@ .sourcepos ." :" 89: r@ profile-char @ 0 .r ." : " 90: r@ profile-count 2@ 0 d.r cr 91: r> profile-next @ 92: repeat 93: drop ; 94: 1.2 anton 95: : print-profile-coldef ( -- ) 96: profile-points @ begin 97: dup while 98: dup >r 99: r@ profile-colondef? @ if 100: r@ profile-sourcepos 2@ .sourcepos ." :" 101: r@ profile-char @ 0 .r ." : " 102: r@ profile-count 2@ 0 d.r 103: r@ profile-straight-line @ space . 104: cr 105: endif 106: r> profile-next @ 107: repeat 108: drop ; 109: 110: 111: : dinc ( d-addr -- ) 112: \ increment double pointed to by d-addr 113: dup 2@ 1. d+ rot 2! ; 114: 115: : profile-this ( -- ) 116: new-profile-point profile-count POSTPONE literal POSTPONE dinc ; 117: 118: \ Various words trigger PROFILE-THIS. In order to avoid getting 119: \ several calls to PROFILE-THIS from a compiling word (like ?EXIT), we 120: \ just wait until the next word is parsed by the text interpreter (in 121: \ compile state) and call PROFILE-THIS only once then. The whole 122: \ BEFORE-WORD hooking etc. is there for this. 123: 124: \ The reason that we do this is because we use the source position for 125: \ the profiling information, and there's only one source position for 126: \ ?EXIT. If we used the threaded code position instead, we would see 127: \ that ?EXIT compiles to several threaded-code words, and could use 128: \ different profile points for them. However, usually dealing with 129: \ the source is more practical. 130: 131: \ Another benefit is that we can ask for profiling anywhere in a 132: \ control-flow word (even before it compiles its own stuff). 133: 134: \ Potential problem: Consider "COMPILING ] [" where COMPILING compiles 135: \ a whole colon definition (and triggers our profiler), but during the 136: \ compilation of the colon definition there is no parsing. Afterwards 137: \ you get interpret state at first (no profiling, either), but after 138: \ the "]" you get parsing in compile state, and PROFILE-THIS gets 139: \ called (and compiles code that is never executed). It would be 140: \ better if we had a way of knowing whether we are in a colon def or 141: \ not (and used that knowledge instead of STATE). 142: 143: Defer before-word-profile ( -- ) 144: ' noop IS before-word-profile 145: 146: : before-word1 ( -- ) 147: before-word-profile defers before-word ; 148: 149: ' before-word1 IS before-word 150: 151: : profile-this-compiling ( -- ) 152: state @ if 153: profile-this 154: ['] noop IS before-word-profile 155: endif ; 156: 157: : cock-profiler ( -- ) 158: \ as in cock the gun - pull the trigger 159: ['] profile-this-compiling IS before-word-profile 160: [ count-calls? ] [if] \ we are at a non-colondef profile point 161: last-colondef-profile @ profile-straight-line off 162: [endif] 163: ; 164: 165: : hook-profiling-into ( "name" -- ) 166: \ make (deferred word) "name" call cock-profiler, too 167: ' >body >r :noname 168: POSTPONE cock-profiler 169: r@ @ compile, \ old hook behaviour 170: POSTPONE ; 171: r> ! ; \ change hook behaviour 172: 173: hook-profiling-into then-like 1.3 anton 174: \ hook-profiling-into if-like \ subsumed by other-control-flow 175: \ hook-profiling-into ahead-like \ subsumed by other-control-flow 1.2 anton 176: hook-profiling-into other-control-flow 177: hook-profiling-into begin-like 178: hook-profiling-into again-like 179: hook-profiling-into until-like 180: 181: count-calls? [if] 182: : :-hook-profile ( -- ) 183: defers :-hook 184: next-profile-point-p @ 185: profile-this 186: @ dup last-colondef-profile ! 187: profile-colondef? on ; 188: 189: ' :-hook-profile IS :-hook 190: [else] 191: hook-profiling-into exit-like 192: hook-profiling-into :-hook 193: [endif] | https://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/profile.fs?annotate=1.5;sortby=rev;f=h;only_with_tag=v0-7-0;ln=1 | CC-MAIN-2021-43 | refinedweb | 1,078 | 56.35 |
Agenda
See also: IRC log
<RalphS> previous 2007-06-26
<TomB> Agenda:
Guus: proposal to accept
minutes
... carried
... Upcoming tcon July 10
... Tom will Chair
... Next F2F meeting
<RalphS> results of November f2f poll
Guus: after summer will need
meeting resolve SKOS and RDFa issues.
... Should we have SKOS meeting in Korea or separate venue?
... For RDFa US is likely candidate
Ralph: Only Guus couldn't be in
Cambridge for SKOS
... 5 said they can't be in Korea
Antoine: If SKOS were in Europe, that is preferable.
Ralph: First two weeks in Nov are
not possible.
... 3rd week of Nov is a big US holiday, so we'd be at end of Nov.
Guus: We could select Amsterdam.
<scribe> ACTION: Guus to propose dates in Oct for Amsterdam meeting on SKOS. [recorded in]
TomB: can we pick early Oct?
Guus: We should do a web
poll.
... for RDAa meeting--cambridge venue?
Ralph: only 3 people wanted a
meeting
... suggest that RDFa be taken up in XHTML2 meeting
... there are 2 new chairs for XHTML2
... Roland Merrick and Steven Pemberton
... correction Steven Pemberton
<scribe> ACTION: Discuss possibility of meeting for RDFa in Cambridge. [recorded in]
Issue-26: RelationshipsBetweenLabels ()
Guus: Two current proposals, simple extension and minimal label.
<RalphS> (RDFa hopes to be substantially done by Nov, so the question of a f2f agendum for it was considered low priority by Ben)
Guus: gave this to ontology
engineering students. Will post results to list.
... Other issue is comment from Antoine on naming Guus used
... Instead of prefLabel, use prefLabelR--antoine wonders if this is good naming
... we could discuss
edsu: Does adding an "R" used elsewhere?
Guus: was in OWL
... Actually in OWL it was dropped.
... You need a lexical way of having difference.
Antoine: This is not really
explicit and confusing, as could be interpreted as
relation
... you have properties with R and label relation
... this is a worry
Guus: "resource" might be
better
... There was also discussion as to whether relation was bijectional
... Alistair was going to propose resolution for issue 33. Action not yet been done.
... Proposal to leave it at that
seanb: Wasn't there mail from Allistair in June proposing this?
Guus: if you are willing to look, we'll move on.
seanb: will look for url
-- ISSUE-31 BasicLexicalLabelSemantics proposed resolution
See thread from:
-- ISSUE-31 BasicLexicalLabelSemantics proposed resolution
See thread from:
Guus: John, I can clarify what I
meant
... we had discussion on the potential ontological commitment
... should the concept be in only one scheme
<TomB>
Guus: if there is no clear reason
to say this is the case, we should not specify
... The other issue is whether broader/narrower can be between concepts in 2 different schemes
... I don't see concerns here yet
JonP: this has to do with
ownership schemes
... there was also question whether concept can be in more than one scheme.
Guus: from web approach, whether
concepts belong to scheme is something owner should have
control over
... whether you use broader/narrower for that is another question
JonP: you should look at mapping vocabulary
<seanb> I think this is also related to issue 36:
<Antoine>
Guus: We have equivalent concepts and overlapping concepts
Antoine: I was proposing using broader/narrower relations
Guus: I feel uncomforable
replicating OWL vocabulary here
... for equivalence we have equivalentClass and sameAS
... we hav union and negation
... would hamper usability if we introduce redundancy
Antoine: equivalentConcept may exist in another namespace, so we would turn to a less satisfactory concetp
Guus: why not use sameAs?
Antoine: the meaning of the
concepts are the same, but sameAs states equivalence of the
resources.
... if you have metadata about the concepts, then this information would be aggregated around unique resource
Guus: you can't use equivClass
because they are not equivalent.
... ok
... so we will need further discussion
... do we have an owner for issue 31?
... it was proposed by Alistair
... so Alistair will be owner
Mapping Topic Maps to SKOS:
https: //mijn.postbank.nl/internetbankieren/SesamLoginServlet
Antoine: what Alistiar has
proposed is interesting, but I am concerned about constraints
on semantics.
... people in WG should look at this before next week.
... I'm questioning use of 'syntactic constraints'--I'm not used to that and its relevance to people outside the WG
... is this a good way to specify semantics?
... even Alistair not sure
... people should look at whether this is proper way to do things
Guus: there are analogies in owl.
<JonP>
Guus: every parser might flag a warning as a syntactic condition
Antoine: so no problem specifying
semantic constraints at syntactic level?
... I am ok with this.
Guus: Sean--what do you think?
seanb: where is this?
Guus: if you look at issue 31 and
go to wiki page, you see skos semantics labeling.
... you see semantic conditions
... it is not about the statement but whether semantic considtions are ok
... for language tag, there is no other option...
seanb: ok
<TomB>
Guus: will you look at this and see whether this form is ok?
seanb: yes
Antoine: this may be redundant
with owl specification
... I am ok with what is there.
Mapping Topic Maps to SKOS:
https: //mijn.postbank.nl/internetbankieren/SesamLoginServlet
Guus: this is the wrong link--I
apologize
... I'll resend a new message
<guus>
Guus: There is support for properties of narrower/broader
Antoine: should we raise this as an issue?
Guus: we have these subtypes on our issue list
Antoine: the standardization level is different?
<RalphS> Semantic relation BroaderPartitive/ NarrowerPartitiv
Guus: We can indicate how to do
it
... at moment, topic map community isn't very large
Antoine: while broader/narrower
is something that might come from outside topic map
communtiy
... people have said they would use it for their vocabulary case
Guus: we have these things on our issue list
Anotoine: I don't think so
... we have issue 37 on skos specialization
Guus: should we include in skos
the broader/narrower specialization?
... could Antoine raise that issue?
Antoine: ok
seanb: is there a use case that picks up on that?
Antoine: yes in one of the use cases
<scribe> ACTION: Antoine to raise issue of adding broader/narrower relations in skos [recorded in]
Guus: suggestions on how to move forward these discussions?
<TomB>
<TomB> I have proposed the following section of the SKOS Semantics wiki draft as a resolution for this issue:
Guus: some of these issues need to be resovled at f2f meeting
<TomB> [1] <>
<TomB> This is section of the SKOS Semantics wiki draft, which defines a semantics for skos:Collection, skos:OrderedCollection, skos:member and skos:memberList.
<TomB>.
<TomB> I would like to suggest that the Working Group accept this resolution, because it fixes the basic contradiction in the previous specifications, regarding the use of skos:Collection with skos:broader or skos:narrower, that [ISSUE-33] captures.
<Zakim> TomB, you wanted to draw attention to Alistair's proposal re: ISSUE-33
TomB: On issue 33, I added
link.
... Alistair proposes to address issue 33 by getting wiki draft of skos semantics
... his proposal is that we focus on that part of wiki draft for skos that we can agree on
Guus: we cannot decide on this while issue owner is not here.
TomB: the proposal was that
Alistair would make the proposal explicit and that we would
discuss that section on a tcon.
... I propose we do that at the f2f
Guus: ok, we should schedule that for next week.
<RalphS> RE: [SKOS] ISSUE-33 "Minimal Fix" Proposal [Alistair, 2007-06-26]
Guus: there is proposal for resolution of issues
RalphS: I haven't see responses from group members for the resoution. I need comments from them.
Guus: let's look at issue 2
Proposed resolutions to ISSUE-2, ISSUE-5, ISSUE-25, ISSUE-29, ISSUE-4
Guus: if that is consensus in the subgroup, I'm happy with it
<RalphS> Custom Attributes for RDF shorthand
Guus: any discussion?
... should we go through and accept them?
RalphS: I would like some sense that other WG members have given input
Guus: these are
non-controversial.
... these are fine with me. No real commitments that worry me.
... I propose we resolve and accept RDFa issue 2
... objections?
... so carried
<RalphS> CURIEs in Predicate Attributes
Guus: next is issue 5
RalphS: the subtelty that the
task force has not abandoned the compact URIs
... XHTML is advocating compact URIs
... task force continues to go along with it.
... it will be controversial in HTML community
... Proposed resolution relates to URL part
... This proposed resolution is ok, but this wg may give recommendation to task force as to whether they should still continue persue compact URIs
Guus: I suggest we leave this
until this can be explained to rest of group
... issue 25
... this doesn't look as simple
RalphS: Issue 1 is simple
Discussion on ISSUE-1: reification
Guus: ok
<TomB> +1 on Issue-1 - i.e., not support reification
Guus: seems wise decison to
me
... I propose we resolve issue 1 based on Ben's message
objections?
Guus: so carried
... issue 3
Discussion thread on ISSUE-3 @class and @role for rdf:type
Guus: this is not one we can
easily decide.
... is Michael here?
... I suggest we leave it to issues 1 and 2
RalphS: the class and role issue
relates to how we value clarity of semantics in class
attribute
... we need clearer way to express semantics. Momentum for using class
Guus: we skip to agenda item 5
Guus: any current actions?
vit: there is discussion on naming of terms but these should be taken over by Elisa
RalphS: if Elisa proposes text to discuss, then we can discuss, but there is no action on her for this
vit: what are requirements on
version identification and report on results of
questionnaire
... on identifying versions...
... this will be by end of July at soonest.
Guus: shouldn't be a problem.
<RalphS> Ralph: that sounds like reasonable progress
vit: it will take longer to gather the answers.
Guus: we are at end of the time.
<scribe> ACTION: Guus to move Action 26 forward [recorded in]
Guus: people representing user communities should compare different proposals
<RalphS> ACTION: Guus to post user experience reports for issue-26 [recorded in]
Guus: I will use same
examples
... so makes easier to comapre. We need explicit feedback. | http://www.w3.org/2007/07/03-swd-minutes.html | CC-MAIN-2015-18 | refinedweb | 1,722 | 65.93 |
Cross-reference: Standard exceptions and error codes
his table is intended as an aid for cross-referencing Windows Runtime app error codes to the Microsoft .NET standard exceptions that you can catch as part of your app's exception handling techniques. For more info on those techniques, see Exception handling for Windows Runtime apps in C# or Visual Basic.
Notes
In the ".NET Exception" column of the table above, if the exception name is linked, that exception is part of the classes for .NET for Windows Runtime apps. That means you could raise a new exception of that type in your own code. Or you can catch those exceptions specifically as part of your exception handling for try-catch or UnhandledException. If the exception name is not linked, that exception is not part of the classes for .NET for Windows Runtime. The exceptions that aren't part of the .NET for Windows Runtime set might be encountered in certain interop scenarios, or might come from system or Windows Runtime internals. You won't be able to write catch blocks for them using that specific exception type, because that type isn't known to the .NET libraries you're running for Windows Runtime apps. But you still might be able to read an HRESULT code, look it up from the "HRESULT(s) - raw:" column, and note that there is a .NET exception that corresponds. Or you can catch it as a general Exception. Then you can read the .NET documentation and perhaps learn more about the intention of that exception and the reasons that the originating code might have thrown that exception, even if that exception wasn't represented in the .NET for Windows Runtime types.
If no (Namespace) is listed for a .NET exception, it's from the System namespace.
The constants listed in the "HRESULT(s) - symbolic" column come from a variety of sources. Some are defined in winerror.h. Some are defined in headers that are specific to Component Object Model (COM) programming, or in headers that are part of specific subsystems of Windows. Some require HRESULT_From_Win32 macro usages with codes from even earlier sets of constants (these are the ones preceded with
ERROR_). For typical Windows Runtime programming when you're using a .NET language, these headers are not something that you'd have included as part of your project. If you are getting error code info for the cases where the system can't map to a standard exception, you'll probably see it as a raw integer or hex value and won't have automatic support that aliases the numeric code to the Windows named constant values.
Still, there's a history of referencing error codes by their named constants instead of raw codes, based on previous Windows error reporting systems. You may be able to use the named constants you see in the table as a way to further research the error in other documentation sources such as forums or support documents, in particular what that error meant for desktop programming, Microsoft Win32 and COM, and so on.
SystemException: In the original .NET exception hierarchy, many exceptions derived from SystemException. For example, System.ArgumentException derived from SystemException. Inheritance from SystemException indicated that an exception was defined by the .NET core. SystemException wasn't included in the set of classes for .NET for Windows Runtime. All the exceptions that would have derived from SystemException under the full framework instead derive from System.Exception.
COMException: The .NET documentation suggests that COMException would be thrown for any unrecognized HRESULT, but that's not the behavior for Windows Runtime apps. Instead, COMException is typically the standard exception used for unmapped exceptions that originate from components. Unmapped exceptions from your own app code or from the system are reported as the base Exception, with a nonstandard HResult value.
ExternalException: Not included in .NET for Windows Runtime. You won't see this in the hierarchy for exceptions that do exist (like SEHException).
Related topics
- Exception handling for Windows Store apps in C# or Visual Basic
- System.Exception
- Exceptions (C++/CX)
- Debug Windows Runtime apps in Visual Studio | http://msdn.microsoft.com/en-us/library/windows/apps/dn535792 | CC-MAIN-2014-23 | refinedweb | 687 | 57.16 |
When I looked for magic formulae, etc., I would give up after 20 minutes!
-- Jasper
When I looked for magic formulae, etc., I would give up after 20 minutes!
-- Jasper
Unlike Jasper, I have spent more than 20 minutes searching for magic formulae.
Especially ancient Roman ones.
I first became aware of them back in 2006 during
the Fonality Christmas Golf Challenge
where I was astonished by Ton's ingenuity and deviousness in constructing
his original HART (Hospelian Arabic to Roman Transform) magic formula.
Shortly after the Fonality game, codegolf.com hosted an endless competition
where you must convert the other way, from Roman to Decimal.
By 2009, I had managed to take the lead in all four languages
(Perl, Python, Ruby, PHP), as detailed
in this series of nodes.
And the winning solutions -- in all four languages --
all used (quite different) magic formulae!
To refresh your memory, the codegolf game rules were essentially:.
As you might expect, a key component of solutions to this game
is mapping individual Roman letters to their decimal equivalents.
To help us focus on that, let's define a simpler spec:
Write a function to convert a single Roman Numeral letter to its decimal equivalent.
The function assumes the Roman letter is in $_
and returns its decimal equivalent.
To clarify, here's a sample (non-golfed) Perl solution:
sub r {
my %h = ( I=>1, V=>5, X=>10, L=>50, C=>100, D=>500, M=>1000 );
return $h{$_};
}
print "$_: ", 0+r(), "\n" for (qw(I V X L C D M));
[download]
I: 1
V: 5
X: 10
L: 50
C: 100
D: 500
M: 1000
[download]
Lookup Table vs Magic Formula
In code golf, there is often a battle between a lookup table
and a magic formula. So it proved here.
When converting from Roman to Decimal, magic formula trumps lookup table.
Here are three attempts to solve this problem using a lookup table:
sub r {%h=(I,1,V,5,X,10,L,50,C,100,D,500,M,1000);$h{$_}}
sub r {M1000D500C100L50X10V5I1=~$_;$'}
sub r {M999D499C99L49X9V4I=~$_+$'}
[download]
And here are some of my earliest magic formulae from 2007:
sub r {5**y/VLD//.E.(3*/M/+2*/C|D/+/X|L/)}
sub r {1 .E.~-ord()*41%52%5>>y/VLD//}
sub r {5**y/VLD//.E.ord()x3%75%50%4}
sub r {1 .E.(72^ord)*5/7%5>>y/VLD//}
sub r {5**y/VLD//.E.(42^88*ord)%5}
sub r {1 .E.(3^77%ord)%7>>y/VLD//}
[download]
Later, when I tackled this problem in Python, I really needed to use
each Roman letter once only in the formula, which forced me to explore
alternative approaches ... which, in turn, led to still shorter Perl magic formulae,
such as:
sub r {10**(7&69303333/ord)%9995}
sub r {10**(7&5045e8/ord)%2857} # needs 64-bit Perl
sub r {IXCMVLD=~$_;"1E@-"%9995}
sub r {XCMVLD=~$_;"1E@+"%9995} # Grimy improvement
[download]
The long numbers (such as 69303333 above) that began popping up in these formulae
were an indication that the ord function didn't scale very well as
the required solutions became less probable.
Can we find a built-in function better suited to Roman magic formulae?
In PHP and Python, yes. In Perl and Ruby, probably not.
At least, I don't know of one.
The PHP built-in md5 function is perfect for Roman magic formulae.
Not only does it generate all required digits (0-9), it generates little else (just a-f).
Moreover, you can use all 256 characters in a magic formula,
compared to just ten (0-9) for ord.
To illustrate, in an eight character magic string (for example 69303333),
there are just 10**8 combinations available for ord, while there
are a mind-boggling 256**8=1.8*10**19 combinations available for md5!
This is a huge advantage when searching for highly improbable solutions,
as we shall see later.
The Python hash function is also superior to ord,
though not as good as PHP's md5. This is because Python's Unicode
and character escaping claptrap limits you to 125 characters
(namely ord 1..9,11,12,14..127) that can be used as input to the hash
function without special treatment.
Still, 125 is a huge improvement over 10!
One drawback of hash compared to md5 is that it generates
huge numbers, forcing you to waste five strokes with %1001
to trim the generated numbers into the required Roman Numeral range (1-1000).
In some cases, the Perl crypt built-in could be employed, though
it is not well-suited to this specific problem because (unlike md5)
it generates many other characters in addition to the desired 0-9.
To recap, the shortest magic formulae found so far in all four languages
(as detailed in this series of nodes) are:
10**(205558%ord(r)%7)%9995 # Python
hash(r+"magicstrng")%1001 # Python (finding magicstrng is the subjec
+t of this node!)
VLD=~$_*5+IXCM=~$_."E@-" # Perl
10**(7&5045e8/ord)%2857 # Perl (64-bit)
IXCMVLD=~$_;"1E@-"%9995 # Perl
XCMVLD=~$_;"1E@+"%9995 # Perl (update: Grimy improvement)
uppp&md5_hex$_.PQcUv # Perl (needs Digest::MD5 module)
10**(494254%r/9)%4999 # Ruby (no need for explicit ord in this g
+ame)
md5($r.magicstrng) # PHP (finding magicstrng is an unsolved p
+roblem)
md5($r.PQcUv)&uppp # PHP wins due to superb mf properties of
+md5
[download]
The 10**21 Problem
When Ton Hospel invented magic formulae in golf way back in 2004,
he correctly noted that they work best "with a very small result set".
Indeed, if there were only five Roman Numeral letters, rather than seven, we would
have a straightforward 10**15 problem, rather than a (borderline intractable)
10**21 problem. Why 10**21?
Suppose you have a magic formula that produces a random number between 1 and
1000. The probability of scoring a (lucky) hit for one numeral is therefore
1 in 1000. Since probabilities multiply, the probability of hitting five
out of five numerals is 1 in 10**15, while the chance of hitting
all seven Roman Numerals is a daunting 1 in 10**21.
Though 1 in 10**21 sounds improbable in the extreme,
if you could generate 10**21 combinations, you would not need luck,
indeed you would expect to find such an improbable solution.
Yet how long would it take to search 10**21
combinations for the elusive (lucky) one?
Well, if you could perform 10,000 search operations per second, the time
required to search 10**21 combinations is a
mere 10**21/10000 seconds = 10**17 seconds = 3,170,979,198 years!
By the way, this "brute force search infeasibility problem" is why you
are asked to create longer and longer passwords, and with a wider range
of characters in them, as computer speeds improve.
Indeed, Password cracking
and magic formula searching are closely related disciplines,
the lack of a "codegolf magic formula" wikipedia page notwithstanding. :-)
To make this theoretical argument more concrete, consider searching
for a Roman to Decimal magic formula using the Python built-in
hash function.
Since this hash function produces very large values, we need to apply %1001
to it so as to produce an essentially random value in the desired 1..1000 range.
We might try searching for such a magic formula using a simple Python brute-force
search program, such as:
import time
print time.time(), time.clock()
for q0 in range(1, 128):
for q1 in range(1, 128):
for q2 in range(1, 128):
for q3 in range(1, 128):
for q4 in range(1, 128):
for q5 in range(1, 128):
for q6 in range(1, 128):
for q7 in range(1, 128):
for q8 in range(1, 128):
for q9 in range(1, 128):
magic = chr(q0)+chr(q1)+chr(q2)+chr(q3)+chr(q4)+chr(q5)+chr(
+q6)+chr(q7)+chr(q8)+chr(q9)
m = hash("M" + magic) % 1001
if m != 1000: continue
d = hash("D" + magic) % 1001
if d != 500: continue
c = hash("C" + magic) % 1001
if c != 100: continue
l = hash("L" + magic) % 1001
if l != 50: continue
x = hash("X" + magic) % 1001
if x != 10: continue
v = hash("V" + magic) % 1001
if v != 5: continue
i = hash("I" + magic) % 1001
if i != 1: continue
print "bingo!", q0, q1, q2, q3, q4, q5, q6, q7, q8, q9
print time.time(), time.clock()
[download]
Rather than give up at this point, I found this
"impossible" 50 million year challenge
strangely irresistible ... and was eager to learn about any high performance computing techniques required to solve it.
I get it -- optimization is a fun game ... one can play all day with unrolling loops, peeling away layers of indirection, and so forth to gain cycles, while piddling away time and energy
-- davido
I get it -- optimization is a fun game ... one can play all day with unrolling loops, peeling away layers of indirection, and so forth to gain cycles, while piddling away time and energy
-- davido
Or, as davido puts it, "optimization is a fun game".
Well, I enjoy it.
So I started by rewriting the above search program in C++, then kept on refining
it until I was able to reduce the running time from fifty million years down to
only several years and eventually find a solution.
This new series of articles describes that endeavour.
Please note that this series focuses more on High Performance Computing/Supercomputing/Parallel computing
in C/C++/Intel assembler than code golf.
First Attempt
Re-writing our crude Python searcher in C/C++ we get:
#include <stdio.h>
#include <time.h>
// Python hash() function. Assumes 32-bit int.
// Derived from string_hash() in stringobject.c in Python 2.5.1 source
+s.
static int py_hash(const char* a, int size)
{
int len = size;
const unsigned char* p = (unsigned char*)a;
int x = *p << 7;
while (--len >= 0) x = (1000003 * x) ^ *p++;
x ^= size;
if (x == -1) x = -2;
return x;
}
// Simulate python modulo operator. Assumes mod is positive.
static int py_mod(int j, int mod)
{
int ret;
if (j >= 0) {
ret = j % mod;
} else {
ret = j - (j / mod) * mod;
if (ret) ret += mod;
}
return ret;
}
int main()
{
int q0, q1, q2, q3, q4, q5, q6, q7, q8, q9;
int m, d, c, l, x, v, i;
char magic[16];
time_t tstart = time(NULL);
clock_t cstart = clock();
time_t tend;
clock_t cend;
if (sizeof(int) != 4) { fprintf(stderr, "oops sizeof int != 4\n");
+return 1; }
for (q0 = 1; q0 < 128; ++q0) {
magic[1] = q0;
for (q1 = 1; q1 < 128; ++q1) {
magic[2] = q1;
for (q2 = 1; q2 < 128; ++q2) {
magic[3] = q2;
for (q3 = 1; q3 < 128; ++q3) {
magic[4] = q3;
for (q4 = 1; q4 < 128; ++q4) {
magic[5] = q4;
for (q5 = 1; q5 < 128; ++q5) {
magic[6] = q5;
for (q6 = 1; q6 < 128; ++q6) {
magic[7] = q6;
for (q7 = 1; q7 < 128; ++q7) {
magic[8] = q7;
for (q8 = 1; q8 < 128; ++q8) {
magic[9] = q8;
for (q9 = 1; q9 < 128; ++q9) {
magic[10] = q9;
magic[0] = 'M'; m = py_mod(py_hash(magic, 11), 1001);
if (m != 1000) continue;
magic[0] = 'D'; d = py_mod(py_hash(magic, 11), 1001);
if (d != 500) continue;
magic[0] = 'C'; c = py_mod(py_hash(magic, 11), 1001);
if (c != 100) continue;
magic[0] = 'L'; l = py_mod(py_hash(magic, 11), 1001);
if (l != 50) continue;
magic[0] = 'X'; x = py_mod(py_hash(magic, 11), 1001);
if (x != 10) continue;
magic[0] = 'V'; v = py_mod(py_hash(magic, 11), 1001);
if (v != 5) continue;
magic[0] = 'I'; i = py_mod(py_hash(magic, 11), 1001);
if (i != 1) continue;
printf("bingo! %d %d %d %d %d %d %d %d %d %d\n",
q0, q1, q2, q3, q4, q5, q6, q7, q8, q9);
}
}
}
}
}
}
}
}
}
}
tend = time(NULL);
cend = clock();
printf("(wall clock time:%ld secs, cpu time:%.2f units)\n",
(long) (difftime(tend, tstart)+0.5),
(double) (cend-cstart) / (double)CLOCKS_PER_SEC);
return 0;
}
[download]
Unroll the hash and reorg the code
An obvious optimization is to "unroll" the py_hash() function within the loop;
that is, incrementally build the hash value within the loop and remove the
py_hash() function.
Note, by the way, that this algorithm is very well-suited to multi-threading;
each thread can be given a different starting and ending range to search
and just go at it; there is no need for any thread synchronization at all.
So I took the opportunity at this stage to reorganize the code,
to factor out the "inner loop" into its own file with a single function (with
a C call interface) that just contains raw calculation, no global or static variables,
no library calls, no I/O. Just code.
This reorganization has a number of benefits:
After the code reorganization and hash function unrolling, here is the new main program, find1.cpp:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define H_PRIME 1000003
// Most unlikely to get this many hits in a single call of the inner l
+oop function.
#define MAX_HITS 64
// my_m128_t mimics Intel __m128i type (which will be used later)
typedef struct my_m128_t my_m128_t;
struct my_m128_t { short m128i_i16[8]; };
// the inner loop function (lives in a separate file)
extern "C" int inner(
int startval, int endval,
int m2, int d2, int c2, int l2, int x2, int v2, int i2,
my_m128_t* ps
);
void do_one(int q0, int sv1, int ev1, int sv2, int ev2, int sv3, int e
+v3)
{
time_t tstart = time(NULL);
clock_t cstart = clock();
time_t tend;
clock_t cend;
my_m128_t soln[MAX_HITS];
int m1, m2;
int m_char = 'M';
int m0 = ( ( H_PRIME * (m_char << 7) ) ^ m_char ) * H_PRIME;
int d1, d2;
int d_char = 'D';
int d0 = ( ( H_PRIME * (d_char << 7) ) ^ d_char ) * H_PRIME;
int c1, c2;
int c_char = 'C';
int c0 = ( ( H_PRIME * (c_char << 7) ) ^ c_char ) * H_PRIME;
int l1, l2;
int l_char = 'L';
int l0 = ( ( H_PRIME * (l_char << 7) ) ^ l_char ) * H_PRIME;
int x1, x2;
int x_char = 'X';
int x0 = ( ( H_PRIME * (x_char << 7) ) ^ x_char ) * H_PRIME;
int v1, v2;
int v_char = 'V';
int v0 = ( ( H_PRIME * (v_char << 7) ) ^ v_char ) * H_PRIME;
int i1, i2;
int i_char = 'I';
int i0 = ( ( H_PRIME * (i_char << 7) ) ^ i_char ) * H_PRIME;
int q1, q2;
int mm0 = (m0 ^ q0) * H_PRIME;
int dd0 = (d0 ^ q0) * H_PRIME;
int cc0 = (c0 ^ q0) * H_PRIME;
int ll0 = (l0 ^ q0) * H_PRIME;
int xx0 = (x0 ^ q0) * H_PRIME;
int vv0 = (v0 ^ q0) * H_PRIME;
int ii0 = (i0 ^ q0) * H_PRIME;
fprintf(stderr, "%d: sv1=%d ev1=%d sv2=%d ev2=%d sv3=%d ev3=%d:\n",
q0, sv1, ev1, sv2, ev2, sv3, ev3);
// We ignore 0, 10, 13 because these three require escaping in Pytho
+n.
for (q1 = sv1; q1 < ev1; ++q1) {
if (q1 == 10 || q1 == 13) continue;
m1 = (mm0 ^ q1) * H_PRIME;
d1 = (dd0 ^ q1) * H_PRIME;
c1 = (cc0 ^ q1) * H_PRIME;
l1 = (ll0 ^ q1) * H_PRIME;
x1 = (xx0 ^ q1) * H_PRIME;
v1 = (vv0 ^ q1) * H_PRIME;
i1 = (ii0 ^ q1) * H_PRIME;
for (q2 = sv2; q2 < ev2; ++q2) {
if (q2 == 10 || q2 == 13) continue;
m2 = (m1 ^ q2) * H_PRIME;
d2 = (d1 ^ q2) * H_PRIME;
c2 = (c1 ^ q2) * H_PRIME;
l2 = (l1 ^ q2) * H_PRIME;
x2 = (x1 ^ q2) * H_PRIME;
v2 = (v1 ^ q2) * H_PRIME;
i2 = (i1 ^ q2) * H_PRIME;
int isoln = inner(sv3, ev3, m2, d2, c2, l2, x2, v2, i2, soln);
if (isoln > 0) {
int k;
for (k = 0; k < isoln; ++k) {
fprintf(stderr, "%d %d %d %hd %hd %hd %hd %hd %hd %hd\n",
q0, q1, q2, soln[k].m128i_i16[0],
soln[k].m128i_i16[1], soln[k].m128i_i16[2], soln[k].m128i_i1
+6[3],
soln[k].m128i_i16[4], soln[k].m128i_i16[5], soln[k].m128i_i1
+6[6]);
}
}
}
}
tend = time(NULL);
cend = clock();
fprintf(stderr, "(wall clock time:%ld secs, cpu time:%.2f units)\n"
+,
(long) (difftime(tend, tstart)+0.5),
(double) (cend-cstart) / (double)CLOCKS_PER_SEC);
}
int main(int argc, char* argv[])
{
int sv0, sv1, sv2, sv3, ev1, ev2, ev3;
if (argc != 8) { fprintf(stderr, "usage: prog sv0 sv1 ev1 sv2 ev2 s
+v3 ev3\n"); return 1; }
sv0 = atoi(argv[1]);
sv1 = atoi(argv[2]);
ev1 = atoi(argv[3]);
sv2 = atoi(argv[4]);
ev2 = atoi(argv[5]);
sv3 = atoi(argv[6]);
ev3 = atoi(argv[7]);
do_one(sv0, sv1, ev1, sv2, ev2, sv3, ev3);
return 0;
}
[download]
And here is the "inner loop" function, in its own file, inner1.c:
#define H_PRIME 1000003
#define HASH_LEN 11
// my_m128_t mimics Intel __m128i type
typedef struct my_m128_t my_m128_t;
struct my_m128_t { short m128i_i16[8]; };
// Simulate python modulo operator. Assumes mod is positive.
static int py_mod(int j, int mod)
{
int ret;
if (j >= 0) {
ret = j % mod;
} else {
ret = j - (j / mod) * mod;
if (ret) ret += mod;
}
return ret;
}
// Apart from:
// -1 % 1001 == 1000
// -2 % 1002 == 1000
// both -1 and -2 can never match any of 1000, 500, ..., 1
// Thus don't worry about the Python hash conversion from -1 to -2, ex
+cept for M
int inner(
int startval, int endval,
int m2, int d2, int c2, int l2, int x2, int v2, int i2,
my_m128_t* ps)
{
int m, d, c, l, x, v, i;
int m3, m4, m5, m6, m7, m8, m9;
int d3, d4, d5, d6, d7, d8, d9;
int c3, c4, c5, c6, c7, c8, c9;
int l3, l4, l5, l6, l7, l8, l9;
int x3, x4, x5, x6, x7, x8, x9;
int v3, v4, v5, v6, v7, v8, v9;
int i3, i4, i5, i6, i7, i8, i9;
int q3, q4, q5, q6, q7, q8, q9;
int iret = 0;
for (q3 = startval; q3 < endval; ++q3) {
if (q3 == 10 || q3 == 13);
for (q4 = 1; q4 < 128; ++q4) {
if (q4 == 10 || q4 == 13) continue;
m4 = (m3 ^ q4) * H_PRIME;
d4 = (d3 ^ q4) * H_PRIME;
c4 = (c3 ^ q4) * H_PRIME;
l4 = (l3 ^ q4) * H_PRIME;
x4 = (x3 ^ q4) * H_PRIME;
v4 = (v3 ^ q4) * H_PRIME;
i4 = (i3 ^ q4) * H_PRIME;
for (q5 = 1; q5 < 128; ++q5) {
if (q5 == 10 || q5 == 13) continue;
m5 = (m4 ^ q5) * H_PRIME;
d5 = (d4 ^ q5) * H_PRIME;
c5 = (c4 ^ q5) * H_PRIME;
l5 = (l4 ^ q5) * H_PRIME;
x5 = (x4 ^ q5) * H_PRIME;
v5 = (v4 ^ q5) * H_PRIME;
i5 = (i4 ^ q5) * H_PRIME;
for (q6 = 1; q6 < 128; ++q6) {
if (q6 == 10 || q6 == 13) continue;
m6 = (m5 ^ q6) * H_PRIME;
d6 = (d5 ^ q6) * H_PRIME;
c6 = (c5 ^ q6) * H_PRIME;
l6 = (l5 ^ q6) * H_PRIME;
x6 = (x5 ^ q6) * H_PRIME;
v6 = (v5 ^ q6) * H_PRIME;
i6 = (i5 ^ q6) * H_PRIME;
for (q7 = 1; q7 < 128; ++q7) {
if (q7 == 10 || q7 == 13) continue;
m7 = (m6 ^ q7) * H_PRIME;
d7 = (d6 ^ q7) * H_PRIME;
c7 = (c6 ^ q7) * H_PRIME;
l7 = (l6 ^ q7) * H_PRIME;
x7 = (x6 ^ q7) * H_PRIME;
v7 = (v6 ^ q7) * H_PRIME;
i7 = (i6 ^ q7) * H_PRIME;
for (q8 = 1; q8 < 128; ++q8) {
if (q8 == 10 || q8 == 13) continue;
m8 = (m7 ^ q8) * H_PRIME;
d8 = (d7 ^ q8) * H_PRIME;
c8 = (c7 ^ q8) * H_PRIME;
l8 = (l7 ^ q8) * H_PRIME;
x8 = (x7 ^ q8) * H_PRIME;
v8 = (v7 ^ q8) * H_PRIME;
i8 = (i7 ^ q8) * H_PRIME;
for (q9 = 1; q9 < 128; ++q9) {
if (q9 == 10 || q9 == 13) continue;
m9 = (m8 ^ q9) ^ HASH_LEN;
if (m9 == -1) m9 = -2;
m = py_mod(m9, 1001);
if (m != 1000) continue;
d9 = (d8 ^ q9) ^ HASH_LEN;
d = py_mod(d9, 1001);
if (d != 500) continue;
c9 = (c8 ^ q9) ^ HASH_LEN;
c = py_mod(c9, 1001);
if (c != 100) continue;
l9 = (l8 ^ q9) ^ HASH_LEN;
l = py_mod(l9, 1001);
if (l != 50) continue;
x9 = (x8 ^ q9) ^ HASH_LEN;
x = py_mod(x9, 1001);
if (x != 10) continue;
v9 = (v8 ^ q9) ^ HASH_LEN;
v = py_mod(v9, 1001);
if (v != 5) continue;
i9 = (i8 ^ q9) ^ HASH_LEN;
i = py_mod(i9, 1001);
if (i != 1) continue;
ps[iret].m128i_i16[0] = q3;
ps[iret].m128i_i16[1] = q4;
ps[iret].m128i_i16[2] = q5;
ps[iret].m128i_i16[3] = q6;
ps[iret].m128i_i16[4] = q7;
ps[iret].m128i_i16[5] = q8;
ps[iret].m128i_i16[6] = q9;
++iret;
}
}
}
}
}
}
}
return iret;
}
[download]
This is incredible. You must be impossibly stubborn to go through such a tedious work. :)
-- wazoox
This is incredible. You must be impossibly stubborn to go through such a tedious work. :)
-- wazoox
Yes wazoox, that was tedious.
Yet the simple, if tedious, unrolling of the py_hash function sped up the code by a factor of four.
Down to an estimated running time of 62,860 years now.
Still a lot more work to do before we can break out the champagne.
Tactical vs Strategic Optimizations
There are many micro-optimizations we could apply to speed up this inner loop.
For example, we shall see later how to apply
the Intel AVX instructions
to vectorize this;
[download]
References
Updated 1 May 2014: Updated find1.cpp main() to take command-line arguments specifying a range of values to search for.
Updated 31 May 2014: added Grimy's one stroke Perl improvement
plus a Perl version of PHP md5 magic formula..
++ for the entertaining post, and the well drawn conclusions.
Dave
Firstly, the if (m9 == -1) continue; clause could just as well be omitted—this may only result in false positives, not a false negative. Unlikely to matter though. I would also test if skipping the 10/13 cmps in the innermost loop(s) might improve performance!
Apart from the oddball -1 case, the py_hash() function does not feed high order bits back into the register. Bits propagate higher; low bits of the hash value depend on low bits of input only. The python modulus is trickier. It ((1001+v%1001) % 1001) can be evaluated via unsigned modulus: ((v-(v<0)*620U) % 1001). The sign bit therefore mixes into the 3rd lowest bit.
Compilers know how to replace a divide-by-constant with multiplication by its reciprocal. (Div operation typically has a very high latency.) A division by 10, for example, may be substituted with mul 0xcccccccd; shift right by 3(+32). The shift size varies:]
Update: it is easily shown that modulus must be odd. Hash function either preserves or inverts the lowest bit of r. Even modulus would also preserve it, making (r^v)&1 constant. But that does not fit the problem.
sub u {IXCMVLD=~$_;"1E@-"%9995}
sub i {XCMVLD=~$_;"1E@+"%9995}
print $_, v9, u, v9, i, $/ for qw(M D C L X V I);
[download]
M 1000 1000
D 500 500
C 100 100
L 50 50
X 10 10
V 5 5
I 1 1
[download]
Thanks Grimy.
By the way, the PHP md5 solution works in Perl too
since these two languages have essentially the same
bitwise string operators:
use Digest::MD5 qw(md5_hex);
sub r {uppp&md5_hex$_.PQcUv}
print "$_: ", 0+r(), "\n" for (qw(I V X L C D M));
[download]
I've updated the Perl summary of shortest solutions in the root node like so:
VLD=~$_*5+IXCM=~$_."E@-" # Perl
10**(7&5045e8/ord)%2857 # Perl (64-bit)
IXCMVLD=~$_;"1E@-"%9995 # Perl
XCMVLD=~$_;"1E@+"%9995 # Perl (Grimy improvement)
uppp&md5_hex$_.PQcUv # Perl (needs Digest::MD5 module)
[download]
As you can see, if Perl had a md5 built-in function, this would be
the shortest Perl solution --
even with a ridiculously long md5_hex function name!
Update: for full details on how I happened to find this md5 solution, see Re^2: The golf course looks great, my swing feels good, I like my chances (Part III).
Deep frier
Frying pan on the stove
Oven
Microwave
Halogen oven
Solar cooker
Campfire
Air fryer
Other
None
Results (323 votes). Check out past polls. | http://www.perlmonks.org/?node_id=1083046 | CC-MAIN-2016-26 | refinedweb | 3,823 | 67.79 |
However whenever I tried to do this, I was presented with the following error:
"No module named setuptools"
Some google searches and a read of the python.org website told be I was missing the python setup tools component distribute.
So the first step is to install distribute:
mkdir python-setuptools
cd python-setuptools
wget -O - | sudo python
cd python-setuptools
wget -O - | sudo python
Then download whatever module you need and run the setup.py program using the command:
sudo python setup.py install
Then with a bit of luck, your module should be setup and ready to use.
Thanks for this post! I'm getting a similar error. I need to install the twitter api, so I assume I write "sudo python setup.py twitter"?? However I get told that python cannot open setup.p. There is not setup.py in my directory so do I need to change to a different directory?
Thanks
Ok, im not really sure from your description what your problem is. What module are you trying to install? Have you followed the blog post and installed distribute? Any other info ?
Hi Martin,
Im trying to install distribute but after downloading and I try to do "sudo python distribute_setup.py" it says: cant open file... ...no such file or directory. Anything you know how to get around?
Thanks,
Jacob
Did you download the file using - "curl -O" - did it work? Or create an error?
Hi,
I did ""curl -O" and got in return:
"#!python
"""Bootstrap distribute installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from distribute os
import shutil
import sys
import time
import fnmatch
import tempfile
import tarfile
import optparse
from distutils import log...."
It continues with alot more commands and text. No warnings that I can see. According to the file "curl -O" refers to has been changed in July 2013, could it be the method has changed since your guide was written?
If i try to list the files in directory python-distribute after "downloading" no files are shown.
Big big thanks Martin for replying to my call for help! Very green in the software programing world.
Jacob
Hi again Martin,
solved the problem with the info from and just run "sudo apt-get install python-setuptools"
Thanks again for your help! | http://www.stuffaboutcode.com/2012/10/raspberry-pi-python-installing-modules.html | CC-MAIN-2016-44 | refinedweb | 406 | 76.01 |
This is a discussion on RE: sha test failing on MkLinux PPC - Openssl ; Riccardo wrote: > it is nice to see how my messages are totally ignored... I hope this > doesn't mean that everybody is clueless. I did further tests though. All it means is that in the time between when you ...
Riccardo wrote:
> it is nice to see how my messages are totally ignored... I hope this
> doesn't mean that everybody is clueless. I did further tests though.
All it means is that in the time between when you posted your first message
and now, no one who chanced to read the list had seen this problem before.
With the wide variety of platforms, it is not unusual for problems to show
up on only one platform.
> > error calculating SHA on '3c48692aceb44f85cf99c985154c15b79e6baef0'
> > got 3c48692aceb44f85cf99c985154c15b79e6baef0 instead of
> > 3232affa48628a26653b5aaa44541fd90d690603
>[snip]
> I tried to build and test 0.9.6i and even 0.9.5 and they both fail the
> same way (buit not using rpm, but make and make test). Another more
> experienced developer of MkLinux hints the test program is wrong, I
> prefer some help and hints on how to proceed to identify the soruce of
> the problem. As it happens, I have a
big-endian environment on an Intel box, so the assumption was grossly
incorrect. I inserted some #if...#endif macros to comment-out the
optimizations, and the problem was solved.
I presume that a PPC is a PowerPC, which is also a big-endian platform.
Take a close look at some of the #if macro tests in, for example,
crypto/sha/sha_locl.h. You could be hitting a similar problem.
We found the problem by one of our programmers having a brilliant insight,
but we were moments away from running parallel debugging sessions on a
working versus non-working platform to see where the math divered. Enjoy.
Thanks
PG
--
Paul Green, Senior Technical Consultant, Stratus Technologies.
Voice: +1 978-461-7557; FAX: +1 978-461-3610; AIM: PaulGreen
__________________________________________________ ____________________
OpenSSL Project
Development Mailing List openssl-dev@openssl.org
Automated List Manager majordomo@openssl.org | http://fixunix.com/openssl/151916-re-sha-test-failing-mklinux-ppc.html | CC-MAIN-2015-18 | refinedweb | 349 | 65.52 |
Suppose you have a tensor with shape [4, 16, 256], where your LSTM is 2-layer bi-directional (2*2 = 4), the batch size is 16 and the hidden state is 256. What is the correct way to get the concatenated last layer output of the output (shape [16, 512])?
I’m doing the following – please note that I support both GRU and LSTM in the model so I can decide on setup time:
def forward(self, inputs): batch_size = inputs.shape[0] # Push through embedding layer X = self.embedding(inputs) # Push through RNN layer (the ouput is irrelevant) _, self.hidden = self.rnn(X, self.hidden) # Get the hidden state of the last layer of the RNN if self.params.rnn_type == RnnType.RNN_TYPE__GRU: hidden = self.hidden elif self.params.rnn_type == RnnType.RNN_TYPE__LSTM: hidden = self.hidden[0] # Flatten hidden state with respect to batch size hidden = hidden.transpose(1,0).contiguous().view(batch_size, -1) ...
The important part is the
transpose(1,0) to get the batch size to the front. Everything else is handled by the
view() command. I only need the
transpose since I initialize the RNN with
batch_first=True.
Note that the input shape of the directly following linear layer needs to be
(rnn_hidden_dim * num_directions * num_layers, output_size).
Thanks for the reply. Suppose in a two stack LSTM, the hidden state of the first layer is pretty much intermediate and I am thinking to get rid of it. It seems your code did not touch this part. Do you have any recommendations on how to do so? From the official doc it is not clear which parts of the hidden output (self.hidden[0] in your example) we should pick.
The output of LSTM is
output, (h_n, c_n) in my code
_, self.hidden = self.rnn(X, self.hidden),
self.hidden is the tuples
(h_n, c_n), and since I only want
h_n, I have to do
hidden = self.hidden[0].
In case you only want the last layer, the docs say that you can separate the hidden state with
h_n = h_n.view(num_layers, num_directions, batch, hidden_size. Since
num_layers is the first dimension, you only need to to
h_n = h_n[-1] to get the last layer. The shape will be
(num_directions, batch, hidden_size) | https://discuss.pytorch.org/t/how-to-concatenate-the-hidden-states-of-a-bi-lstm-with-multiple-layers/39798 | CC-MAIN-2022-21 | refinedweb | 372 | 67.04 |
Two fun things happened recently and the proximity of the two made something go click in my head and now I think I understand how bytecode interpreters work.
- I went to a class at work called “Interpreters 101” or something of the sort. In it, the presenter walked through creating a dead-simple tree-walking Lisp interpreter. Then he ended by suggesting we go out and re-implement it as a bytecode interpreter or even a JIT.
- I joined a new team at work that is working on something Python related. Because of my new job responsibilities, I have had to become rather closely acquainted with CPython 3.6 bytecode.
Since learning by writing seems to be something I do frequently, here is a blog post about writing a small bytecode compiler and interpreter in small pieces. We’ll go through it in the same manner as my lisp interpreter: start with the simplest pices and build up the rest of the stack as we need other components.
Some definitions
Before we dive right in, I’m going to make some imprecise definitions that should help differentiate types of interpreters:
- Tree-walking interpreters process the program AST node by node, recursively evaluating based on some evaluation rules. For a program like
Add(Lit 1, Lit 2), it might see the add rule, recursively evaluate the arguments, add them together, and then package that result in the appropriate value type.
Bytecode interpreters don’t work on the AST directly. They work on preprocessed ASTs. This simplifies the execution model and can produce impressive speed wins. A program like
Add(Lit 1, Lit 2)might be bytecode compiled into the following bytecode:
And then the interpreter would go instruction by instruction, sort of like a hardware CPU.
- JIT interpreters are like bytecode interpreters except instead of compiling to language implementation-specific bytecode, they try to compile to native machine instructions. Most production-level JIT interpreters “warm up” by measuring what functions get called the most and then compiling them to native code in the background. This way, the so-called “hot code” gets optimized and has a smaller performance penalty.
My Writing a Lisp series presents a tree-walking interpreter. This much smaller post will present a bytecode interpreter. A future post may present a JIT compiler when I figure out how they work.
Without further ado, let us learn.
In the beginning, there was a tree-walking interpreter
Lisp interpreters have pretty simple semantics. Below is a sample REPL
(read-eval-print-loop) where all the commands are
parsed into ASTs and then
evaled straightaway. See Peter Norvig’s lis.py for a similar
tree-walking interpreter.
>>> 1 1 >>> '1' 1 >>> "hello" hello >>> (val x 3) None >>> x 3 >>> (set x 7) None >>> x 7 >>> (if True 3 4) 3 >>> (lambda (x) (+ x 1)) <Function instance...> >>> ((lambda (x) (+ x 1)) 5) 6 >>> (define f (x) (+ x 1)) None >>> f <Function instance...> >>> + <function + at...> >>> (f 10) 11 >>>
For our interpreter, we’re going to write a function called
compile that
takes in an expression represented by a Python list (something like
['+', 5,
['+', 3, 5]]) and returns a list of bytecode instructions. Then we’ll write
eval that takes in those instructions and returns a Python value (in this
case, the int
13). It should behave identically to the tree-walking
interpreter, except faster.
The ISA
For our interpreter we’ll need a surprisingly small set of instructions, mostly lifted from the CPython runtime’s own instruction set architecture. CPython is a stack-based architecture, so ours will be too.
LOAD_CONST
- Pushes constants onto the stack.
STORE_NAME
- Stores values into the environment.
LOAD_NAME
- Reads values from the environment.
CALL_FUNCTION
- Calls a function (built-in or user-defined).
RELATIVE_JUMP_IF_TRUE
- Jumps if the value on top of the stack is true.
RELATIVE_JUMP
MAKE_FUNCTION
- Creates a function object from a code object on the stack and pushes it on the stack.
With these instructions we can define an entire language. Most people choose to define math operations in their instruction sets for speed, but we’ll define them as built-in functions because it’s quick and easy.
The
Opcode and
Instruction classes
I’ve written an
Opcode enum:
import enum class AutoNumber(enum.Enum): def _generate_next_value_(name, start, count, last_values): return count @enum.unique class Opcode(AutoNumber): # Add opcodes like: # OP_NAME = enum.auto() pass
Its sole purpose is to enumerate all of the possible opcodes — we’ll add them
later. Python’s
enum API is pretty horrific so you can gloss over this if you
like and pretend that the opcodes are just integers.
I’ve also written an
Instruction class that stores opcode and optional
argument pairs:
class Instruction: def __init__(self, opcode, arg=None): self.opcode = opcode self.arg = arg def __repr__(self): return "<Instruction.{}({})>".format(self.opcode.name, self.arg) def __call__(self, arg): return Instruction(self.opcode, arg) def __eq__(self, other): assert(isinstance(other, Instruction)) return self.opcode == other.opcode and self.arg == other.arg
The plan is to declare one
Instruction instance per opcode, naming its
argument something sensible. Then when bytecode compiling, we can make
instances of each instruction by calling them with a given argument. This is
pretty hacky but it works alright.
# Creating top-level opcodes STORE_NAME = Instruction(Opcode.STORE_NAME, "name") # Creating instances [STORE_NAME("x"), STORE_NAME("y")]
Now that we’ve got some infrastructure for compilation, let’s start compiling.
Integers
This is what our
compile function looks like right now:
def compile(exp): raise NotImplementedError(exp)
It is not a useful compiler, but at least it will let us know what operations it does not yet support. Let’s make it more useful.
The simplest thing I can think of to compile is an integer. If we see one, we should put it on the stack. That’s all! So let’s first add some instructions that can do that, and then implement it.
class Opcode(AutoNumber): LOAD_CONST = enum.auto()
I called it
LOAD_CONST because that’s what Python calls its opcode that does
something similar. “Load” is a sort of confusing word for what its doing,
because that doesn’t specify where it’s being loaded. If you want, you can
call this
PUSH_CONST, which in my opinion better implies that it is to be
pushed onto the VM stack. I also specify
CONST because this instruction
should only be used for literal values:
5,
"hello", etc. Something where
the value is completely defined by the expression itself.
Here’s the parallel for the
Instruction class (defined at the module scope):
LOAD_CONST = Instruction(Opcode.LOAD_CONST, "const")
The argument name
"const" is there only for bytecode documentation for the
reader. It will be replaced by an actual value when this instruction is created
and executed. Next, let’s add in a check to catch this case.
def compile(exp): if isinstance(exp, int): return [LOAD_CONST(exp)] raise NotImplementedError(exp)
Oh, yeah.
compile is going to walk the expression tree and merge together
lists of instructions from compiled sub-expressions — so every branch has to
return a list. This will look better when we have nested cases. Let’s test it
out:
assert compile(5) == [LOAD_CONST(5)] assert compile(7) == [LOAD_CONST(7)]
Now that we’ve got an instruction, we should also be able to run it. So let’s
set up a basic
eval loop:
def eval(self, code): pc = 0 while pc < len(code): ins = code[pc] op = ins.opcode pc += 1 raise NotImplementedError(op)
Here
pc is short for “program counter”, which is equivalent to the term
“instruction pointer”, if you’re more familiar with that. The idea is that we
iterate through the instructions one by one, executing them in order.
This loop will throw when it cannot handle a particular instruction, so it is
reasonable scaffolding, but not much more. Let’s add a case to handle
LOAD_CONST in
eval.
def eval(code): pc = 0 stack = [] while pc < len(code): ins = code[pc] op = ins.opcode pc += 1 if op == Opcode.LOAD_CONST: stack.append(ins.arg) else: raise NotImplementedError(op) if stack: return stack[-1]
Note, since it will come in handy later, that
eval returns the value on the
top of the stack. This is the beginning of our calling convention, which we’ll
flesh out more as the post continues. Let’s see if this whole thing works, end
to end.
assert eval(compile(5)) == 5 assert eval(compile(7)) == 7
And now let’s run it:
willow% python3 ~/tmp/bytecode0.py willow%
Swell.
Naming things, A Wizard of Earthsea
Now, numbers aren’t much fun if you can’t do anything with them. Right now the only valid programs are programs that push one number onto the stack. Let’s add some opcodes that put those values into variables.
We’ll be adding
STORE_NAME, which takes one value off the stack and stores it
in the current environment, and
LOAD_NAME, which reads a value from the
current environment and pushes it onto the stack.
@enum.unique class Opcode(AutoNumber): LOAD_CONST = enum.auto() STORE_NAME = enum.auto() LOAD_NAME = enum.auto() # ... STORE_NAME = Instruction(Opcode.STORE_NAME, "name") LOAD_NAME = Instruction(Opcode.LOAD_NAME, "name")
Let’s talk about our representation of environments. Our
Env class looks like
this (based on Dmitry Soshnikov’s “Spy” interpreter):
class Env(object): # table holds the variable assignments within the env. It is a dict that # maps names to values. def __init__(self, table, parent=None): self.table = table self.parent = parent # define() maps a name to a value in the current env. def define(self, name, value): self.table[name] = value # assign() maps a name to a value in whatever env that name is bound, # raising a ReferenceError if it is not yet bound. def assign(self, name, value): self.resolve(name).define(name, value) # lookup() returns the value associated with a name in whatever env it is # bound, raising a ReferenceError if it is not bound. def lookup(self, name): return self.resolve(name).table[name] # resolve() finds the env in which a name is bound and returns the whole # associated env object, raising a ReferenceError if it is not bound. def resolve(self, name): if name in self.table: return self if self.parent is None: raise ReferenceError(name) return self.parent.resolve(name) # is_defined() checks if a name is bound. def is_defined(self, name): try: self.resolve(name) return True except ReferenceError: return False
Our execution model will make one new
Env per function call frame and one new
env per closure frame, but we’re not quite there yet. So if that doesn’t yet
make sense, ignore it for now.
What we care about right now is the global environment. We’re going to make one
top-level environment for storing values. We’ll then thread that through the
eval function so that we can use it. But let’s not get ahead of ourselves.
Let’s start by compiling.
def compile(exp): if isinstance(exp, int): return [LOAD_CONST(exp)] elif isinstance(exp, list): assert len(exp) > 0 if exp[0] == 'val': # (val n v) assert len(exp) == 3 _, name, subexp = exp return compile(subexp) + [STORE_NAME(name)] raise NotImplementedError(exp)
I’ve added this second branch to check if the expression is a list, since we’ll
mostly be dealing with lists now. Since we also have just about zero
error-handling right now, I’ve also added some
asserts to help with code
simplicity.
In the
val case, we want to extract the name and the subexpression —
remember, we won’t just be compiling simple values like
5; the values might
be
(+ 1 2). Then, we want to compile the subexpression and add a
STORE_NAME
instruction. We can’t test that just yet — we don’t have more complicated
expressions — but we’ll get there soon enough. Let’s test what we can,
though:
assert compile(['val', 'x', 5]) == [LOAD_CONST(5), STORE_NAME('x')]
Now let’s move back to
eval.
def eval(code, env): pc = 0 stack = [] while pc < len(code): ins = code[pc] op = ins.opcode pc += 1 if op == Opcode.LOAD_CONST: stack.append(ins.arg) elif op == Opcode.STORE_NAME: val = stack.pop(-1) env.define(ins.arg, val) else: raise NotImplementedError(ins) if stack: return stack[-1]
You’ll notice that I’ve
- Added an
envparameter, so that we can evaluate expressions in different contexts and get different results
- Added a case for
STORE_NAME
We’ll have to modify our other tests to pass an
env parameter — you can
just pass
None if you are feeling lazy.
Let’s make our first environment and test out
STORE_NAME. For this, I’m going
to make an environment and test that storing a name in it side-effects that
environment.
env = Env({}, parent=None) eval([LOAD_CONST(5), STORE_NAME('x')], env) assert env.table['x'] == 5
Now we should probably go about adding compiler and evaluator functionality for reading those stored values. The compiler will just have to check for variable accesses, represented just as strings.
def compile(exp): if isinstance(exp, int): return [LOAD_CONST(exp)] elif isinstance(exp, str): return [LOAD_NAME(exp)] # ...
And add a test for it:
assert compile('x') == [LOAD_NAME('x')]
Now that we can generate
LOAD_NAME, let’s add
eval support for it. If we
did anything right, its implementation should pretty closely mirror that of its
sister instruction.
def eval(code, env): # ... while pc < len(code): # ... elif op == Opcode.STORE_NAME: val = stack.pop(-1) env.define(ins.arg, val) elif op == Opcode.LOAD_NAME: val = env.lookup(ins.arg) stack.append(val) # ... # ...
To test it, we’ll first manually store a name into the environment, then see if
LOAD_NAME can read it back out.
env = Env({'x': 5}, parent=None) assert eval([LOAD_NAME('x')], env) == 5
Neat.
Built-in functions
We can add as many opcodes as features we need, or we can add one opcode that allows us to call native (Python) code and extend our interpreter that way. Which approach you take is mostly a matter of taste.
In our case, we’ll add the
CALL_FUNCTION opcode, which will be used both for
built-in functions and for user-defined functions. We’ll get to user-defined
functions later.
CALL_FUNCTION will be generated when an expression is of the form
(x0 x1 x2
...) and
x0 is not one of the pre-set recognized names like
val. The
compiler should generate code to load first the function, then the arguments
onto the stack. Then it should issue the
CALL_FUNCTION instruction. This is
very similar to CPython’s implementation.
I’m not going to reproduce the
Opcode declaration, because all of those look
the same, but here is my
Instruction declaration:
CALL_FUNCTION = Instruction(Opcode.CALL_FUNCTION, "nargs")
The
CALL_FUNCTION instruction takes with it the number of arguments passed to
the function so that we can call it correctly. Note that we do this instead of
storing the correct number of arguments in the function because functions could
take variable numbers of arguments.
Let’s compile some call expressions.
def compile(exp): # ... elif isinstance(exp, list): assert len(exp) > 0 if exp[0] == 'val': assert len(exp) == 3 _, name, subexp = exp return compile(subexp) + [STORE_NAME(name)] else: args = exp[1:] nargs = len(args) arg_code = sum([compile(arg) for arg in args], []) return compile(exp[0]) + arg_code + [CALL_FUNCTION(nargs)] # ...
I’ve added a default case for list expressions. See that it compiles the name,
then the arguments, then issues a
CALL_FUNCTION. Let’s test it out with 0, 1,
and more arguments.
assert compile(['hello']) == [LOAD_NAME('hello'), CALL_FUNCTION(0)] assert compile(['hello', 1]) == [LOAD_NAME('hello'), LOAD_CONST(1), CALL_FUNCTION(1)] assert compile(['hello', 1, 2]) == [LOAD_NAME('hello'), LOAD_CONST(1), LOAD_CONST(2), CALL_FUNCTION(2)]
Now let’s implement
eval.
def eval(code, env): # ... while pc < len(code): # ... elif op == Opcode.CALL_FUNCTION: nargs = ins.arg args = [stack.pop(-1) for i in range(nargs)][::-1] fn = stack.pop(-1) assert callable(fn) stack.append(fn(args)) else: raise NotImplementedError(ins) # ...
Notice that we’re reading the arguments off the stack — in reverse order — and then reading the function off the stack. Everything is read the opposite way it is pushed onto the stack, since, you know, it’s a stack.
We also check that the
fn is callable. This is a Python-ism. Since we’re
allowing raw Python objects on the stack, we have to make sure that we’re
actually about to call a Python function. Then we’ll call that function with a
list of arguments and push its result on the stack.
Here’s what this looks like in real life, in a test:
env = Env({'+': lambda args: args[0] + args[1]}, None) assert eval(compile(['+', 1, 2]), env) == 3
This is pretty neat. If we stuff
lambda expressions into environments, we get
these super easy built-in functions. But that’s not quite the most optimal
+
function. Let’s make a variadic one for fun.
env = Env({'+': sum}, None) assert eval(compile(['+', 1, 2, 3, 4, 5]), env) == 15 assert eval(compile(['+']), env) == 0
Since we pass the arguments a list, we can do all sorts of whack stuff like this!
Since I only alluded to it earlier, let’s add a test for compiling nested
expressions in
STORE_NAME.
env = Env({'+': sum}, None) eval(compile(['val', 'x', ['+', 1, 2, 3]]), env) assert env.table['x'] == 6
Go ahead and add all the builtin functions that your heart desires… like
env = Env({'print': print}, None) eval(compile(['print', 1, 2, 3]), env)
You should see the arguments passed in the correct order. Note that if you are
using Python 2, you should wrap the print in a
lambda, since
Conditionals
Without conditionals, we can’t really do much with our language. While we could choose to implement conditionals eagerly as built-in functions, we’re going to do “normal” conditionals. Conditionals that lazily evaluate their branches. This can’t be done with our current execution model because all arguments are evaluated before being passed to built-in functions.
We’re going to do conditionals the traditional way:
will compile to
[a BYTECODE] RELATIVE_JUMP_IF_TRUE b [c BYTECODE] RELATIVE_JUMP end b: [b BYTECODE] end:
We’re also going to take the CPython approach in generating relative jumps instead of absolute jumps. This way we don’t need a separate target resolution step.
To accomplish this, we’ll add two the opcodes and instructions listed above:
RELATIVE_JUMP_IF_TRUE = Instruction(Opcode.RELATIVE_JUMP_IF_TRUE, "off") RELATIVE_JUMP = Instruction(Opcode.RELATIVE_JUMP, "off")
Each of them takes an offset in instructions of how far to jump. This could be positive or negative — for loops, perhaps — but right now we will only generate positive offsets.
We’ll add one new case in the compiler:
def compile(exp): # ... elif isinstance(exp, list): # ... elif exp[0] == 'if': assert len(exp) == 4 _, cond, iftrue, iffalse = exp iftrue_code = compile(iftrue) iffalse_code = compile(iffalse) + [RELATIVE_JUMP(len(iftrue_code))] return (compile(cond) + [RELATIVE_JUMP_IF_TRUE(len(iffalse_code))] + iffalse_code + iftrue_code) # ...
First compile the condition. Then, compile the branch that will execute if the
condition passes. The if-false branch is a little bit tricky because I am also
including the jump-to-end in there. This is so that the offset calculation for
the jump to the if-true branch is correct (I need not add
+1).
Let’s add some tests to check our work:
assert compile(['if', 1, 2, 3]) == [LOAD_CONST(1), RELATIVE_JUMP_IF_TRUE(2), LOAD_CONST(3), RELATIVE_JUMP(1), LOAD_CONST(2)] assert compile(['if', 1, ['+', 1, 2], ['+', 3, 4]]) == \ [LOAD_CONST(1), RELATIVE_JUMP_IF_TRUE(5), LOAD_NAME('+'), LOAD_CONST(3), LOAD_CONST(4), CALL_FUNCTION(2), RELATIVE_JUMP(4), LOAD_NAME('+'), LOAD_CONST(1), LOAD_CONST(2), CALL_FUNCTION(2)]
I added the second test to double-check that nested expressions work correctly.
Looks like they do. On to
eval!
This part should be pretty simple — adjust the
pc, sometimes conditionally.
def eval(code, env): # ... while pc < len(code): # ... elif op == Opcode.RELATIVE_JUMP_IF_TRUE: cond = stack.pop(-1) if cond: pc += ins.arg # pc has already been incremented elif op == Opcode.RELATIVE_JUMP: pc += ins.arg # pc has already been incremented # ... # ...
If it takes a second to convince yourself that this is not off-by-one, that makes sense. Took me a little bit too. And hey, if convincing yourself isn’t good enough, here are some tests.
assert eval(compile(['if', 'true', 2, 3]), Env({'true': True})) == 2 assert eval(compile(['if', 'false', 2, 3]), Env({'false': False})) == 3 assert eval(compile(['if', 1, ['+', 1, 2], ['+', 3, 4]]), Env({'+': sum})) == 3
Defining your own functions
User-defined functions are absolutely key to having a usable programming
language. Let’s let our users do that. Again, we’re using Dmitry’s
Function
representation, which is wonderfully simple.
class Function(object): def __init__(self, params, body, env): self.params = params self.body = body self.env = env # closure!
The params will be a tuple of names, the body a tuple of instructions, and the
env an
Env.
In our language, all functions will be closures. They can reference variables defined in the scope where the function is defined (and above). We’ll use the following forms:
((lambda (x) (+ x 1)) 5) ; or (define inc (x) (+ x 1)) (inc 5)
In fact, we’re going to use a syntax transformation to re-write
defines in
terms of
val and
lambda. This isn’t required, but it’s kind of neat.
For this whole thing to work, we’re going to need a new opcode:
MAKE_FUNCTION. This will convert some objects stored on the stack into a
Function object.
MAKE_FUNCTION = Instruction(Opcode.MAKE_FUNCTION, "nargs")
This takes an integer, the number of arguments that the function expects. Right now we only allow positional, non-optional arguments. If we wanted to have additional calling conventions, we’d have to add them later.
Let’s take a look at
compile.
def compile(exp): # ... elif isinstance(exp, list): assert len(exp) > 0 # ... elif exp[0] == 'lambda': assert len(exp) == 3 (_, params, body) = exp return [LOAD_CONST(tuple(params)), LOAD_CONST(tuple(compile(body))), MAKE_FUNCTION(len(params))] elif exp[0] == 'define': assert len(exp) == 4 (_, name, params, body) = exp return compile(['lambda', params, body]) + [STORE_NAME(name)] # ...
For
lambda, it’s pretty straightforward. Push the params, push the body code,
make a function.
define is a little sneaker. It acts as a macro and rewrites the AST before
compiling it. If we wanted to be more professional, we could make a macro
system so that the standard library could define
define and
if… but
that’s too much for right now. But still. It’s pretty neat.
Before we move on to
eval, let’s quickly check our work.
assert compile(['lambda', ['x'], ['+', 'x', 1]]) == \ [LOAD_CONST(('x',)), LOAD_CONST(( LOAD_NAME('+'), LOAD_NAME('x'), LOAD_CONST(1), CALL_FUNCTION(2))), MAKE_FUNCTION(1)] assert compile(['define', 'f', ['x'], ['+', 'x', 1]]) == \ [LOAD_CONST(('x',)), LOAD_CONST(( LOAD_NAME('+'), LOAD_NAME('x'), LOAD_CONST(1), CALL_FUNCTION(2))), MAKE_FUNCTION(1), STORE_NAME('f')]
Alright alright alright. Let’s get these functions created. We need to handle
the
MAKE_FUNCTION opcode in
eval.
def eval(code, env): # ... while pc < len(code): # ... elif op == Opcode.MAKE_FUNCTION: nargs = ins.arg body_code = stack.pop(-1) params = stack.pop(-1) assert len(params) == nargs stack.append(Function(params, body_code, env)) # ... # ...
As with calling functions, we read everything in the reverse of the order that
we pushed it. First the body, then the params — checking that they’re the
right length — then push the new
Function object.
But
Functions aren’t particularly useful without being callable. There are
two strategies for calling functions, one slightly slicker than the other. You
can choose which you like.
The first strategy, the simple one, is to add another case in
CALL_FUNCTION
that handles
Function objects. This is what most people do in most
programming languages. It looks like this:
def eval(code, env): # ... while pc < len(code): # ... elif op == Opcode.CALL_FUNCTION: nargs = ins.arg args = [stack.pop(-1) for i in range(nargs)][::-1] fn = stack.pop(-1) if callable(fn): stack.append(fn(args)) elif isinstance(fn, Function): actuals_record = dict(zip(fn.params, args)) body_env = Env(actuals_record, fn.env) stack.append(eval(fn.body, body_env)) else: raise RuntimeError("Cannot call {}".format(fn)) # ... # ...
Notice that the function environment consists solely of the given arguments and its parent is the stored environment — not the current one.
The other approach is more Pythonic, I think. It turns
Function into a
callable object, putting the custom setup code into
Function itself. If you
opt to do this, leave
CALL_FUNCTION alone and modify
Function this way:
class Function(object): def __init__(self, params, body, env): self.params = params self.body = body self.env = env # closure! def __call__(self, actuals): actuals_record = dict(zip(self.params, actuals)) body_env = Env(actuals_record, self.env) return eval(self.body, body_env)
Then
eval should call the
Function as if it were a normal Python function.
Cool… or gross, depending on what programming languages you are used to
working with.
They should both work as follows:
env = Env({'+': sum}, None) assert eval(compile([['lambda', 'x', ['+', 'x', 1]], 5]), env) == 6 eval(compile(['define', 'f', ['x'], ['+', 'x', 1]]), env) assert isinstance(env.table['f'], Function)
Hell, even recursion works! Let’s write ourselves a little factorial function.
import operator env = Env({ '*': lambda args: args[0] * args[1], '-': lambda args: args[0] - args[1], 'eq': lambda args: operator.eq(*args), }, None) eval(compile(['define', 'factorial', ['x'], ['if', ['eq', 'x', 0], 1, ['*', 'x', ['factorial', ['-', 'x', 1]]]]]), env) assert eval(compile(['factorial', 5]), env) == 120
Which works, but it feels like we’re lacking the ability to sequence operations… because we are! So let’s add that.
One teensy little thing is missing
It should suffice to write a function
compile_program that can take a list of
expressions, compile them, and join them. This alone is not enough, though. We
should expose that to the user so that they can sequence operations when they
need to. So let’s also add a
begin keyword.
def compile_program(prog): return [instr for exp in prog for instr in compile(exp)] # flatten
And then a case in
compile:
def compile(exp): # ... elif isinstance(exp, list): # ... elif exp[0] == 'begin': return compile_program(exp[1:]) else: args = exp[1:] nargs = len(args) arg_code = sum([compile(arg) for arg in args], []) return compile(exp[0]) + arg_code + [CALL_FUNCTION(nargs)] raise NotImplementedError(exp)
And of course a test:
import operator env = Env({ '*': lambda args: args[0] * args[1], '-': lambda args: args[0] - args[1], 'eq': lambda args: operator.eq(*args), }, None) assert eval(compile(['begin', ['define', 'factorial', ['x'], ['if', ['eq', 'x', 0], 1, ['*', 'x', ['factorial', ['-', 'x', 1]]]]], ['factorial', 5] ]), env) == 120
And you’re done!
You’re off to the races. You’ve just written a bytecode interpreter in Python or whatever language you are using to follow along. There are many ways to extend and improve it. Maybe those will be the subject of a future post. Here are a few I can think of:
- Make a JIT compiler — generate native code instead of bytecode
- Re-write this in a language whose runtime is faster than CPython
- Choose a file format and write the compiler and interpreter so that they eject to and read from the disk
- Add a foreign-function interface so that the user can call functions from the host language
- Expose
compileand
evalin the environment to add metaprogramming to your language
- Add macros
- Learn from CPython and store local variables in the frame itself instead of in a dict — this is much faster (see
LOAD_FASTand
STORE_FAST)
- Target an existing VM’s bytecode so you can compile to, say, actual CPython or Lua or something
- Similar to above: target OPy so you can run compiled programs with Andy Chu’s VM | https://www.tefter.io/bookmarks/66910/readable | CC-MAIN-2021-04 | refinedweb | 4,605 | 57.98 |
For a tutorial I need to write a method that will take in a number of minutes, and return a string that formats the number into "hours:minutes".
My answer was:
def time_conversion(minutes)
hrs = 0
min = 0
if minutes >= 60
min = minutes % 60
hrs = (minutes - min) / 60
min = format('%02d',min)
else
min = minutes
end
return "#{hrs}:#{min}"
end
def time_conversion(minutes)
hours = 0
while minutes >= 60
hours += 1
minutes -= 60
end
if minutes < 10
minutes_s = "0" + minutes.to_s
else
minutes_s = minutes.to_s
end
return hours.to_s + ":" + minutes_s
end
Your answer is perfectly fine, if not a better more succinct way for making the method. Performance wise, your answer is only minimally better as you're using a modulos operation where they are using a while loop in their code. I believe the tutorial is answered the way it is, is so that beginners can better grasp control flow and loops. Lastly, you can leave out the 'return' on the second to last line as ruby will implicitly return the last thing it evaluates in a method. But that's more of a individual preference just incase you come across it. | https://codedump.io/share/ldN1qjfEtAvU/1/how-to-efficiently-convert-minutes-to-quothoursminutesquot | CC-MAIN-2017-04 | refinedweb | 192 | 59.53 |
How to make the most out of the top-down fast.ai course, Practical Deep Learning For Coders, Part 1
So far, Practical Deep Learning For Coders, Part 1 taught by Jeremy Howard has been a wonderful class with every one of its lectures packed with cutting edge knowledge and best practices of deep learning. Instead of taking the familiar bottom-up approach, where we first learn all the underlying theories, especially the math, and then gradually build up to real-world level application at the very end, the course takes a top-down approach, which allows us to get exposed to cutting-edge applications and performance starting from the first lesson. In my past schooling experience, the research papers are what we look up to in awe and reverence, something beyond our reach. However, here in this class, we break the records set by famous research papers in almost every dataset we get our hands on, often by a wide margin.
I have always been in a state of wonder when running the record-breaking Jupyter notebooks provided by Jeremy and walked through in lectures: how is it possible that I beat so easily, just in a few lines of codes, the results obtained by a team of brilliant professors and PhD students from prestigious universities, who have years more experience than me? Of course, it is not as easy as it looks. Most of the heavy-lifting has been done by the incredible fast.ai library, an opinionated one that incorporates the state-of-the-art research findings and make a default choice for the users when possible, freeing me from all kinds of traps and loopholes in choosing from an endless collection of frameworks, architectures, and optimizers, followed by fine-tuning hyper-parameters, every step of which is instrumental to the success of training a deep learning model.
The Illusion of Competence
Yet, as almost always, with great abstraction comes great ignorance; it creates an illusion of competence that quickly falters in the face of real-world problems. The lesson 1’s notebook is about building a 37-category pet classification model using CNN. Since the legend says that any article with cute pet pictures will attract people to read, I will put one here.
Here is a code snippet example from the notebook:
data = ImageDataBunch.from_name_re(path_img, fnames, pat, ds_tfms=get_transforms(), size=224, bs=bs
).normalize(imagenet_stats)
For now, please focus on
ds_tfms=get_transforms() and ignore the remaining details. Here,
ds_tfms stands for dataset transformation, more commonly known as data augmentation, which generates copies of the images, each of which is changed in such a way that it looks slightly different visually but still distinctively belong to the category it should belong to. If you feel that it sounds sketchy to you, you are on the point. However, as for lesson 1, this is the level of understanding I reached; I had a rough idea about what it does and assumed it to work. It did, beautifully, on the Oxford pet classification dataset, but got me straight into a shipwreck when later working on one created on my own, a collection of car images labeled according to the angles or views. Here are some examples, each with a different label of angles:
Just a note here, I labeled these 1000-plus images from scratch in hours using the amazing data preparation platform Platform.ai built, again, by our awesome Jeremy Howard. I strongly recommend you to check it out. It is hella cool and free to use for now.
Investigation
Since it is also an image classification problem, I basically copied and pasted the codes from lesson 1 notebook with little modification. However, the training failed miserably and could not even get to an accuracy above 80%. This is highly unusual as the problem itself is extremely simple, only differentiating the photos on very basic geometric properties. I started walking through the codes, especially focusing on the black boxes I assumed to work before. Eventually I started investigating
get_transforms() and looked into its documentation.
def argument
do_flip:bool=True looks very suspicious to me. Here are some more documentations:
doflip: if True, a random flip is applied with probability 0.5
flipvert: requires doflip=True. If True, the image can be flipped vertically or rotated of 90 degrees, otherwise only an horizontal flip is applied
There is also a demonstration of the transformation, with cute pet photos of course:
So apparently the default transforms will flip my images horizontally at a 50% chance. It. Is fine for kitties as a kitty flipped horizontally is still a kitty, but for my specific dataset, the label depends on the very horizontal view angle of the car itself. As a result, the image transformations will completely mess up the image labels. No wonder the training does not work. After adding an additional argument to the function call,
get_transforms(do_flip=False), the training went as smooth as usual and I got a merry 96% validation accuracy.
The Lesson
What is the lesson here? As stated at the beginning of this article,
fast.ai is a highly opinionated library with many built-in assumptions, thus able to perform at a very high level on many deep learning datasets and problems right out of the box. For example, the default data augmentation works very well on most image classification dataset. However, for certain datasets that do not meet the assumptions, like that horizontal orientation does not change image labels, it would perform significantly worse. To be able to use the library on more datasets, inevitably we need to look into the black boxes and understand what the library is doing.
The question here is, however, when to look into the black boxes. There is much merit in the top-down approach of learning. If we simply look into every black box we encounter, then the learning experience is no different from a bottom-up one. The strategy I take is to only do so when the black box does not work as expected. In the spirit of the wise old saying “if it ain’t broke, don’t fix it,” I would suggest here that “if an abstraction ain’t broken, don’t look into it.” To use the jargon of machine learning, the process of breaking down the abstraction and fine tuning our understanding of it is just like training the model with more data. At the beginning of the training, when the model has been through only a small set of data, it does not generalize well; when we just started learning and using an abstraction, we overfit our understanding of the black box to the few examples we have seen.
However, just like it does not make sense to train our models to aptly recognize all the different dog and cat species in order to differentiate a dog and a cat, we don’t need to know every tiny detail of the abstraction to start using it for some very general problems. Nevertheless, we do need to give ourselves opportunities to encounter occasions where the rough conception broken down; only then can we learn how to apply it to more general problems. That is why in a top-down approach learning, it is instrumental to apply what you have learned to a slightly different set of problems. If neglected, your understanding of the knowledge works in the messy real world will work as poorly as a model trained with a tiny dataset.
Next time when learning a material top-down, if you get stumbled applying it to a real-world problem, don’t panic, doubt the learning approach, or even outright switch back to the rabbit hole of bottom-up learning. Remind yourself that it is an integral, and, indeed, the most rewarding part of the top-down learning experience, just like solving challenging problems is for learning math. Do your research, read the documentation, understand the source code, or even dig into the mathematics theory behind until you have refined your understanding of the abstraction enough to solve the problem. You will come out with a much better understanding of the concept and that is how you grow. At the same time, unlike in a bottom-up approach, where you have no clue why you are learning all the materials until the very end, you will always have a motivation and sense of purpose throughout the whole learning experience, as every bit of your work is directed to solve a problem at your hand. For me, learning top-down has been a dramatically more satisfying and rewarding experience. I hope that you can enjoy it as well. Happy top-down learning. | https://medium.com/@georgezhang_33009/how-to-make-the-most-of-the-top-down-fast-ai-courses-ae70814c736f | CC-MAIN-2019-13 | refinedweb | 1,453 | 56.59 |
C6211
Visual Studio 2005
warning C6211: Leaking memory <pointer> due to an exception. Consider using a local catch block to clean up memory
This warning indicates that allocated memory is not being freed when an exception is thrown. The statement at the end of the path could potentially throw an exception.
Example
The following code generates this warning:
To correct this warning, use exception handler as shown in the following code:
#include<new> #include<iostream> using namespace std; void f( ) { char *p1=NULL; char *p2=NULL; try { p1 = new char[10]; p2 = new char[10]; // code ... delete [] p1; delete [] p2; } catch (bad_alloc &ba) { cout << ba.what() << endl; if (NULL != p1) delete [] p1; if (NULL !=p2) delete [] p2; } // code ... }
See Also
ReferenceC++ Exception Handling
Show: | https://msdn.microsoft.com/en-US/library/f1ac315x(d=printer,v=vs.80).aspx | CC-MAIN-2015-22 | refinedweb | 124 | 66.74 |
TL;DR — If you’re working on a large Python project or just like to keep your code-base tidy and neat, Pytype is the tool for you.
Python is a great programming language for prototyping and scripting. The concise syntax, flexible type system, and interpreted nature allows us to quickly try an idea, tweak it, and try again.
When Python projects grow, the flexibility that was once an enabler for speed becomes a burden on development velocity. As additional developers join the project, and more code is written, the lack of type information makes it harder to read and understand the code. Without a type-checking system, mistakes are easy to make and hard to catch.
Pytype to the rescue! Pytype is an open-source tool for type checking and type inference in Python. And it works out-of-the-box — just install and run!
Pytype will…
- Statically infer type information and check your code for type errors.
- Validate PEP 484 type annotations in your code for consistency.
- Merge back inferred type information into your code, if you want.
If you’re sold, go ahead and visit Pytype for installation and usage instructions. Below I present some cool usage examples!
Example #1: Type inference and checking
This is the most common scenario. You wrote some code and want to sanity-check that you didn’t make any mistakes. Consider this function:
import re def GetUsername(email_address): match = re.match(r'([^@]+)@example\.com', email_address) return match.group(1)
Pretty straightforward. It extracts the part of an email address before the @ using a regular expression, and returns it. Did you notice the bug?
Let’s see what happens when we use
pytype to check it:
% pytype get_username.py Analyzing 1 sources with 0 dependencies File "/.../get_username.py", line 5, in GetUsername: No attribute 'group' on None [attribute-error] In Optional[Match[str]]
Pytype tells us that
group is not a valid function call on
match. Oh!
re.match() returns
None when no match is found. Indeed, in these cases
match.group(1) will throw an exception.
Let’s fix the bug, by having the function return None for an invalid email address:
import re def GetUsername(email_address): match = re.match(r'([^@]+)@example\.com', email_address) if match is None: return None return match.group(1) # <-- Here, match can't be None
Now, when we re-run
pytype, the error is gone. Pytype infers that if the code after the if gets executed, match is guaranteed not to be
None.
Example #2: Validation of type annotations
In Python 3, you can type-annotate (PEP 484) your code to help type-checking tools and other developers understand your intention. Pytype is able to alert when your type annotations have mistakes:
import re from typing import Match def GetEmailMatch(email) -> Match: return re.match(r'([^@]+)@example\.com', email)
Let’s use
pytype to check this code snippet:
% pytype example.py Analyzing 1 sources with 0 dependencies File "/.../example.py", line 5, in GetEmailMatch: bad option in return type [bad-return-type] Expected: Match Actually returned: None
Pytype is telling us that
GetEmailMatch might return
None, but we annotated its return type as
Match. To fix this, we can use the
Optional type annotation from the typing module:
import re from typing import Match, Optional def GetEmailMatch(email) -> Optional[Match]: return re.match(r'([^@]+)@example\.com', email)
Optional means that the return value can be a
Match object or
None.
Example #3: Merging back inferred type information
To help you adopt type annotations, Pytype can add them into the code for you. Let’s look at this code snippet:
import re def GetEmailMatch(email): return re.match(r'([^@]+)@example\.com', email) def GetUsername(email_address): match = GetEmailMatch(email_address) if match is None: return None return match.group(1)
To add type annotations to this code, we first run
pytype on the file.
pytype saves the inferred type information into a
.pyi file. Then, we can run
merge-pyi to merge the type annotations back into the code:
% pytype email.py % merge-pyi -i email.py pytype_output/email.pyi
And voilà!
import re from typing import Match from typing import Optional def GetEmailMatch(email) -> Optional[Match[str]]: return re.match(r'([^@]+)@example\.com', email) def GetUsername(email_address) -> Optional[str]: match = GetEmailMatch(email_address) if match is None: return None return match.group(1)
The type annotations, including
import statements, are now in the source file.
For more usage examples and installation instructions, please visit Pytype on GitHub.
Thanks for reading! | https://www.freecodecamp.org/news/how-to-quickly-find-type-issues-in-your-python-code-with-pytype-c022782f61c3/ | CC-MAIN-2020-24 | refinedweb | 751 | 58.18 |
So I ran into a problem today. I wanted to call a method (TryParse) off a type using relfection, but the catch is that there is an out parameter. At first I though, “Hey, I just give it the type and it will find it. Not so lucky. See when you call GetMethod you have to supply a list of parameters. why? because if you don’t, the name alone could return any number of methods named the same thing. By using a parameter list, it in essence narrows it down to one. Say you look at decimal.TryParse which expects a string and an out parameter of type decimal. Would think it is:
Type[] paramTypes = new Type[2] { typeof(string), typeof(decimal) }; returnValue = typeToCheck.GetMethod("TryParse", paramTypes);
No dice. Looks ok until you actually look at the type of the second parameter. It’s actually “decimal&”, meaning there is a reference attached to it. This makes sense since Out will switch the pointer of the old parameter sent in to whatever you create in the method. Problem is when you trying to find the method you are looking for “decimal” != “decimal&”. Now this looks like a big problem, but it’s actually easy to solve.
Type[] paramTypes = new Type[2] { typeof(string), typeof(decimal).MakeByRefType() };
See the difference? Turns out Microsoft already thought this one through. The MakeByRefType method allows you to simulate an out parameter. Here’s the method in full to get the MethodInfo:
private static MethodInfo GetCorrectMethodInfo(Type typeToCheck) { //This line may not mean much but with reflection, it's usually a good idea to store //things like method info or property info in a cache somewhere so that you don't have //have to use reflection every time to get what you need. That's what this is doing. //Basically I am using the passed in type name as the key and the value is the methodInfo //for that type. MethodInfo returnValue = someCache.Get(typeToCheck.FullName); //Ok, now for the reflection part. if(returnValue == null) { Type[] paramTypes = new Type[2] { typeof(string), typeToCheck.MakeByRefType() }; returnValue = typeToCheck.GetMethod("TryParse", paramTypes); if (returnValue != null) { someCache.Add(typeToCheck.FullName, returnValue); } } return returnValue; }
Now we’re not done yet, are we? No. That just gets the methodInfo needed. Now how do I call it and get a value back? Well that’s pretty easy too:
MethodInfo neededInfo = GetCorrectMethodInfo(typeof(decimal)); decimal output = new decimal(); object[] paramsArray = new object[2] { numberToConvert, output }; object returnedValue = neededInfo.Invoke(returnValue.Value, paramsArray); if (returnedValue is bool && (bool)returnedValue) { returnValue = (decimal)paramsArray[1]; } else { returnValue = null; }
So first part is actually calling the method we now have:
MethodInfo neededInfo = GetCorrectMethodInfo(typeof(decimal)); decimal output = new decimal(); object[] paramsArray = new object[2] { numberToConvert, output }; object returnedValue = neededInfo.Invoke(returnValue, paramsArray);
So basically you take the variables, put them into an array, and then pass that array trough the invoke method. Nice thing is when the two variables are sent into the method, you don’t have to flag output as an Out parameter.
Now for the FINALLY ITS OVER
if (returnedValue is bool && (bool)returnedValue) { returnValue = (decimal)paramsArray[1]; } else { returnValue = null; }
You would think that the “output” variable you sent through .Invoke would hold the needed value. Too bad. You actually have to look at the object array passed in to get the value of the Out parameter. Kind of annoying, but deal with it.
And there you have it, how to not only find a methodInfo with an out parameter, but how to get the value back too. YAY
using System; using System.Reflection;
My next post will show why I had to figure this out and I promise it will be worth it. | http://byatool.com/tag/dynamic/page/3/ | CC-MAIN-2019-13 | refinedweb | 621 | 57.67 |
10 August 2009
By clicking Submit, you accept the Adobe Terms of Use.
This article covers beginning to intermediate concepts in working with audio for the web. General knowledge of the Flash authoring interface and ActionScript fundamentals is advised.
Beginning
This article gives you a solid understanding of working with audio in Adobe Soundbooth CS4 and Adobe Flash CS4 Professional as well as tutorials and sample files to get you up and running. You'll cover the basic techniques to work with audio in ActionScript 3.
Adobe Flash has a long history of successfully deploying audio on the web. Flash 4 introduced support for the MP3 format, which opened up the door for using larger files with better performance. Flash 5 introduced the Sound object in ActionScript and the ability to control sound dynamically in runtime-based applications. Flash MX introduced the FLV format and MP3 metadata support for expanded options in synchronization and data management. Flash CS3 added new levels of audio support with ActionScript 3, capable of displaying sound spectrums and performing enhanced error handling.
Flash CS4 now adds support for the ASND format, which allows you to take a snapshot of the original audio so you can revert edits all the way back to the starting point. In addition, Flash CS4 FLA files (and FLV files) created with Adobe Media Encoder CS4 can now contain XMP metadata, which describes the audio related to the file along with other file information.
When you're developing audio for SWF applications, you need to be aware of the capabilities and requirements of audio in Adobe Flash Player. This section covers everything you need to know to get started.
The general workflow for audio production in Flash CS4 is the same as with other non-vector media. In most cases the audio asset will be acquired and edited externally from the application. When the audio file is prepared, it is then imported into the FLA file or loaded at runtime using ActionScript. This is the first big decision to be made in the process; do you embed the audio or use audio that is external to the Flash movie?
Using embedded audio allows you to import a range of audio formats and has the benefit of visual authoring in the Adobe Flash interface (you don't need to use any coding to implement it). Embedded audio also has the advantage of visual synchronization with graphic content. The disadvantages are the incurred larger file size to the SWF file and the lack of flexibility for changes and runtime manipulation.
Using external audio is generally the way to go for more complex projects. External audio has the advantage of remaining flexible for edits and dynamic play list driven content. It also has the advantage of excluding the audio's file size from the SWF file. The primary disadvantage is that it requires some ActionScript knowledge to implement it. Some tasks like voice synchronization with a character animation on the Timeline work best if the audio is embedded directly on the Timeline.
The following list is divided into the four facets of production that should be considered: file preparation, working with embedded audio, working with external audio, and editing your audio.
General steps in the preparation workflow include the following:
General steps in the embedded audio workflow include the following:
General steps in the external audio workflow include the following:
General steps in the editing workflow include the following:
Before I go further into production techniques, let's take a look at the types of audio formats that Flash Player supports.
It is important to understand that Flash Player is designed to play audio in a few specific formats. By itself, Flash Player cannot record audio streams. However the player does have access to the microphone object on the end viewer's computer and can be combined with the Flash Media Server to record and store sound files on a server or stream the sound to other SWF application instances. The Flash Media Server greatly expands the possibilities of what can be done with Flash audio, but Flash Player by itself works well for streaming sounds for playback.
The Flash Player supports 8-bit or 16-bit audio at sample rates of 5.512, 11.025, 22.05, or 44.1 kHz. The audio can be converted into lower sample rate during publishing, but it is recommended that you use an audio editing application to resample and edit the audio files—outside of Flash CS4. If you want to add effects to sounds in Flash, it's best to use 16-bit sounds. If you have limited RAM on your system, keep your sounds short and use 8-bit audio.
Tip: Your sound needs to be recorded in a format sampled at 44.1 kHz, or an even factor of 44.1, to assure proper playback in the SWF file. Working in an audio production tool built to produce "Flash-friendly" audio can save a lot of headaches dealing with subtle details. Soundbooth CS4 is a solution designed specifically for Adobe Flash audio production and integration with other Adobe tools.
Flash supports a range of audio formats for importing and embedding sounds in a SWF file. You'll need to have QuickTime 4 or higher installed on your computer to take full advantage of the supported formats during authoring (see Table 1).
Table 1. Supported audio formats when importing audio into Flash
Note: The ASND format is a nondestructive audio file format native to Adobe Soundbooth. ASND files can contain audio data with effects, sound scores, and multitrack compositions that can be modified later.
When you embed the audio, Flash CS4 bundles the sound with the SWF file. In most cases the embedded sound will be compressed along with the rest of the assets in the file during publishing. So in the case of embedded audio, you also have to think about the exported audio format as well (see Table 2).
Table 2. Supported audio formats when exporting embedded audio in a SWF
Notice that while QuickTime is required for importing the full range of supported audio formats, it is not needed to export them or play the published movie. Flash Player handles the playback of the four export formats. The default and most commonly used audio format is MP3. Also notice that all formats are supported on Mac and Windows regardless of whether the file required a Mac during the authoring process.
The export audio format can be set globally in the Publish Settings dialog box or set per sound file. To adjust audio settings globally, edit the event and streaming fields in the Publish Settings (File > Publish Settings). To adjust audio settings per sound, right-click the sound in the Library to launch the Sound Settings dialog box (see Figure 1).
When you work with embedded audio that is attached to a timeline, you have to decide whether to handle each sound as "event" audio or "streaming" audio in Flash Player. This is a concept that specifies how the audio relates to its timeline (or not). Streaming audio signals Flash Player to synchronize the audio to the timeline to which it is attached, and to start playing the sound as it downloads. When you stream audio, you attach the sound to a timeline and the audio playback is directly synched to the length of that timeline. This approach is commonly used for synchronization with animated content and for streaming playback of larger content files.
Event audio signals Flash Player to handle the sound's playback without regard to its timeline. If its timeline contains a limited number of frames, such as a button, the sound can play from start to finish. Event audio has to download completely before it can play, and therefore is most commonly used for short sounds, such as button clicks.
Flash Player supports playback of external audio in MP3 and FLV format. The MP3 format has been a mainstay with Flash developers since the Flash 4 era whereas the FLV format became an option in Flash MX (6) when the Flash Media Server implemented the format for Flash video and audio streaming.
Tip: Flash Player 9,0,115 and later supports the HE-AAC audio codecs along with H.264 video.
The MP3 format is commonly used because it is familiar to developers from other areas of web production. MP3 formatted files are relatively easy to produce and easy to share with other web-based applications. While this may be the case, there are some advantages to working with the FLV format. FLV formatted files can hold metadata, such as cue points for synchronization. You can also manipulate FLV audio files using the FLVPlayback component, which allows you to load the sound and create a playback interface with little to no ActionScript knowledge. As audio editing tools such as Soundbooth now export source audio to FLV format, FLV has become a viable option for developers working outside of the Flash Media Server environment.
Table 3. Supported audio formats when playing external audio in Flash
Flash Player 6 and later supports metadata for both the MP3 and FLV formats. MP3 files support the ID3 v1.0 and v1.1 standard. FLV files support FLV video metadata parameters, including cue points for content synchronization and custom parameter entries. In both cases the metadata can be retrieved at runtime using event handler functions in ActionScript.
Tip: Flash CS4 FLA files and FLV files created with Adobe Media Encoder CS4 can also contain XMP metadata, which describes the audio related to the file along with other file information. XMP metadata conforms to W3C standards and can be used by web-based search engines to return meaningful search results about the SWF file and its internal content.
See Working with sound metadata in the Programming ActionScript 3 for Flash online documentation for more information on MP3 metadata. Also check out Using cue points and metadata to learn more about working with FLV metadata.
Flash Lite is a runtime engine used to display SWF files on consumer electronics and mobile devices. This article focuses on implementing audio for playback in Flash Player; however it's interesting to note that Flash Lite supports the playback of device sounds such as MIDI and SMAF, among others. See Import and play a device sound in the Developing Flash Lite 2.x and 3.0 Applications online documentation for more information on working with Flash Lite and deploying audio in mobile devices.
Soundbooth CS4 is an audio editing tool that integrates with Flash CS4 and other software in Adobe Creative Suite 4. Soundbooth provides a range of editing and composition tools in a simple workflow that anyone can use. New to this version is the editable ASND format—the ability to create multitrack compositions—along with a handful of other upgrades.
This section focuses on the basic tasks you'll commonly work through when preparing audio for Flash in Soundbooth. For full documentation, see the Soundbooth CS4 online documentation.
One of the most accessible and least expensive ways to obtain audio files is to record the sound yourself. The Soundbooth environment takes this into account and provides the means to record and clean up the artifacts commonly incurred when recording audio outside of a professional studio.
To prepare Soundbooth for audio recording, follow these steps:
To record audio, follow these steps:
For more best practices on recording techniques, see the following resources:
One of the unique features of Soundbooth is the ability to generate soundtracks by combining audio and video clips with prebuilt audio compositions called scores. Basically, you can create a soundtrack that adds your content on top of professional compositions. You can also use the score without additional content as a quick way to add background audio to your movie. Each score template provides a range of editable parameters that allow you to customize and export the score as a new audio file. You may also save customized score templates for reuse later.
For the purposes of this tutorial, I'll focus on the simple audio clip that you recorded in the previous section. To find more information on working with scores, see Customizing scores in the Using Soundbooth CS4 online documentation.
Tip: Soundbooth ships with two default scores available for immediate use. You can acquire more templates by launching the Resource Central panel from the Windows menu.
In addition to recording your own audio and creating your own scores, you can open prerecorded audio and video sources to work with as well. The process is fairly easy. You open a file and edit it using the range of features in Soundbooth. Or you open a handful of files and copy and paste portions of them to collage together a multitrack sound file. You may also open files to use as reference clips while working with a score template.
To open an audio or video file, follow these steps:
New to Soundbooth CS4 is the ability to save an editable source file in ASND format. The ASND format allows you to take a snapshot of the original audio so you can revert edits all the way back to the starting point. You can save ASND files for future editing and embed them directly in Flash CS4 FLA files.
Before you make edits to your source audio, you should save the file in the ASND format:
Soundbooth has some great clean up features built-in to help you create the best quality audio from an office environment. This is a fairly common situation for a web developer; you may be using professional equipment, but you're working in an office environment instead of an actual sound booth. In my studio I often deal with the hum of several large computers or an occasional dog bark that needs to be edited out of an otherwise great track.
To remove noise or clicks and pops from an audio file, follow these steps:
To remove a sound from an audio file, follow these steps:
Another editing best practice is to cut the high frequencies out of the signal before converting the file to a compressed format. Doing so will produce a compressed sound with less of the artifacts that are commonly heard in web audio.
To cut the high frequencies or hiss out of the audio before export, follow these steps:
I find that I run through a standard set of editing steps before moving on toward exporting the file to a compressed format. Usually that includes trimming the audio to the correct length, adding fades and effects, and normalizing the audio if the levels are too low.
To trim the audio file to a specific length, follow these steps:
To apply an effect, such as the Voice Enhancer, follow these steps:
To add a fade in or out of the sound, follow these steps:
To normalize the recording and boost the volume level, follow these steps:
One of the benefits of this new generation of audio software is the ability to easily generate and export timing markers to use for content synchronization.
To create time markers in your audio file, follow these steps:
To export the markers as an XML file, follow these steps:
Tip: It's interesting to note that you can use the File > Import command to import a marker XML file. This feature allows you to create marker definitions for reuse across other media files or allows you to write markers in XML for output in FLV format. You can also import and export marker XML files in Adobe Media Encoder.
Last stop on the audio production side of things is to export the compressed audio from the source audio. Usually you'll be exporting to MP3 or FLV format, although you can work with ASND, WAV, or AIFF if you plan on embedding the audio in your FLA file.
To export an MP3 audio file, follow these steps:
To export an FLV file (with cue point markers bundled with the audio), follow these steps:
Whether you export your source files in MP3 or FLV format, you should end up with two sets of audio files: your master files (used for editing) and your exported files (served from the website).
Note: If you encode the FLV using Adobe Media Encoder outside of Soundbooth, you can embed the cue points directly in the FLV format. F4V video does not support cue points in the same way as the FLV format.
One topic that's often overlooked in web development is the topic of file management. To maintain a fast and easy workflow while handling multiple projects, your best bet is to use a process for organizing your FLA files, assets files, and website files. In addition, the structure of your FLA files, ActionScript coding, and the interface to the web environment should be simple and organized.
This section focuses on file management approaches in handling assets in the file system, while editing in Soundbooth, and implementing functionality in Flash CS4.
The primary means of file management while working in Soundbooth are the File, Scores, and Resource Central panels. You'll work with these panels while performing routine tasks and selecting files.
Adobe Bridge CS4 is used for audio file management across Soundbooth and all CS4 applications. Bridge is a simple, stand-alone application installed with the CS4 products. Included in its feature set is the ability to browse files, add metadata to files, group related assets, and perform automated tasks and batch commands.
To launch the Adobe Bridge CS4 file management tool, follow these steps:
For more information on Adobe Bridge CS4 features, see the Adobe Bridge/Version Cue online documentation.
Throughout this article the topic of embedded audio vs. external audio has come up. In regards to file management, you have to think about the question before you start setting up your file structure and approach. If you're embedding the audio, then your file management will take place in Flash CS4, where you'll use the FLA file's document Library to create an organized collection of movie clip symbols, sound assets, and library folders. If you're using external audio, then you'll manage the collection of files using XML play lists, an organized folder structure in an application folder, and the new Project panel in Flash CS4.
Consider the organization approach best used if you're planning on embedding your audio. In this case, the Library panel and movie clip symbols become your environment for organization. Embedded audio has to be imported through the File menu in Flash CS4 (File > Import). As you import sounds, they appear in the Library panel. It's important to organize your Library using folders. Otherwise, the view can quickly become a long scrolling list of assets that is unwieldy and impractical to navigate. It is a best practice to use a pattern and choose naming conventions for your Library folders that repeats across projects. This makes it easier for other developers (and even yourself at a later date) to understand where assets are located and where to edit your project (see Figure 12).
In addition to creating an easy to navigate series of folders for the Library assets, you have to think about how you will handle the sounds next. If you use the Sound object in ActionScript, then you can create a single reusable component or script to handle the audio in the Library. If you attach the sounds to a timeline using the Property inspector, then you'll either be separating sounds in buttons symbols, separating sounds in movie clip symbols, or staggering sounds along a single movie clip's timeline.
In the first sample file, three audio files are attached to timelines as event sounds in three separate button symbols. The collection of sound buttons is stored in a "Sound Player" movie clip that encapsulates the controls into a single object on the main Timeline. This type of organization within the FLA file works well for portability and general ease of navigation.
Note: Even though a sound in the Library is not a symbol type, the same concepts apply for reuse. That means you can create as many instances of the sound as you like without adding more file size to the FLA file.
For dynamic applications using sound, the audio files will usually be located external to the SWF file. These types of applications require a different organizational approach. In general, the Flash file should read in a playlist to remain flexible and reusable. Now that you're dealing with separate external files, you should create an organized project folder containing all your assets separated in corresponding folders.
The Project panel is similar to the Dreamweaver Site window, in that it allows you view the file structure of the website while working on a document. Flash CS4 includes an update to the Project panel. You can add FLA files, ActionScript files, and folders, to a project. I use the Project panel as a shortcut to quickly open FLA files, ActionScript files, and text files directly from Flash CS4. I also find it useful to create a list of all the files and folders in my "project" folder for visual reference while thinking about or discussing the site (see Figure 13).
XML is a commonly used format for configuring playlists in SWF applications. For example, let's say that you build an MP3 jukebox application that loads a series of MP3 files and plays them in a simple interface. You probably wouldn't want to rebuild the application every time you wanted to switch the list of MP3 files. And what if you wanted an English version and a Spanish version?
Instead of embedding the audio files, you'll use external MP3 files and set up the jukebox application to read an external playlist. This external playlist is simply an XML formatted text file, which can be easily changed without changing the jukebox application. Furthermore, you could supply the path to the playlist file in the HTML parameters that embed the SWF file on the web page; this approach allows you to switch from English to Spanish file references dynamically or by using a separate HTML page for each language version.
The XML format is simple to learn in the context of Flash development. An XML document is made up of open and close tags (
<myTag></myTag>) similar to HTML tags. The names of the tags, called XML nodes, are user-defined and are intended to describe the data in-between the open and close tags. The node names and the nesting of nodes create a hierarchy of information that can be consumed as a string in any programming language.
A simple playlist document contains references to the audio file paths as well as track names and any other related information, as shown in the XML example below:
<songs> <song> <name>Song 1</name> <source>audio/song1.mp3</source> </song> <song> <name>Song 2</name> <source>audio/song2.mp3</source> </song> <song> <name>Song 3</name> <source>audio/song3.mp3</source> </song> </songs>
Tip: It's a best practice to include the folder path in the XML data in addition to the filename. That way you can easily change files without necessarily having to change the filenames; for example, you could change the folder name to route between multiple languages.
An XML file can also be used to store timing markers for synchronization of content while the audio is playing. One of the useful things about working with XML is that you can define its granularity as needed. For example, you could create a playlist that stores audio file paths and timing markers for each file—all in one playlist. Alternatively, you could create a simple playlist with file references and then create individual XML files containing timing markers per audio file. In this case you would load the synchronization details as needed. When deciding which route to take, the decision usually is based upon the amount of data being described and when the data is needed. If you can get everything in one file, then you can load that file as the application launches and instantly have access to all the information as the movie plays. If the amount of information is so great that you cannot load it all up front, then you can split the data into separate files and load each file as needed.
The general concept of timing markers (more commonly called cue points in ActionScript) is to provide time-based notifications to the SWF application's interface that something is happening. This strategy can be used for synchronizing animation, signaling to the interface that it's time to do something, or for displaying text captions that visually support the audio. Cue points generally have name and time properties associated with them. However, you can combine caption text or anything else that you need when creating the XML file. Remember, the goal is to create an external playlist that is easy to change so that you can update the movie without editing it. Identify all the information you need to update in your project and add the corresponding data in each XML node.
In the example shown below, the playlist has been updated to add cue points and captions to each audio file:
<songs> <song> <name>Song 1</name> <source>audio/song1.mp3</source> <cuePoints> <cuePoint> <name>Cue 1</name> <time>2</time> <caption>Caption 1...</caption> <cuePoint> <cuePoint> <name>Cue 2</name> <time>4</time> <caption>Caption 2...</caption> <cuePoint> </cuePoints> </song> <song> <name>Song 2</name> <source>audio/song2.mp3</source> <cuePoints> <cuePoint> <name>Cue 1</name> <time>5</time> <caption>Caption 1...</caption> <cuePoint> <cuePoint> <name>Cue 2</name> <time>10</time> <caption>Caption 2...</caption> <cuePoint> </cuePoints> </song> </songs>
For more information while you're getting started with XML, read XML in the real world.
Now that you understand the supported audio formats in Flash Player, have prepared files in an audio editing application, and have organized your project to achieve best results, you're ready to jump in and start implementing the audio. There are a number of approaches you can take that range from easy to intermediate in difficultly. This section lists a range of options available to you and supplies examples for each approach.
The easiest strategy is also one of the oldest approaches for synchronizing sounds to graphic content in your FLA file. It involves attaching embedded audio to a keyframe on the Timeline using the Property inspector. The process is fairly easy and can be accomplished quickly without using code.
To embed an audio file and attach it to a button timeline, follow these steps:
If you are following along using the sample files provided on the first page of this article, open sample_1.fla and double-click the Button – One symbol in the Library to view its timeline (see Figure 14). You can experiment with this working example.
To embed an audio file and set it up for synchronized streaming with the timeline, follow these steps:
stopaction at the end of the timeline to keep it from looping and repeating the sound.
The introduction of ActionScript 1.0 in Flash 5 brought along with it the Sound object in ActionScript. The Sound object is an easy to use code feature that allows you to load a sound from the Library dynamically or load an MP3 file from an external location.
To load an embedded sound from the Library using a button symbol and ActionScript 3, follow these steps:
import flash.events.MouseEvent; import flash.media.Sound; function handleClick(event:MouseEvent):void { var snd:Sound = new sound1(); snd.play(); } play_btn.addEventListener(MouseEvent.CLICK,handleClick);
To see a working example of this section, open up sample_2.fla file from the sample files folder. You can examine the project in detail by investigating the code and assets on each layer (see Figure 15).
To load an MP3 file from an external location, follow these steps:
import flash.events.MouseEvent; import flash.media.*; function handleClick(event:MouseEvent):void { var path:String = "audio/mp3/counting1a.mp3"; var stream = new URLRequest(path); var snd:Sound = new Sound(stream); } play_btn.addEventListener(MouseEvent.CLICK,handleClick);
To see a working example of this section, open up sample_3.fla file from the sample files folder. Examine the project by reviewing the code as it is updated for three buttons and plays a different external sound as each button is clicked (see Figure 16).
There are two benefits to using FLV audio. First, FLV files can contain embedded cue point metadata that can easily be used for content synchronization without using XML data. Second, the FLV file can be loaded and manipulated using the FLVPlayback component with little to no coding.
Note: The FLV export feature in Soundbooth does not appear to embed cue points or totalTime metadata. You can use the cue point marker file saved from Soundbooth for synchronization as seen in the next example. For best results, encode your WAV source file to FLV using stand-alone Adobe Media Encoder utility.
To load an FLV audio file using the FLVPlayback component, follow these steps:
skinparameter to choose one of the default skins or set the
skinparameter to
noneto either forego controls or clear the default skins so you can piece together your own controls using the FLVPlayback custom user interface components. For more information on skinning the FLVPlayback components, read Skinning the ActionScript 3 FLVPlayback component.
true.
To synchronize content to an FLV audio file using embedded cue point metadata, follow these steps:
import fl.video.*; import flash.net.*; import flash.events.Event; // Respond to cuePoint events function handleCuePoint(event:MetadataEvent):void { trace("name: = "+event.info.name+", time = "+event.info.time); } // Parse XML and add ActionScript cue // points to the FLVPlayback instance. function addMarkers( xmlData:XML ):void { // Convert the XML format to ActionScript var len:Number = xmlData.CuePoint.length(); for(var i:Number=0; i < len; i++) { var curCueTime:Number = Number(xmlData.CuePoint[i].Time)/1000; var curCueName:String = String(xmlData.CuePoint[i].Name); // Add cue point flvAudio.addASCuePoint(curCueTime,curCueName); } flvAudio.addEventListener(MetadataEvent.CUE_POINT,handleCuePoint); } // Load the XML marker list function dataHandler(event:Event):void { addMarkers(new XML(loader.data)); } var loader = new URLLoader(); loader.addEventListener(Event.COMPLETE, dataHandler); loader.load(new URLRequest("settings/counting1_markers.xml"));
Tip: This code loads the markers file, converts the XML into ActionScript cue points, and listens to the cue point event from the video component to change the currently viewed frame and content.
stop(); import fl.video import flash.net.*; import flash.events.Event; function handleCuePoint(event:MetadataEvent):void { gotoAndStop(event.info.name); } ...
Tip: If you're using Navigation or Event cue points already embedded in the FLV file, simply skip the XML loading parts of the code sample and assign the handleCuePoint event handler to the flvAudio instance.
To see a working example of this section, open up sample_4.fla file from the sample files folder. Examine the project by reviewing the code as it is updated for three buttons and plays a different external sound as each button is clicked (see Figure 17).
While the use of FLV files and cue point metadata can be a powerful way to develop synchronized media, it may not always be an option if the audio files have to be usable outside of a SWF environment. In these cases, you can use MP3 files, XML playlists, and cue point lists to create synchronization between audio and other content.
To load an XML playlist file into ActionScript, follow these steps:
import flash.net.*; import flash.events.Event; var playlist:XML; var loader:URLLoader = new URLLoader(); loader.load(new URLRequest("settings/audio_playlist.xml")); function dataHandler(event:Event):void { playlist= new XML(loader.data); trace(playlist); } loader.addEventListener(Event.COMPLETE, dataHandler);
<?xml version="1.0" encoding="UTF-8" standalone="no" ?> <sounds> <sound> <label>Sound 1</label> <data>audio/mp3/counting1.mp3</data> </sound> <sound> <label>Sound 1</label> <data>audio/mp3/counting2.mp3</data> </sound> <sound> <label>Sound 1</label> <data>audio/mp3/counting3.mp3</data> </sound> </sounds>
To implement an XML playlist in ActionScript 3, follow these steps:
import flash.net.*; import flash.media.*; import flash.events.Event; var playlist:XML; var loader = new URLLoader(); loader.load(new URLRequest("settings/audio_playlist.xml")); // Load the XML play list function dataHandler(event:Event):void { playlist = new XML(loader.data); // Assign the play list to a combobox component for(var n:String in playlist.sound) { var child = playlist.sound[n]; soundList.addItem({label:child.label,data:child.data}); } } loader.addEventListener(Event.COMPLETE, dataHandler); // Load files from the play list when a combobox selection is made var snd:Sound; function changeHandler(event:Event):void { var path:String = event.target.selectedItem.data; snd = new Sound(new URLRequest(path)); snd.play(); } soundList.addEventListener(Event.CHANGE, changeHandler);
Tip: Working with events and event handler functions is the key to handling interactivity in ActionScript 3. Explore the Flash CS4 Help pages (F1) for more information on using audio events to work with metadata and error handling.
To get a working example of this section, open up sample_5.fla file from the sample files folder (see Figure 18).
ActionScript 3 introduced the SoundChannel object, which allows you to stop a sound and respond to its completion without closing the stream. This is a handy trick to know when you want to load a sound once and play it multiple times without streaming it down each time.
To play a sound and control it with a SoundChannel object, follow these steps:
import flash.media.Sound; import flash.media.SoundChannel; import flash.events.MouseEvent; import flash.net.URLRequest; var snd:Sound; var sndChannel:SoundChannel; var sndPlaying:Boolean = false; function playHandler(event:MouseEvent):void { if( sndPlaying ){ stopSound(); } sndPlaying = true; snd = new Sound(new URLRequest("audio/mp3/counting1.mp3")); sndChannel = snd.play(); sndChannel.addEventListener(Event.SOUND_COMPLETE, completeHandler); } function stopHandler(event:MouseEvent):void { stopSound(); } function completeHandler(event:Event):void { stopSound(); } function stopSound():void { sndPlaying = false; sndChannel.stop(); sndChannel.removeEventListener(Event.SOUND_COMPLETE, completeHandler); } play_btn.addEventListener(MouseEvent.CLICK, playHandler); stop_btn.addEventListener(MouseEvent.CLICK, stopHandler);
See sample_6.fla in the sample files for the working example of this section.
ActionScript 3 provides a number of options for sound control beyond the basics discussed here. If you want to take your research further, the next steps will be to look deeper into the SoundChannel object and examine how to control volume, panning, and sound transformations.
Take a look at the Flash CS4 Professional ActionScript 3 sample files and other media sample files to see more sound control examples.
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License | https://www.adobe.com/devnet/flash/articles/web_audio.html | CC-MAIN-2016-07 | refinedweb | 5,792 | 52.8 |
Event for when the OM changes?
On 12/03/2013 at 16:51, xxxxxxxx wrote:
Hey kids,
I need to clean up some widgets and Basedraw stuff if/when someone deletes any objects in the OM. This is for an ObjectData plugin. I CAN check it in GVO but would hate to do that every cycle which seems like a waste. Is there a document message to handle so I can have it do cleanup only when any object is deleted in the OM?
On 12/03/2013 at 16:54, xxxxxxxx wrote:
To be more specific, for example one of the things I need to do is erase references in an In_Ex list if it's parent has been deleted. Here is what I am doing below. I made a lil method to check if there is NONE and erase it and do some recursion to do it again until all the objects in the list are 'real'. This works fine. Just looking for some optimization. Maybe there are Description flags I should be setting to do this automatically so I don't even have to do it in code?
My code I'm using (called every GVO cycle) :
def cleanList(self, camlist) :
for i in xrange(camlist.GetObjectCount()) :
if camlist.ObjectFromIndex(self.__doc, i) == None:
camlist.DeleteObject(i)
self.cleanList(camlist)
On 12/03/2013 at 17:11, xxxxxxxx wrote:
c4d.plugins.nodedata.free() might be what you are looking for.
On 12/03/2013 at 17:21, xxxxxxxx wrote:
Is this not used for when your plug-in itself is being deleted? Looking for a message that tells me when any object (not my plug-in object) is being deleted (or changed in any way) so I can do some cleanup without having to do cleanup of my in_ex list on every cycle.
In the same way I modify a lot of parameters only when the Update Message is sent so I'm not doing it all the time, only when people change something.
On 12/03/2013 at 18:13, xxxxxxxx wrote:
My 2c:
K.I.S.S. and only optimize what really need optimizing.
if not obj:
is slightly faster than
if obj == None:
But even faster is not to do any check at all:
try: except:
And remove the thing that will build up
any except/errors, in this case a faulty
In/Ex List, that will be read for every cycle
giving an error for every cycle (See print below).
I.o.w, refresh the In/Ex List and do a break.
So for example:
for o in xrange(liscount) : listobj = inexlist.ObjectFromIndex(doc,o) try: #do things with your listobj listobj.Message(c4d.MSG_UPDATE) except: inexlist.DeleteObject(o) myplugin[c4d.MY_LIST] = inexlist # rebuild a correct list myplugin.Message(c4d.MSG_UPDATE) print 'GONE' # The error is now only printed once break # start a new cycle only if errors
Cheers
Lennart
On 12/03/2013 at 21:40, xxxxxxxx wrote:
Hey, who're you calling S.? ;)
Thanks, Lennart. As usual, you are supremely wise with your input. I forget try/Except even exists. I'll give it a go. Like usual, thanks for your time as you've saved my arse a number of times now. | https://plugincafe.maxon.net/topic/7022/7921_event-for-when-the-om-changes | CC-MAIN-2020-40 | refinedweb | 542 | 73.27 |
Opened 3 years ago
Closed 3 years ago
Last modified 3 years ago
#20136 closed Cleanup/optimization (fixed)
Recommend note identifying that post_save signals will be fired on loaddata
Description
On:
It says the following:
- When fixture files are processed, the data is saved to the database as is. Model defined save methods and pre_save signals are not called.
However, it does not make specific mention about other signals. Recommend making the text explicit so that readers understand that other signals not mentioned here will be called (post_save et al).
Example:
Let's say you're testing on a local server and you have use post_save to send emails or other notifications. loaddata will resend all emails on load. This is behaviour that, in a test environment, one may wish to avoid.
Related:
Attachments (2)
Change History (10)
Changed 3 years ago by timo
comment:1 Changed 3 years ago by timo
- Has patch set
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Type changed from Uncategorized to Cleanup/optimization
comment:2 Changed 3 years ago by brandon@…
Just looking at the diff, I asked a similar question to 8399 and 13299. The answer suggested creating a decorator to block the signal from loaddata. Seems like it may be a better solution than increasing cyclomatic complexity in signal functions.
Source:
from functools import wraps def disable_for_loaddata(signal_handler): """ Decorator that turns off signal handlers when loading fixture data. """ @wraps(signal_handler) def wrapper(*args, **kwargs): if kwargs['raw']: return signal_handler(*args, **kwargs) return wrapper Then: @disable_for_loaddata def your_fun(**kwargs): ## stuff that won't happen if the signal is initiated by loaddata process
comment:3 Changed 3 years ago by akaariai
If I am not mistaken both pre_save and post_save signals will be sent. There is a raw argument to the signal that can be used to detect when loaddata (or any other method wishing to insert the values as-is to the DB). See.
It seems the loaddata docs are currently plain wrong.
comment:4 Changed 3 years ago by timo
- Patch needs improvement set
- Triage Stage changed from Unreviewed to Accepted
I wouldn't be opposed to documenting the decorator method as I've used it before as well.
comment:5 Changed 3 years ago by brandon@…
That decorator creates some unintended consequences when used in conjunction with django-tastypie (API POST calls skip signals with that decorator). Perhaps not entirely relevant here, but "nice to know".
Changed 3 years ago by timo
comment:6 Changed 3 years ago by timo
- Patch needs improvement unset
Anssi is correct, I've fixed that inaccuracy and added the decorator example.
comment:7 Changed 3 years ago by Tim Graham <timograham@…>
- Resolution set to fixed
- Status changed from new to closed
Added a patch which also attempts to address #13299 since it's related. | https://code.djangoproject.com/ticket/20136 | CC-MAIN-2016-30 | refinedweb | 472 | 55.98 |
On 4/19/21 10:50 PM, Zev Weiss wrote:
[ ... ]
I had a glance at the enclosure driver; it looks pretty geared toward SES-like things (drivers/scsi/ses.c being its only usage I can see in the kernel at the moment) and while it could perhaps be pressed into working for this it seems like it would probably drag in a fair amount of boilerplate and result in a somewhat gratuitously confusing driver arrangement (calling the things involved in the cases we're looking at "enclosures" seems like a bit of a stretch).
As an alternative, would something like the patch below be more along the lines of what you're suggesting? And if so, would it make sense to generalize it into something like 'pmbus-switch.c' and add a PMBUS_HAVE_POWERSWITCH functionality bit or similar in the pmbus code instead of hardcoding it for only LM25066 support?
No. Don't access pmbus functions from outside drivers/hwmon/pmbus.
I used to be opposed to function export restrictions (aka export namespaces),
but you are making a good case that we need to introduce them for pmbus
functions.
Guenter | https://lkml.iu.edu/hypermail/linux/kernel/2104.2/03591.html | CC-MAIN-2022-40 | refinedweb | 190 | 57.61 |
String
Arrays in Java are dynamically created objects; therefore Java arrays are quite different from C and C++ the way they are created. Elements in Java array have no individual names; instead they are accessed by their indices. In Java, array index begins with 0 hence the first element of an array has index zero. The size of a Java array object is fixed at the time of its creation that cannot be changed later throughout the scope of the object. Because Java arrays are objects, they are created using
new operator. When an object is created in Java by using
new operator the identifier holds the reference not the object exactly. Secondly, any identifier that holds reference to an array can also hold value null. Third, like any object, an array belongs to a class that is essentially a subclass of the class Object, hence dynamically created arrays maybe assigned to variables of type Object, also all methods of class Object can be invoked on arrays. However, there are differences between arrays and other objects the way they are created and used.
It is very important to note that an element of an array can be an array. If the element type is
Object or
Cloneable or
java.io.Serializable, then some or all of the elements may be arrays, because any array object can be assigned to any variable of these types.
As it is said earlier, a Java array variable holds a reference to an array object in memory. Array object is not created in memory simply by declaring a variable. Declaration of a Java array variable creates the variable only and allocates no memory to it. Array objects are created (allocated memory) by using
new operator that returns a reference of array that is further assigned to the declared variable.
Note That Java allows creating arrays of
abstract class types. Elements of such an array can either be null or instances of any subclass that is not itself abstract.
Let's take a look at the following example Java array declarations those declare array variables but do not allocate memory for them.
int[] arrOfInts; // array of integers short[][] arrOfShorts; // two dimensional array of shorts Object[] arrOfObjects; // array of Objects int i, ai[]; // scalar i of type int, and array ai of ints
For creating a Java array we first create the array in memory by using
new then assign the reference of created array to an array variable. Here is an example demonstrating creation of arrays.
/* ArrayCreationDemo.java */ // Demonstrating creation of Java array objects public class ArrayCreationDemo { public static void main(String[] args) { int[] arrOfInts = new int [5]; // array of 5 ints int arrOfInts1[] = new int [5]; // another array of 5 ints // array of 5 ints, initializing array at the time of creation int arrOfInts2[] = new int []{1, 2, 3, 4, 5}; //creates array of 5 Objects Object[] arrOfObjects = new Object[5]; Object arrOfObjects1[] = new Object[5]; //creates array of 5 Exceptions Exception arrEx[] = new Exception[5]; // array of shorts, initializing that at the time of creation. short as[] = {1, 2,3, 4, 5}; } }
Above program declares and allocates memory for arrays of types
int,
Object,
Exception, and
short. Most importantly, you would have observed that the array index operator
[] that is used to declare an array can appear as part of the type or as part of the variable. For example,
int[] arr and
int arr[], both declare an array arr of type
int.
The placement of
[] during array declaration makes difference when you declare a scalar and an array in the same statement. For an instance, the statement
int i, arr[]; declares
i as an
int scalar, and
arr as an
int array. Whereas, the statement
int[] i, arr; declares both
i and
arr as
int arrays.
One more example, have a look at following declarations and you would understand the role of placement of array operator (
[]) in array declaration statements.
int[] arr1, arr2[]; //is equivalent to int arr1[], arr2[][]; int[] arr3, arr4; //is equivalent to int arr3[], arr4[];
In Java programming language, there are more than one ways to create an array. For demonstration, an array of
int elements can be created in following number of ways.
int[] arr = new int[5]; int arr[] = new int[5]; /* In following declarations, the size of array * will be decided by the compiler and will be * equal to the number of elements supplied for * initialization of the array */ int[] arr = {1, 2, 3, 4, 5}; int arr[] = {1, 2, 3, 4, 5}; int arr[] = new int[]{1, 2, 3, 4, 5};
Java allows creating an array of size zero. If the number of elements in a Java array is zero, the array is said to be empty. In this case you will not be able to store any element in the array; therefore the array will be empty. Following example demonstrates this.
/* EmptyArrayDemo.java */ // Demonstrating empty array public class EmptyArrayDemo { public static void main(String[] args) { int[] emptyArray = new int[0]; //will print 0, if length of array is printed System.out.println(emptyArray.length); //will throw java.lang.ArrayIndexOutOfBoundsException exception emptyArray[0] = 1; } }
As you can see in the
EmptyArrayDemo.java, a Java array of size 0 can be created but it will be of no use because it cannot contain anything. To print the size of
emptyArray in above program we use
emptyArray.length that returns the total size, zero of course, of
emptyArray.
Every array type has a
public and
final field
length that returns the size of array or the number of elements an array can store. Note that, it is a field named
length, unlike the instance method named
length() associated with
String objects.
You can also create an array of negative size. Your program will be successfully compiled by the compiler with a negative array size, but when you run this program it will throw
java.lang.NegativeArraySizeException exception. Following is an example:
/* NegativeArraySizeDemo.java */ // Demonstrating negative-sized array public class NegativeArraySizeDemo { public static void main(String[] args) { /* following declaration throw a * run time exception * java.lang.NegativeArraySizeException */ int[] arr = new int[-2]; } } OUTPUT ====== D:\>javac NegativeArraySizeDemo.java D:\>java NegativeArraySizeDemo Exception in thread "main" java.lang.NegativeArraySizeException at NegativeArraySizeDemo.main(NegativeArraySizeDemo.java:12) D:\>
Array elements in Java and other programming languages are stored sequentially and they are accessed by their position or index in array. The syntax of an array access expression goes here:
array_reference [ index ];
Array index begins at zero and goes up to the size of the array minus one. An array of size
N has indexes from
0 to
N-1. While accessing an array the index parameter of the array access expression must evaluate to an integer value, using a long value as an array index will result into compile time error. It could be an
int literal, a variable of type
byte,
short,
int,
char, or an expression which evaluates to an integer value.
Another important point you should keep in mind that the validity of index is checked at run time. A valid index must fall between
0 to
N-1 for an N-sized array. Any index value less than
0 and greater than
N-1 is invalid. An invalid index, if encountered, throws
ArrayIndexOutOfBoundsException exception.
Java array elements are printed by iterating through a loop. Since 1.5 Java provides an additional syntax of for loop to iterate through arrays and collections. It is called enhanced
for loop or for-each loop. Use of enhanced for loop is also illustrated in Control Flow - iteration tutorial. Here is an example:
/*
Program
EnForArrayDemo.java demonstrates two important points along with accessing array elements. First, in a two dimensional array of Java, all rows of the array need not to have identical number of columns. Second, if arrays are not explicitly initialized then they are initialized to default values according to their type (see Default values of primitive types in Java). Taking second point into consideration, we have not initializes array
arrTwoD to any value. So the whole array got initialized by zeroes, because
arrTwoD is of type int.
String
Readers, who come from C and C++ background may find the approach, Java follows to arrays, different because arrays in Java work differently than they do in C/C++ languages. In the Java programming language, unlike C, array of
char and
String are different. Character array in Java is not a
String, as well as a
String is also not an array of
char. Also neither a
String nor an array of
char is terminated by
\u0000 (the NUL character).
A
String object is immutable, that is, its contents never change, while an array of
char has mutable elements.
This tutorial explained how to declare, initialize and use Java arrays. Java arrays are created as dynamic objects. Java also supports empty arrays, and even negative size arrays, however, empty arrays cannot be used to store elements. Java provides a special syntax of
for loop called enhanced
for loop or for-each to access Java array elements. Also Java arrays are not
String and the same is true vice versa. | http://cs-fundamentals.com/java-programming/java-array-variables.php | CC-MAIN-2017-17 | refinedweb | 1,526 | 52.49 |
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.
Set default duration in res_config
I have a module that has, a creation date (of course, the day it was created) and a deadline date.
The thing is that I want to be able to set a default value to this deadline date according to the date it was created. But I want to be able to configurate this dynamically from (lets say) res_config.
e.g.
If I configured the default values in res_config to 5 days, I want the default value for the deadline date to be populated with a date 5 days ahead of the creation date.
Is this possible?
Thank you
I managed to do this using the model
ir.configure_parameter.
In res_config.py:
class my_configuration(osv.osv_memory): _inherit = ['res.confi.settings'] _columns = { 'default_deadline' : fields.integer('Days per default', help="""Help field"""), } ... def set_default_deadline(self, cr, uid, ids, context=None): config = self.browse(cr, uid, ids) config = config and config[0] val = '%s' %(config.default_deadline) or '10' self.pool.geet('ir.config_parameter').set_param(cr,uid, 'key_value', val) return True
Whit this we have created a system parameter. It is actually created as a mapping from 'key_value' to val that is a string, so we will have to cast it to the desired type when necessary. In my case, y created a function to get the deadline date in my module:
def _get_deadline_date(self, cr, uid, context=None): val = self.pool.get('ir.config_parameter').get_param(cr, uid, 'key_value') try: val = int(val) except: # Just in case... val = 30 return (datetime.now() + timedelta(days=val)).strftime('%Y,%m,%d') _defaults = { 'deadline_date': lambda s, cr, uid, c: s._get_deadline_date(self, cr, uid, context=c), }
Thank you, hope it helps!
you will need to give only default_model='' " in field ..then no req to over write get and set method ..it should work automatically..whre ever u want to set deadline there you have to get this value and set deadline
Sorry, but I don't know what you mean with the field 'default_model'. Where is it? Actually, my idea wasn't to over write the get/set method, it is just a function to get the default value for the field (maybe the name picking was not the most accurate!). Thanks!
To expand on Turky's comment: You don't need to write your own functions to set and get the default value. It is enough that you add the 'default_model' parameter to your column definition:
class my_configuration(osv.osv_memory): _inherit = ['res.config.settings'] _columns = { 'default_deadline' : fields.integer('Days', default_model='object.name'), }
For this to work correctly you will need:
- a field named 'deadline' in your 'object.name' object
- the column providing the default value in your res.config.settings class must begin with default_
Good one! I did not know that! Nevertheless, the thing is that I am actually setting a numeric value, representing the numbers of days for default for a the objects of my model, so, the default value for deadline_date must be (x days + cration_date) where x is the integer that you can set in my_configuration.
As long as the field type for the default value in res.config and the field type in your object are the same. OpenERP will do the right thing.
Yes, that's the thing in my case, they where not! Because I wanted to set a date "on the fly", adding a time delta to the creation date. Setting a date as default will just set in all records the field with the value in res.config. Hope I am not missing something here!
I'm not sure if I understand correctly, but here goes: In your main object you should have three fields: begin_date, deadline_date and deadline_delta. The begine_date and deadline_date fields are date fields and deadline_delta would be an integer field. Then in res.config you would have a field called default_deadline_delta, which is an integer. Then in your main object you would have an onchange method on the begin_date field, which when triggered would change the value of deadline_date by adding deadline_delta to begin_date. I hope I have correctly understood what you want to do.
Yes, the answer you are giving me fit my requirements perfectly! The thing is that, by doing so, I would create a field in the database for every record of my model, that is to be filled on creation time and never to be modified again. (If you want to change the deadline_date you should change it directly not changing the deadline_delta). Thanks for your concern! :D
yes this is possible using resconfig.you can define defaultdeadline | https://www.odoo.com/forum/help-1/question/set-default-duration-in-res-config-373 | CC-MAIN-2017-04 | refinedweb | 793 | 66.84 |
OSEE/ATS/Users Guide
Contents
- 1 Configuration
- 2 Views and Editors
- 2.1 ATS Icons
- 2.2 ATS Navigator
- 2.3 ATS Action View
- 2.4 ATS World View
- 2.5 Result View
- 2.6 ATS Workflow Editor
- 2.7 ATS Workflow Editor - Workflow Tab
- 2.8 ATS Workflow Editor - Task Tab
- 2.9 Working Branch Widget
- 2.10 Commit Manager Widget
- 2.11 ATS Workflow Configuration Editor
- 2.12 Work Flow Definition Artifact
- 2.13 Work Page Definition Artifact
- 2.14 Work Rule Widget Artifact
- 2.15 Work Rule Definition Artifact
- 2.16 Mass Artifact Editor
- 2.17 Table Customization
- 3 Using ATS
- 3.1 Report a Bug
- 3.2 Priorities for classifying problems
- 3.3 OSEE Spell Checking
- 3.4 Peer To Peer Review Workflow
- 3.5 Decision Review Workflow
- 3.6 Configure ATS for Change Tracking
- 3.7 Configure Team Definition
- 3.8 Configure Actionable Items (AI)
- 3.9 Workflow Configuration
- 3.10 Configure ATS for Help
- 3.11 OSEE Branching and Differences Diagrams
Configuration.
- Create a New configuration using the ATS Configuration Wizard
- Select File -> New -> Other -> OSEE ATS -> ATS Configuration
- Enter in a unique namespace for your configuration (e.g.: org.company.code)
- Enter in a name for the Team that will be performing the work (e.g.: See Configure ATS for Change Tracking Configure ATS for Change Tracking for more information.
- Editing an existing workflow configuration using the ATS Workflow Configuration Editor
- In the Branch Manager, set the Default Working Branch to the Common branch.
- Configure ATS for Change Tracking.
Views and Editors value file.
Mulit-page
Selecting the down arrow will show a list of all pages that have been displayed during the current instance of OSEE running. Selecting from this list will display the previous page..).
Using ATS
Report a Bug
Purpose
A quick way to report a bug against a view or editor.
How to do it
Select the bug button (
) from the toolbar at the top
of the view or editor that has the problem. A wizard will come up to provide guidance
through the rest of the steps.
Priorities for classifying problems
OSEE Spell Checking.
State Machine.
Review State.
Decision State "ATS Overview". For example, that Name: Extended name for the team. Expansion of acronym if applicable.
- Team relations to be configured:
- TeamActionableItem: relation to all AIs that this team is responsible for.
- Work Item.Child: WorkFlowDefinition artifact configures the state machine that this team works under. Note that privileged Team.
- Work Flow Definition specifies the states, their transitions and the state that represents the beginning of the workflow.
- Work Page Definition defines the a single state of the Work Flow Definition.
- Work Widget Definition defines a single widget and its corresponding attribute that the value will be stored in. It also provides some layout capabilities for that widget.
- Work Rule Definition defines certain rules that can be applied to Work Pages and Team Definitions.
How to do it
- Workflows can be created using the ATS Workflow Configuration Editor (0.6.0 release). States and their transitions can be edited through this interface. Other modifications will need to be edited through Work Flow Definition attributes and relations.
- Work Pages, Widgets and Rules are currently edited through the attributes and relations using the default Artifact Editor. See links above to set the proper values.
- | http://wiki.eclipse.org/index.php?title=OSEE/ATS/Users_Guide&oldid=158755 | CC-MAIN-2016-50 | refinedweb | 554 | 53.78 |
Suppose we have an array called nums of positive integers. We have to select some subset of nums, then multiply each element by an integer and add all these numbers. The array will be a good array if we can get a sum of 1 from the array by any possible subset and multiplicand.
We have to check whether the array is good or not.
So, if the input is like [12,23,7,5], then the output will be True, this is because If we take numbers 5, 7, then 5*3 + 7*(-2) = 1
To solve this, we will follow these steps −
g := nums[0]
for initialize i := 1, when i < size of nums, update (increase i by 1), do −
g := gcd of g and nums[i]
return true when g is 1
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int gcd(int a, int b){ return !b ? a : gcd(b, a % b); } bool isGoodArray(vector<int>& nums){ int g = nums[0]; for (int i = 1; i < nums.size(); i++) g = gcd(g, nums[i]); return g == 1; } }; main(){ Solution ob; vector<int> v = {12,23,7,5}; cout << (ob.isGoodArray(v)); }
{12,23,7,5}
1 | https://www.tutorialspoint.com/check-if-it-is-a-good-array-in-cplusplus | CC-MAIN-2021-31 | refinedweb | 212 | 67.38 |
How do you make a password gate in a windows program?
This is a discussion on Password gate within the Windows Programming forums, part of the Platform Specific Boards category; How do you make a password gate in a windows program?...
How do you make a password gate in a windows program?
What's a password gate?
"If you tell the truth, you don't have to remember anything"
-Mark Twain
I'm just going to guess what you mean by 'password gate'..
Here is some code I just threw together as an example of console password input. This code will most likely contain bugs, but it should give you the general idea.
It's quite possible I missunderstood what 'password gate' meant, if I did, just ignore this whole postIt's quite possible I missunderstood what 'password gate' meant, if I did, just ignore this whole postCode:#include <iostream> #include <conio.h> using namespace std; bool GetPassword(char * CorrectPass, int PassMaxLength) { char * str = new char[PassMaxLength+1]; char chr; int InputCounter = 0; do { chr = getch(); if(chr == (char)8) { if(InputCounter == 0) continue; InputCounter--; cout << (char)8 << " " << (char)8; } else if(chr != '\r') { str[InputCounter] = chr; cout << "*"; InputCounter++; } } while(InputCounter < PassMaxLength && chr != '\r'); str[InputCounter] = '\0'; if(strcmp(str,CorrectPass) == 0) {delete[] str; return true;} delete[] str; return false; } int main() { cout << "Password: "; if(GetPassword("password",100) == true) cout << "\nCorrect Password!" << endl; else cout << "\nYou Suck!" << endl; return 0; }
r1ck0r has the right idea, but it's not windows, it's DOS.
Below is an example of a password gate.
There is a 'Windows Programming' section on this forum, this question would've been more suited there. Anyway, this link: will give you an introduction into windows programming. | http://cboard.cprogramming.com/windows-programming/64446-password-gate.html | CC-MAIN-2013-20 | refinedweb | 289 | 63.39 |
Opened on 07/11/2014 at 12:34:03 PM
Closed on 08/25/2015 at 02:34:31 PM
#768 closed change (fixed)
Switch from TR1 to C++11
Description (last modified by trev)
Background
Currently we have to use newer features like shared_ptr only with tr1 prefix, features like unique_ptr cannot be used at all.
What to change
Enable C++11 for our code. To do this we need to replace libstdc++ by libc++ for Android - the former cannot be linked statically due to licensing issues, which means that we depend on whichever version is installed on the system - and that one can be very outdated for some Android devices. Notes:
- libc++ was only recently added to the Android NDK, most likely with Android NDK r9d. We'll need to update requirements.
- It seems that the GCC version in Android NDK is too old for libc++ - GCC 4.6 says "sorry, unimplemented: mangling dotstar_expr" (seems to have been fixed in GCC 4.7). clang works however.
- We need to let googletest determine itself whether tuple header is available rather than overriding the decision with macros.
- In shell/src/Main.cpp the result of std::getline() cannot be converted to bool - we were probably exploiting an implementation detail of libstdc++ there.
Attachments (0)
Change History (13)
comment:3 Changed on 07/11/2014 at 12:42:46 PM by trev
comment:4 Changed on 07/11/2014 at 02:29:27 PM by trev
comment:6 Changed on 08/28/2014 at 07:29:24 AM by fhd
- Cc rjeschke added
One thing we didn't consider enough here I think: What about client applications written in C++98/03? As it stands, they won't be able to use libadblockplus once we merge this.
Note that TR1 isn't particularly portable either - has never been as widely supported as C++03, and compilers are starting to drop support for it. Boost can serve as a drop-in replacement for TR1 (which largely came from Boost). Adding a huge dependency isn't nice, but this would be the easiest way to arrive at something highly portable.
Adding René - what do you think?
comment:7 Changed on 09/04/2014 at 10:57:35 PM by fhd
I've just confirmed that all the major libadblockplus clients should be able to use C++11, so I suppose we could merge this.
However, I'd like to consider the alternatives that would keep us C++98 compatible. Here's the stuff we use in headers that client applications will include:
- std::shared_ptr
- std::enable_shared_from_this
- std::function
The only way to stay C++98 compatible will be to eliminate this stuff from the public API. (We can still go nuts with C++11 features as we see fit in our implementation as long as the standard library is linked statically).
I think we have two reasonable options for this:
- Use that stuff from boost - it's zero effort since it'll actually be a drop-in replacement. The major downside is that it'll add megabytes worth of headers to the project even when using bcp, which is supposed to only copy individual boost libraries. However, I'm pretty sure we can get away with a hand full of headers if we copy what we need manually (I think bcp will just copy all of Boost.Core).
- Write our own replacements. std::shared_ptr is a textbook excercise. std::enable_shared_from_this sounds doable, too. Replacing std::function could be as simple as using a plain old functor in the public API.
Neither option sounds really brilliant. But frankly, it sounds better to me than to make it impossible for most C++ projects out there to use libadblockplus overnight.
comment:8 Changed on 09/05/2014 at 02:16:15 PM by sergz
I'm also not aware about the clients which don't support used features of C++11. If there are some concrete troubles, could somebody please post them here?
As I understand there is no troubles at the linking stage now and the client code is compiled by the same compiler as the library code. So I would suggest to keep the code clean without compatibility "polyfills" so far.
I think we have two reasonable options for this:
- Use that stuff from boost...
- Write our own replacements...
I would add another option, we can access them from our own namespace. For example with the shared_ptr like abp::shared_ptr and in our own namespace we can choose between std::shared_ptr, std::tr1::shared_ptr and boost::shared_ptr, we can leave it up to the client. As well for the enums as far as I know recent compilers allow to use enum type name as prefix like in C++11, thus MyEnumType::valueX without emulating of scoped enums.
But so far there is no concrete troubles I would consider all this options like overengineering.
comment:10 Changed on 09/05/2014 at 05:53:24 PM by fhd
That's a great solution Sergei! All we'd have to do is import whatever the user wants (C++11, TR1 or Boost) into our own namespace and that's it. We could easily do this with a define.
But I suppose I'm the only one thinking we should stay backwards compatible just-in-case, so I guess we should do it the way you suggested: Require C++11 and see if it's a problem for anyone. I'm happy that we have an easy workaround in case this happens.
We should definitely point this out in the README though. Will say that in the review.
comment:11 Changed on 09/05/2014 at 06:15:07 PM by sergz
comment:12 Changed on 06/23/2015 at 11:10:14 AM by trev
- Owner trev deleted
Unassigning, feel free to take it as I won't finish this any more. I can add you as a "contributor" to the existing review.
comment:13 Changed on 08/25/2015 at 02:34:31 PM by sergz
- Resolution set to fixed
- Status changed from reviewing to closed
- Tester set to Unknown
Note that we also need to replace everything from TR1 we use with the C++11 equivalents in the same step. libc++ doesn't have TR1 support, it's a C++11+ library. (We can keep auto_ptr for now though, even though we should soon replace it with unique_ptr once we moved to C++11.) | https://issues.adblockplus.org/ticket/768/ | CC-MAIN-2022-33 | refinedweb | 1,080 | 69.21 |
Hello,
My project contain tests that can be executed in several environments. So far I've defined three environments pointing to different equipments that have different endpoints and credentials. These are the only difference between them.
I want to extend the use of my tests to other users that have their own equipment with a new endpoint and their own credentials. As I don't know how many of them will need to use my tests, I think of passing endpoint and credentials to the testRunner in order to configure the default environment via a groovy script before executing the tests.
Is it possible to do so ?
thanks for any help
Alexandre
Solved!
Go to Solution.
Well,
I did not manage to understand it enough to apply it to my case, so I ended up with a dynamic setting.
I removed the use of Enviroment parameter in testRunner (now it uses default) and I provide as additional parameters the endpoint and credentials for my new environment.
Then I parse my requests and when I hit the first one, if data is provided and the endpoint is different from the default one, I update values with the parameters provided.
I noticed that changing it on one API impacts all the other APIs so I do it only once. As it is done with testRunner, modification is not persistent which perfectly suits my needs.
Here's the procedure :
in all my setup scripts I call configuration test case that I provide with the parameters and then I set the properties to the step
def endpoint = context.expand( '${#TestCase#endpoint}' )
def username = context.expand( '${#TestCase#username}' )
def password = context.expand( '${#TestCase#password}' )
... <checking the completness of data>
endpoint = "http://"+endpoint
// updating endpoint and credentials require to modify only once
found = false
project.testSuites.find(){
ts ->
ts.getValue().getTestCaseList().find(){
tc ->
tc.getTestStepList().find(){
step ->
//log.info step.config.type
if ((tc.name.contains("/m2m/fim/items"))&&( step.config.type == "restrequest"))
{
current_endpoint = step.getPropertyValue("endpoint")
// update environment if it is not the one expected
if (current_endpoint != endpoint)
{
step.setPropertyValue("endpoint", endpoint)
if( (username == "")||(password == ""))
{
msg = "the current Username and/or Password have not been set for environment $endpoint"
testRunner.fail(msg)
log.error msg
}
else
{
step.setPropertyValue("Username", username)
step.setPropertyValue("Password", password)
log.info "updated environment to $endpoint"
}
}
found = true
}
}
}
}
Thanks for the help @nmrao
Thanks for the link, @nmrao .
@krogold, did this help?
Hi @krogold ,
Thanks for sharing the solution and for providing such detailed information.Great to hear you have found a way to solve this! | https://community.smartbear.com/t5/SoapUI-Pro/Is-it-possible-to-overload-default-environment-propgrammatically/m-p/187737 | CC-MAIN-2019-35 | refinedweb | 425 | 50.43 |
Here is my compilation of example code for a variety of database operations written in VB.NET These range from: Continue reading “VB.NET Basic Database Query Examples”
Category: SQLDataAdapter
ASP.NET Example – Populating a DataSet Using SQLDataAdapter Fill DataSet
In the example functions below I’m illustrating how to set up a basic query to a stored procedure in your database that takes a single string parameter. The examples involve using the SQLDataAdapter object to Fill a DataSet. The resulting DataTable can then be queried as desired. Specifically:
- The first example shows how to read the first row of the results after your Datatable has been populated. I provide the same example in VB.NET and C#.
- The second example shows how to loop through the results if you anticipate multiple returned rows. As before, I provide the same example in VB.NET and C#.
As part of this code, remember to include the correct .NET Namespaces. If you are writing your code inline (in either VB.NET or C#), use:
<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %>
and if you are writing your code in codebehind, use:
VB Codebehind:
Imports System.Data Imports System.Data.SqlClient
C# Codebehind:
using System.Data; using System.Data.SqlClient;
Also, navigate here if you are interested in further articles I have written about ADO in .NET. | https://jwcooney.com/category/net/ado-net/sqldataadapter/ | CC-MAIN-2021-39 | refinedweb | 226 | 52.97 |
(6)
Vishal Gilbile(5)
Akshay Phadke(5)
Jasbeer Singh(4)
John Antony(3)
Satyaprakash Samantaray(3)
Sumit Deshmukh(3)
Mohit Chhabra(3)
Juan Francisco Morales Larios(3)
Nilesh Shah(3)
Rajkiran Swain(2)
Jesus Morales(2)
Viral Jain(2)
Ramees (2)
Khaja Moizuddin(2)
Praveen Kumar Sreeram(2)
Bikesh Srivastava(2)
Prasanna Murali(2)
Jignesh Trivedi(2)
Swagata Prateek(1)
Munish A(1)
Sourav Bhattacharya(1)
Prakashraj P(1)
Suketu Nayak(1)
Jamil Moughal(1)
Akhil Mittal(1)
Upendra Pratap Shahi (1)
Faizan Amjad(1)
Mukesh Shah(1)
Diamondantony Joseph(1)
Rakesh (1)
Vinodhini M(1)
Devinder Yadav(1)
Umair Hassan(1)
Ravi Ranjan Kumar(1)
Khuram Shahzad(1)
Vignesh Mani(1)
Rahat Yasir(1)
Prashant Kumar(1)
Daniel Jones(1)
Arvind Singh Baghel(1)
Ahmad Anas(1)
Pramod Thakur(1)
Rakesh Trivedi(1)
Kuppurasu Nagaraj(1)
Delpin Susai Raj(1)
Rafnas T P(1)
Suraj Nohar(1)
Sounik Chandra(1)
Debendra Dash(1)
Allen O'neill(1)
Hemanth Kumar(1)
Suchit Khunt(1)
Shiju Joseph(1)
Ananth G(1)
Jinal Shah(1)
Sourabh Mishra(1)
Debasis Saha(1)
Asma Khalid(1)
Sourabh Somani(1)
Vignesh Ganesan(1)
Syed Shanu(1)
Mayank Verma(1)
Resources
No resource found..
Ruby On Rails Introduction And Installation
Jun 21, 2017.
In this article you will learn about the introduction and installation for Ruby on Rails step by step.
Introduction To JavaScript Promises
Jun 21, 2017.
In this article you will learn about JavaScript Promises.
Introduction To BootBox JavaScript Library In ASP.NET MVC
Jun 21, 2017.
Bootbox.js is designed to make using Bootstrap modals easier..
Azure Cosmos DB - Part One - Introduction To The World Of NOSQL
May 23, 2017.
Azure Cosmos DB Introduction To The World Of NOSQL.
Data Structures And Algorithms - Part Two - A Word About Big-O Notation
May 22, 2017.
This article is an introduction to Big-O Notation, which is used to measure the running time of a function/ method.
Introduction To Machine Learning
May 22, 2017.
Introduction To Machine Learning.
Learn AngularJS Series Part One - Introduction
May 22, 2017.
Learn AngularJS Series Part One - Introduction.
Data Structures And Algorithms - Part One - Introduction
May 22, 2017.
Introduction to data structures and algorithms.
Introduction To Azure Cloud Shell
May 19, 2017.
Introduction to Azure Cloud Shell.
Introduction To Windows Template Studio
May 19, 2017.
A brief guidance for Windows developers to understand about new Windows Template Studio.
Introduction To Azure Functions
May 17, 2017.
Introduction To Azure Functions.
Introduction To Dapper Generic Repository
May 15, 2017.
This article introduces you to the introduction to Dapper Generic Repository.
Introduction To Microsoft Business Intelligence
May 14, 2017.
Introduction To Microsoft Business Intelligence.
Azure WebJobs
May 09, 2017.
The article given below will give you a brief introduction about Azure WebJobs.
Introduction To Azure Search Service
May 08, 2017.
This article acquaints you with Azure Search Service.
A Brief Introduction To Azure Resource Group
May 04, 2017.
This article will give a brief introduction about Azure Resource Group and what it is used for.
Introduction To Azure CLI 2.0 And Its Installation
May 04, 2017.
Introduction To Azure CLI 2.0 And Its Installation.
Introduction To Bootstrap And How To Install It
May 03, 2017.
How to Download and install Bootstrap.
Introduction To Web Services Using AngularJS In ASP.NET MVC
May 03, 2017.
Introduction To Web Services Using AngularJS In ASP.NET MVC.
An Introduction To Interface
May 02, 2017.
In this Article, I will explain about Interface and why an interface is known as pure polymorphism.
Introduction Of Big Data
Apr 30, 2017.
In this article, I will discuss about Big data and where it is used and how it will perform in various applications in the world.
A Brief Introduction To LINQ
Apr 27, 2017.
Introduction to LINQ.
Introduction To AngularJS In ASP.NET MVC
Apr 26, 2017.
Introduction To AngularJS In ASP.NET MVC.
Introduction To MS Graph Explorer
Apr 25, 2017.
In this article, I will introduce you to MS Graph Explorer and what you can do with it.
Introduction To Xamarin For Beginners
Apr 18, 2017.
Introduction To Xamarin For Beginners.
A Basic Introduction To Unit Test For Beginners
Apr 11, 2017.
In this article, you will learn what unit test is and how to use it, using C# language.
Introduction To Tag Helpers
Apr 01, 2017.
ASP.Net Core : Introduction to Tag Helpers.
Overview And Getting Started With AngularJS In ASP.NET Using Visual Studio 2017
Mar 31, 2017.
This article presents an overview and introduction to AngularJS In ASP.NET, using Visual Studio 2017.
Introduction To ADO.NET
Mar 20, 2017.
In the article, we will learn the usage of ADO.NET technology used with ASP.NET..
Introduction To Serverless Computing Using Azure Functions
Mar 07, 2017.
In this article, you will learn Serverless Computing using Azure Functions.
Introduction To Azure Machine Learning Studio
Feb 28, 2017.
In this article, you will learn about Azure Machine Learning Studio.
Introduction To Routing In Angular 2
Feb 27, 2017.
In this article, you will learn about Routing in Angular 2.
Introduction To Microsoft Sway In Office 365
Feb 24, 2017.
This article introduces you to Microsoft Sway in Office 365.
Introduction To Dependency Injection And Services In Angular 2
Feb 21, 2017.
In this article, you will learn about Dependency Injection and Services in Angular 2.
Introduction To Featured Modules In Angular 2
Feb 20, 2017.
In this article, you will learn about featured modules in Angular 2.
Introduction To Mount Point In SQL Server
Feb 17, 2017.
This article will give you brief information on SQL Server Mount Point and its benefits and you will learn how to set up a new partition.
Introduction To AES And DES Encryption Algorithms In .NET
Feb 17, 2017.
In this article, I am going to explore encryption and decryption. We will see some of the encryption algorithms with C# example code..
Introduction To Services In Angular 2
Feb 16, 2017.
In this article, you will learn about Services in Angular 2.
Introduction To SearchAll Control In WPF
Feb 15, 2017.
In this article, you will learn about SearchAll Control in WPF.
Introduction To Microsoft Power BI
Feb 13, 2017.
In this article, you will learn about Microsoft Power BI.
Introduction To Code First Approach In Entity Framework
Feb 11, 2017.
In this article, you will learn about Entity Framework Code First Approach.
Introduction To JavaScript
Feb 10, 2017.
In this article, we will learn what JavaScript is and why we should use it.
Introduction To Activity Life Cycle And Invoking An Activity From Another Activity
Feb 09, 2017.
In this article, you will learn about activity life cycle and invoking an activity from another activity.
Introduction To Directives In Angular 2
Feb 09, 2017.
In this article, you will learn about directives in Angular 2.
Introduction To Angular 2 - Day One
Feb 04, 2017.
In this article, you will learn about Angular 2.
Introduction To SQL Database Query Editor In Azure Portal
Feb 01, 2017.
In this article, you will learn how to use SQL Database Query Editor in Azure Portal.
Introduction To ASP.NET REST Web API And Drawbacks Of Web Services And WCF - Part One
Feb 01, 2017.
In this article, you will learn about ASP.NET REST Web API and drawbacks of Web Services and WCF.
Introduction To Apache Cordova In Universal Windows Platform Using Visual Studio
Jan 30, 2017.
In this article, you will get an introduction to Apache Cordova in Universal Windows Platform, using Visual Studio.
Introduction To Types In C#
Jan 30, 2017.
In this article, you will learn about Types in C#.
Introduction To Entity Framework
Jan 26, 2017.
In this article, we will see what Entity Framework and Object Relational Mapping in Entity Framework are. We will understand this with an example.
Introduction To Events In AngularJS
Jan 18, 2017.
This article is about AngularJS events. You will learn about AngularJS events and their uses in this article.
Introduction To Bootstrap Tables
Jan 17, 2017.
In this article, we will learn how to use tables in bootstrap.
Introduction To Blob Storage And Its Components
Jan 17, 2017.
In this article, you will learn about Blob Storage and its Components.
Introduction To NUnit Testing Framework
Jan 14, 2017.
In this article we are going to learn the basics of Nunit.
Introduction To Event Binding And Nested Components In AngularJS
Jan 13, 2017.
In this article, you will learn about event binding and nested components in AngularJS.
Introduction To Filters In AngularJS
Jan 12, 2017.
This article is about AngualrJS filters and their use. You can also create your own custom filters.
Introduction To Pipes In Angular 2
Jan 12, 2017.
In this article, you will learn about Pipes in Angular 2.
Introduction To Scope In AngularJS
Jan 11, 2017.
This article is about Angular scope, life cycle of scope, and hierarchy of scope.
Introduction To AngularJS Services
Jan 10, 2017.
This article is about Angular Services. This will give you a brief idea about Angular Services and how can we create our own services.
Importing Api List From Swagger And Introduction To Collection In Postman
Jan 09, 2017.
In this article, you will learn how to import API list from Swagger and an introduction to collection in Postman.
What Is Data Quality?
Jan 03, 2017.
A short introduction to data quality, and why you should consider it.
C# Tutorial Part 2 - The First Error In Your Application
Dec 28, 2016.
This article gives an introduction to namespace, class, and methods used when an error occurs.
Introduction To LINQ
Dec 26, 2016.
In this article you will learn an introduction to LINQ.
Introduction To Code4Fun Metro Flow Component In UWP
Dec 15, 2016.
In this article, we are going to learn about working with the Code4Fun metro flow component.
Introduction To Code4Fun Color Picker Component In UWP
Dec 14, 2016.
In this article, we are going to learn about working with the Code4Fun color picker tool.
A Brief Introduction To ASP.NET Core
Dec 13, 2016.
In this article, you will learn about ASP.NET as an open source framework and you will see various details of ASP.NET. First, we will differentiate .NET Framework (which 4.6/) and .NET Core (ASP.NET 5.0).
Azure Redis Cache – Introduction
Dec 09, 2016.
In this article, you will learn what Azure Redis Cache is
Introduction To ELMAH In MVC
Dec 07, 2016.
In this article, you will learn about ELMAH and how to use and configure it in MVC.
Introduction To Data Science In Visual Studio
Dec 05, 2016.
In this article, you will learn about Data Science in Visual Studio.
An Introduction To .NET Decompiler
Dec 04, 2016.
This article explains about .NET Decompiler.
Introduction To Data Binding In Angular 2
Dec 02, 2016.
In this article, you will learn about data binding in Angular2.
Introduction To Safe Navigation Operator In Angular 2
Dec 01, 2016.
In this article, you will learn about the Safe Navigation Operator in Angular 2
Introduction To ASP.NET Core
Nov 27, 2016.
In this article, you will learn an introduction to ASP.NET Core.
Introduction To Selenium 3.0
Nov 26, 2016.
In this article, we will learn about Selenium 3.0.
AngularJS 2.0 From Beginning - Introduction of AngularJS 2.0
Nov 23, 2016.
In this article, we will discuss the basics of AngularJS 2.0. This is the first part of the article series.
Game Development - An Introduction
Nov 22, 2016.
This article is all about answering common questions, which need to be addressed before jumping into the starry domain of game development.
Introduction To Generic IEqualityComparer
Nov 20, 2016.
In this article, you will learn about Generic IEquality Comparer.
Getting Started With NodeJS
Nov 18, 2016.
In this article, we will discuss about an introduction, advantages, limitations and installation of NodeJS.
Introduction Of Cumulative Update
Nov 17, 2016.
In this article, you will learn about Cumulative Update.
Introduction To ASP.NET Core, WEB API And Repository Class- Part One
Nov 16, 2016.
In this article you will learn an introduction to ASP.NET Core, Web API and Repository Class.
Introduction To WCF
Nov 14, 2016.
In this article. you will learn about WCF.
Introduction To Ionic Templates
Nov 10, 2016.
In this article, you will learn about Ionic Templates.
Introduction To Universal Windows Platform And Creating A Basic Application
Nov 08, 2016.
In this article, you will learn about Universal Windows Platform app.
Introduction To Ionic
Nov 03, 2016.
In this article, you will learn about Ionic.
Introduction To Entity Framework Core
Oct 26, 2016.
In this article, you will learn about Entity Framework Core.
About Velocity-introduction
NA
File APIs for .NET
Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more! | http://www.c-sharpcorner.com/tags/Velocity-introduction | CC-MAIN-2017-30 | refinedweb | 2,147 | 61.22 |
KTF is available as a standalone git repository, but we are also working to offer it as a patch set for integration into the kernel. Read more about KTF in our introductory blog post, here:
Here we're going to try and describe how we can use KTF to write some tests. The neat thing about KTF is it allows us to test kernel code in kernel context directly. This means the environment we're running our tests in affords a lot of control.
Here we're going to try and write some tests for a key abstraction in Linux kernel networking, the "struct sk_buff". The sk_buff (socket buffer) is the structure used to store packet data as it moves through the networking stack. For an excellent introduction, see
In fact we're going to base our tests around some of the descriptions there, by creating/manipulating/freeing skbs and asking questions like
...etc. My hope is that we can show that adding tests is in fact a great way to understand an API. If we can formalize the guarantees of the API such that we can write tests to validate them, we've come a long way in understanding it.
KTF allows us to test both exported and un-exported kernel interfaces in test cases which are added in a dedicated test module. We can make assertions about state during these test cases and the results are communicated to userspace via netlink sockets. The googletest framework is used in conjunction with this framework. While KTF supports hybrid user- and kernel-mode tests, here we will focus on kernel-only tests.
First let's grab a copy of KTF and build it. We use separate source and build trees, and because KTF builds modules we need kernel-specific builds. Because we are building kernel modules we will also need the kernel-uek-devel package. We build googletest from source.
Note: these instructions are for Oracle Linux; some package names etc may differ for other distros. Full instructions can be found in the doc/installation.txt file in KTF. We use Knut's version of googletest as it includes assertion counting and better test case naming.
# yum install cmake3 # cd ~ # mkdir -p src build/`uname -r` # cd src # git clone # cd ~/build/`uname -r` # mkdir googletest # cd googletest # cmake3 ~/src/googletest/ -DBUILD_SHARED_LIBS=ON # make # sudo make install
We need kernel-uek-devel and cpp packages to build. Finally once we have built ktf, we insert the kernel module.
# sudo yum install kernel-uek-devel cpp libnl3-devel # cd ~/src # git clone # cd ktf # autoreconf # cd ~/build/`uname -r` # mkdir ktf # cd ktf # PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig ~/src/ktf/configure KVER=`uname -r` # make # sudo make install # sudo insmod kernel/ktf.ko
Getting started here is easy; Knut created a "ktfnew" program to populate a new suite:
# ~/src/ktf/scripts/ktfnew -p ~/src skbtest Creating a new project under ~/src/skbtest
Let's see what we got!
# ls ~/src/skbtest ac autom4te.cache configure.ac m4 Makefile.in aclocal.m4 configure kernel Makefile.am
The kernel subdir is where we will add tests to our "skbtest" module, and it has already been populated with a file:
# ls ~/src/skbtest/kernel Makefile.in skbtest.c
skbtest.c is a simple module with one test "t1" in test set "simple" which evaluates a true expression via the EXPECT_TRUE() macro. The module init function adds the test via the ADD_TEST(name) macro.
ASSERT_() and EXPECT_() macros are used to test conditions, and if they fail the test fails. We can clean up by using the ASSERT_*_GOTO() variants which we can pass a label to jump to on failure. ASSERTs are fatal to a test case execution. We will see more examples of this later on.
#include <linux/module.h> #include "ktf.h" MODULE_LICENSE("GPL"); KTF_INIT(); TEST(simple, t1) { EXPECT_TRUE(true); } static void add_tests(void) { ADD_TEST(t1); } static int __init skbtest_init(void) { add_tests(); return 0; } static void __exit skbtest_exit(void) { KTF_CLEANUP(); } module_init(skbtest_init); module_exit(skbtest_exit);
So we're ready to start adding our tests!
Before we do anything else, let's ensure we track our progress with git.
We remove "configure" as we don't want to track it via git, we create it with "autoreconf".
# cd ~/src/skbtest # rm configure # git init . # git add ac aclocal.m4 configure.ac kernel/ m4 Makefile.* # git commit -a -m "initial commit"
The first thing we need to do is ensure that our tests have access to the skb interfaces. We need to add
Next, let's add a simple test that makes assertions about skb state after allocation.
/** * alloc_skb_sizes() * * ensure initial skb state is as expected for allocations of various sizes. * - head == data * - end >= tail + size * - len == data_len == 0 * - nr_frags == 0 * **/ TEST(skb, alloc_skb_sizes) { unsigned int i, sizes[] = { 127, 260, 320, 550, 1028, 2059 }; struct sk_buff *skb = NULL; for (i = 0; i < ARRAY_SIZE(sizes); i++) { skb = alloc_skb(sizes[i], GFP_KERNEL); ASSERT_ADDR_NE_GOTO(skb, 0, done); ASSERT_ADDR_EQ_GOTO(skb->head, skb->data, done); /* * skb->end will be aligned and include overhead of shared * info. */ ASSERT_TRUE_GOTO(skb->end >= skb->tail + sizes[i], done); ASSERT_TRUE_GOTO(skb->tail == skb->data - skb->head, done); ASSERT_TRUE_GOTO(skb->len == 0, done); ASSERT_TRUE_GOTO(skb->data_len == 0, done); ASSERT_TRUE_GOTO(skb_shinfo(skb)->nr_frags == 0, done); kfree_skb(skb); skb = NULL; } done: kfree_skb(skb); } static void add_tests(void) { ADD_TEST(alloc_skb_sizes); }
If one of our ASSERT_ macros fails, we will goto "done", and we clean up there by freeing the skb. Ensuring tests tidy up after themselves is important as we don't want our tests to induce memory leaks!
Now we build and run our test.
Here we build our test kernel module. Since we installed ktf/googletest in /usr/local, we need to tell configure to look there.
# cd ~/src/skbtest # autoreconf # cd ~/build/`uname -r` # mkdir skbtest # cd skbtest # ~/src/skbtest/configure KVER=`uname -r` --prefix=/usr/local --libdir=/usr/local/lib64 --with-ktf=/usr/local # make # sudo make install
Now let's load our test module (we loaded ktf above) and run the tests:
# sudo insmod kernel/skbtest.ko # sudo LD_LIBRARY_PATH=/usr/local/lib64 /usr/local/bin/ktfrun [==========] Running 1 test from 1 test case. [----------] Global test environment set-up. [----------] 1 test from skb [ RUN ] skb.alloc_skb_sizes [ OK ] skb.alloc_skb_sizes, 42 assertions (0 ms) [----------] 1 test from skb (0 ms total) [----------] Global test environment tear-down [==========] 1 test from 1 test case ran. (0 ms total) [ PASSED ] 1 test.
Now the above admittedly looks pretty dull. However it's worth emphasizing something before we move on.
This code actually ran in-kernel! With a lot of pain, it would be possible to hack up a user-space equivalent test, but it would require adding definitions for kmalloc, kmem_cache_alloc etc. Here we test the code in the same environment in which it is run, with no caveats or special-purpose environments. This makes KTF execution pretty unique; no need for extensive stubbing, we're testing the code as-is.
Next we're going to try and inject an error and see how skb allocation behaves in low-memory conditions.
KTF allows us to catch function execution and return and mess with the results via kprobes; or specifically kretprobes. To catch a return value we declare:
KTF_RETURN_PROBE(function_name, function_handler) { void *retval = (void *)KTF_RETURN_VALUE(); ... KTF_SET_RETURN_VALUE(newvalue); return 0; }
We get the intended return value witl KTF_RETURN_VALUE(), and we can set our own via KTF_SET_RETURN_VALUE(). Note that the return value that the above function returns should always be 0 - the value that the functionw we're probing actually returns is set by KTF_SET_RETURN_VALUE(). For neatness, if it's a memory allocation we should free it, otherwise we'll be inducing a memory leak with our test!
However we face a few problems with this sort of error injection.
First, the kmem_cache used - skbuff_head_cache - is not exported as a symbol, so how do we access it in order to kmem_cache_free() our skb memory?
Luckily, ktf has a handy function for cases like this - ktf_find_symbol(). We pass in the module name (NULL in this case because it's a core kernel variable) and the symbol name, and we get back the address of the symbol. Remember though that this is essentially &skbuff_head_cache, so we need to dereference it before use.
Second, we don't want to fail skb allocations for everyone as that will kill our network access etc. So by recording the task_struct * for the test in alloc_skb_nomem_task, we can limit the damage to our test thread.
Here's what the test looks like in full:
struct task_struct *alloc_skb_nomem_task; KTF_RETURN_PROBE(kmem_cache_alloc_node, kmem_cache_alloc_nodehandler) { struct sk_buff *retval = (void *)KTF_RETURN_VALUE(); struct kmem_cache **cache; /* We only want alloc failures for this task! */ if (alloc_skb_nomem_task != current) return 0; /* skbuf_head_cache is private to skbuff.c */ cache = ktf_find_symbol(NULL, "skbuff_head_cache"); if (!cache || !*cache || !retval) return 0; kmem_cache_free(*cache, retval); KTF_SET_RETURN_VALUE(0); return 0; } /** * alloc_skb_nomem() * * Ensure that in the face of allocation failures (kmem cache alloc of the * skb) alloc_skb() behaves sensibly and returns NULL. **/ TEST(skb, alloc_skb_nomem) { struct sk_buff *skb = NULL; alloc_skb_nomem_task = current; ASSERT_INT_EQ_GOTO(KTF_REGISTER_RETURN_PROBE(kmem_cache_alloc_node, kmem_cache_alloc_nodehandler), 0, done); skb = alloc_skb(128, GFP_KERNEL); ASSERT_ADDR_EQ_GOTO(skb, 0, done); alloc_skb_nomem_task = NULL; done: KTF_UNREGISTER_RETURN_PROBE(kmem_cache_alloc_node, kmem_cache_alloc_nodehandler); kfree_skb(skb); } static void add_tests(void) { ADD_TEST(alloc_skb_sizes); ADD_TEST(alloc_skb_nomem); }
Let's run it!
# sudo LD_LIBRARY_PATH=/usr/local/lib64 /usr/local/bin/ktfrun [==========] Running 2 tests from 1 test case. [----------] Global test environment set-up. [----------] 2 tests from skb [ RUN ] skb.alloc_skb_nomem [ OK ] skb.alloc_skb_nomem, 2 assertions (27 ms) [ RUN ] skb.alloc_skb_sizes [ OK ] skb.alloc_skb_sizes, 42 assertions (0 ms) [----------] 2 tests from skb (27 ms total) [----------] Global test environment tear-down [==========] 2 tests from 1 test case ran. (27 ms total) [ PASSED ] 2 tests.
Neat! Our error injection must have worked since alloc_skb() returned NULL, and we also cleaned up the memory that was really allocated but we pretended wasn't.
Next we might wonder; given the arguments, can we see what happens when we provide an invalid size? But what is an invalid size? 0? UINT_MAX? Let's try a test where we pass in 0 and UINT_MAX and expect alloc_skb() to fail:
TEST(skb, alloc_skb_invalid_sizes) { unsigned int i, sizes[] = { 0, UINT_MAX }; struct sk_buff *skb = NULL; for (i = 0; i < ARRAY_SIZE(sizes); i++) { skb = alloc_skb(sizes[i], GFP_KERNEL); ASSERT_ADDR_EQ_GOTO(skb, 0, done); } done: kfree_skb(skb); }
Build again, and let's see what happens:
# sudo LD_LIBRARY_PATH=/usr/local/lib64 ktfrun [==========] Running 3 tests from 1 test case. [----------] Global test environment set-up. [----------] 3 tests from skb [ RUN ] skb.alloc_skb_invalid_sizes /var/tmp/build/4.14.35+/skbtest/kernel/skbtest.c:113: Failure Assertion '(u64)(skb)==(u64)(0)' failed: (u64)(skb)==0xffffa07b53ca6c00, (u64)(0)==0x0 [ FAILED ] skb.alloc_skb_invalid_sizes, where GetParam() = "alloc_skb_invalid_sizes" (19 ms) [ RUN ] skb.alloc_skb_nomem [ OK ] skb.alloc_skb_nomem, 2 assertions (23 ms) [ RUN ] skb.alloc_skb_sizes [ OK ] skb.alloc_skb_sizes, 2 assertions (0 ms) [----------] 3 tests from skb (42 ms total) [----------] Global test environment tear-down [==========] 3 tests from 1 test case ran. (42 ms total) [ PASSED ] 2 tests. [ FAILED ] 1 test, listed below: [ FAILED ] skb.alloc_skb_invalid_sizes, where GetParam() = "alloc_skb_invalid_sizes" 1 FAILED TEST
Okay so that failed, which means our allocation succeeded; why? Taking a closer look at alloc_skb(), there's no bar on 0 values. What about UINT_MAX, that shouldn't work, right? Actually it does! If we look at the code however, the size value that gets passed in gets the sizeof(struct skb_shared_info) etc added to it. So we just overflow the value, but what's interesting about that is we'll end up with an skb that invalidates the initial state expectations. Let's demonstrate that by add UINT_MAX to our "sizes" array in our valid skb alloc test "alloc_skb_sizes":
unsigned int i, sizes[] = { 0, 127, 260, 320, 550, 1028, 2059, UINT_MAX };
Rebuilding and running we see this:
# sudo LD_LIBRARY_PATH=/usr/local/lib64 ktfrun [==========] Running 3 tests from 1 test case. [----------] Global test environment set-up. [----------] 3 tests from skb [ RUN ] skb.alloc_skb_invalid_sizes [ OK ] skb.alloc_skb_invalid_sizes, 2 assertions (0 ms) [ RUN ] skb.alloc_skb_nomem [ OK ] skb.alloc_skb_nomem, 2 assertions (23 ms) [ RUN ] skb.alloc_skb_sizes /var/tmp/build/4.14.35+/skbtest/kernel/skbtest.c:45: Failure Failure '(skb->end >= skb->tail + sizes[i])' occurred [ FAILED ] skb.alloc_skb_sizes, where GetParam() = "alloc_skb_sizes" (15 ms) [----------] 3 tests from skb (38 ms total)
So if we pass UINT_MAX to alloc_skb() we end up with a broken skb, in that skb->end isn't pointing where it should be.
Seems like there could be some range checking here, but alloc_skb() is such a hot codepath it's likely the pragmatic argument that "no-one should allocate dumb-sized skbs" wins. We can modify our test to use "safer" bad sizes for now:
TEST(skb, alloc_skb_invalid_sizes) { /* We cannot just use UINT_MAX here as the "size" argument passed in * has sizeof(struct skb_shared_info) etc added to it; let's settle for * UINT_MAX >> 1, UINT_MAX >> 2, etc. */ unsigned int i, sizes[] = { UINT_MAX >> 1, UINT_MAX >> 2}; struct sk_buff *skb = NULL; for (i = 0; i < ARRAY_SIZE(sizes); i++) { skb = alloc_skb(sizes[i], GFP_KERNEL); ASSERT_ADDR_EQ_GOTO(skb, 0, done); } done: kfree_skb(skb); }
In general the skb interfaces assume the data they are provided is sensible, but we've just learned what can happen when it isn't! Writing tests is a great way to learn about an API. | https://blogs.oracle.com/linux/writing-kernel-tests-with-the-new-kernel-test-framework-ktf | CC-MAIN-2020-34 | refinedweb | 2,200 | 55.44 |
In the past, creating analytical web applications was a task for seasoned developers that required knowledge of multiple programming languages and frameworks. That’s no longer the case. Nowadays, you can make data visualization interfaces using pure Python. One popular tool for this is Dash.
Dash gives data scientists the ability to showcase their results in interactive web applications. You don’t need to be an expert in web development. In an afternoon, you can build and deploy a Dash app to share with others.
In this tutorial, you’ll learn how to:
- Create a Dash application
- Use Dash core components and HTML components
- Customize the style of your Dash application
- Use callbacks to build interactive applications
- Deploy your application on Heroku
You can download the source code, data, and resources for the sample application you’ll make in this tutorial by clicking the link below:
Get the Source Code: Click here to get the source code you’ll use to learn about creating data visualization interfaces in Python with Dash in this tutorial.
What Is Dash?
Dash is an open source framework for building data visualization interfaces. Released in 2017 as a Python library, it’s grown to include implementations for R and Julia. Dash helps data scientists build analytical web applications without requiring advanced web development knowledge.
Three technologies constitute the core of Dash:
- Flask supplies the web server functionality.
- React.js renders the user interface of the web page.
- Plotly.js generates the charts used in your application.
But you don’t have to worry about making all these technologies work together. Dash will do that for you. You just need to write Python, R, or Julia and sprinkle it with a bit of CSS.
Plotly, a Canada-based company, built Dash and supports its development. You may know the company from the popular graphing libraries that share its name. Plotly (the company) open-sourced Dash and released it under an MIT license, so you can use Dash at no cost.
Plotly also offers a commercial companion to Dash called Dash Enterprise. This paid service provides companies with support services such as hosting, deploying, and handling authentication on Dash applications. But these features live outside of Dash’s open source ecosystem.
Dash will help you build dashboards quickly. If you’re used to analyzing data or building data visualizations using Python, then Dash will be a useful addition to your toolbox. Here are a few examples of what you can make with Dash:
- A dashboard to analyze trading positions in real-time
- A visualization of millions of Uber rides
- An interactive financial report
This is just a tiny sample. If you’d like to see other interesting use cases, then go check the Dash App Gallery.
Note: You don’t need advanced knowledge of web development to follow this tutorial, but some familiarity with HTML and CSS won’t hurt.
The rest of this tutorial assumes you know the basics of the following topics:
- Python graphing libraries such as Plotly, Bokeh, or Matplotlib
- HTML and the structure of an HTML file
- CSS and style sheets
If you feel comfortable with the requirements and want to learn how to use Dash in your next project, then continue to the following section!
In this tutorial, you’ll go through the end-to-end process of building a dashboard using Dash. If you follow along with the examples, then you’ll go from a bare-bones dashboard on your local machine to a styled dashboard deployed on Heroku.
To build the dashboard, you’ll use a dataset of sales and prices of avocados in the United States between 2015 and 2018. This dataset was compiled by Justin Kiggins using data from the Hass Avocado Board.
How to Set Up Your Local Environment
To develop your app, you’ll need a new directory to store your code and data and a clean Python 3 virtual environment. To create those, follow the instructions below, choosing the version that matches your operating system.
If you’re using Windows, then open a command prompt and execute these commands:
c:\> mkdir avocado_analytics && cd avocado_analytics c:\> c:\path\to\python\launcher\python -m venv venv c:\> venv\Scripts\activate.bat
The first command creates a directory for your project and moves your current location there. The second command creates a virtual environment in that location. The last command activates the virtual environment. Make sure to replace the path in the second command with the path of your Python 3 launcher.
If you’re using macOS or Linux, then follow these steps from a terminal:
$ mkdir avocado_analytics && cd avocado_analytics $ python3 -m venv venv $ source venv/bin/activate
The first two commands perform the following actions:
- Create a directory called
avocado_analytics
- Move your current location to the
avocado_analyticsdirectory
- Create a clean virtual environment called
venvinside that directory
The last command activates the virtual environment you just created.
Next, you need to install the required libraries. You can do that using
pip inside your virtual environment. Install the libraries as follows:
(venv) $ python -m pip install dash==1.13.3 pandas==1.0.5
This command will install Dash and pandas in your virtual environment. You’ll use specific versions of these packages to make sure that you have the same environment as the one used throughout this tutorial. In addition to Dash, pandas will help you handle reading and wrangling the data you’ll use in your app.
Finally, you need some data to feed into your dashboard. You can download the data as well as the code you see throughout this tutorial by clicking the link below:
Get the Source Code: Click here to get the source code you’ll use to learn about creating data visualization interfaces in Python with Dash in this tutorial.
Save the data as
avocado.csv in the root directory of the project. By now, you should have a virtual environment with the required libraries and the data in the root folder of your project. Your project’s structure should look like this:
avocado_analytics/ | ├── venv/ | └── avocado.csv
You’re good to go! Next, you’ll build your first Dash application.
How to Build a Dash Application
For development purposes, it’s useful to think of the process of building a Dash application in two steps:
- Define the looks of your application using the app’s layout.
- Use callbacks to determine which parts of your app are interactive and what they react to.
In this section, you’ll learn about the layout, and in a later section, you’ll learn how to make your dashboard interactive. You’ll start by setting up everything you need to initialize your application and then you’ll define the layout of your app.
Initializing Your Dash Application
Create an empty file named
app.py in the root directory of your project, then review the code of
app.py in this section. To make it easier for you to copy the full code, you’ll find the entire contents of
app.py at the end of this section.
Here are the first few lines of
app.py:
1import dash 2import dash_core_components as dcc 3import dash_html_components as html 4import pandas as pd 5 6data = pd.read_csv("avocado.csv") 7data = data.query("type == 'conventional' and region == 'Albany'") 8data["Date"] = pd.to_datetime(data["Date"], format="%Y-%m-%d") 9data.sort_values("Date", inplace=True) 10 11app = dash.Dash(__name__)
On lines 1 to 4, you import the required libraries:
dash,
dash_core_components,
dash_html_components, and
pandas. Each library provides a building block for your application:
dashhelps you initialize your application.
dash_core_componentsallows you to create interactive components like graphs, dropdowns, or date ranges.
dash_html_componentslets you access HTML tags.
pandashelps you read and organize the data.
On lines 6 to 9, you read the data and preprocess it for use in the dashboard. You filter some of the data because the current version of your dashboard isn’t interactive, and the plotted values wouldn’t make sense otherwise.
On line 11, you create an instance of the
Dash class. If you’ve used Flask before, then initializing a
Dash class may look familiar. In Flask, you usually initialize a WSGI application using
Flask(__name__). Similarly, for a Dash app, you use
Dash(__name__).
Defining the Layout of Your Dash Application
Next, you’ll define the
layout property of your application. This property dictates the look of your app. In this case, you’ll use a heading with a description below it and two graphs. Here’s how you define it:
13app.layout = html.Div( 14 children=[ 15 html.H1(children="Avocado Analytics",), 16 html.P( 17 children="Analyze the behavior of avocado prices" 18 " and the number of avocados sold in the US" 19 " between 2015 and 2018", 20 ), 21 dcc.Graph( 22 figure={ 23 "data": [ 24 { 25 "x": data["Date"], 26 "y": data["AveragePrice"], 27 "type": "lines", 28 }, 29 ], 30 "layout": {"title": "Average Price of Avocados"}, 31 }, 32 ), 33 dcc.Graph( 34 figure={ 35 "data": [ 36 { 37 "x": data["Date"], 38 "y": data["Total Volume"], 39 "type": "lines", 40 }, 41 ], 42 "layout": {"title": "Avocados Sold"}, 43 }, 44 ), 45 ] 46)
This code defines the
layout property of the
app object. This property determines the looks of your application using a tree structure made of Dash components.
Dash components come prepackaged in Python libraries. Some of them come with Dash when you install it. The rest you have to install separately. You’ll see two sets of components in almost every app:
- Dash HTML Components provides you with Python wrappers for HTML elements. For example, you could use this library to create elements such as paragraphs, headings, or lists.
- Dash Core Components provides you with Python abstractions for creating interactive user interfaces. You can use it to create interactive elements such as graphs, sliders, or dropdowns.
On lines 13 to 20, you can see the Dash HTML components in practice. You start by defining the parent component, an
html.Div. Then you add two more elements, a heading (
html.H1) and a paragraph (
html.P), as its children.
These components are equivalent to the
div,
h1, and
p HTML tags. You can use the components’ arguments to modify attributes or the content of the tags. For example, to specify what goes inside the
div tag, you use the
children argument in
html.Div.
There are also other arguments in the components, such as
style,
className, or
id, that refer to attributes of the HTML tags. You’ll see how to use some of these properties to style your dashboard in the next section.
The part of the layout shown on lines 13 to 20 will get transformed into the following HTML code:
<div> <h1>Avocado Analytics</h1> <p> Analyze the behavior of avocado prices and the number of avocados sold in the US between 2015 and 2018 </p> <!-- Rest of the app --> </div>
This HTML code is rendered when you open your application in the browser. It follows the same structure as your Python code, with a
div tag containing an
h1 and a
p element.
On lines 21 to 24 in the layout code snippet, you can see the graph component from Dash Core Components in practice. There are two
dcc.Graph components in the
app.layout. The first one plots the average prices of avocados during the period of study, and the second plots the number of avocados sold in the United States during the same period.
Under the hood, Dash uses Plotly.js to generate graphs. The
dcc.Graph components expect a figure object or a Python dictionary containing the plot’s data and layout. In this case, you provide the latter.
Finally, these two lines of code help you run your application:
48if __name__ == "__main__": 49 app.run_server(debug=True)
Lines 48 and 49 make it possible to run your Dash application locally using Flask’s built-in server. The
debug=True parameter from
app.run_server enables the hot-reloading option in your application. This means that when you make a change to your app, it reloads automatically, without you having to restart the server.
Finally, here’s the full version of
app.py. You can copy this code in the empty
app.py you created earlier.) app = dash.Dash(__name__) app.layout = html.Div( children=[ html.H1(children="Avocado Analytics",), html.P( children="Analyze the behavior of avocado prices" " and the number of avocados sold in the US" " between 2015 and 2018", ), dcc.Graph( figure={ "data": [ { "x": data["Date"], "y": data["AveragePrice"], "type": "lines", }, ], "layout": {"title": "Average Price of Avocados"}, }, ), dcc.Graph( figure={ "data": [ { "x": data["Date"], "y": data["Total Volume"], "type": "lines", }, ], "layout": {"title": "Avocados Sold"}, }, ), ] ) if __name__ == "__main__": app.run_server(debug=True)
This is the code for a bare-bones dashboard. It includes all the snippets of code you reviewed earlier in this section.
Now it’s time to run your application. Open a terminal inside your project’s root directory and in the project’s virtual environment. Run
python app.py, then go to using your preferred browser.
It’s ALIVE! Your dashboard should look like this:
The good news is that you now have a working version of your dashboard. The bad news is that there’s still some work to do before you can show this to others. The dashboard is far from visually pleasing, and you still need to add some interactivity to it.
But don’t worry—you’ll learn how to fix these issues in the next sections.
Style Your Dash Application
Dash provides you with a lot of flexibility to customize the look of your application. You can use your own CSS or JavaScript files, set a favicon (small icon shown on the web browser), and embed images, among other advanced options.
In this section, you’ll learn how to apply custom styles to components, and then you’ll style the dashboard you built in the previous section.
How to Apply a Custom Style to Your Components
You can style components in two ways:
- Using the
styleargument of individual components
- Providing an external CSS file
Using the
style argument to customize your dashboard is straightforward. This argument takes a Python dictionary with key-value pairs consisting of the names of CSS properties and the values you want to set.
Note: When specifying CSS properties in the
style argument, you should use mixedCase syntax instead of hyphen-separated words. For example, to change the background color of an element, you should use
backgroundColor and not
background-color.
If you wanted to change the size and color of the
H1 element in
app.py, then you could set the element’s
style argument as follows:
html.H1( children="Avocado Analytics", style={"fontSize": "48px", "color": "red"}, ),
Here, you provide to
style a dictionary with the properties and the values you want to set for them. In this case, the specified style is to have a red heading with a font size of 48 pixels.
The downside of using the
style argument is that it doesn’t scale well as your codebase grows. If your dashboard has multiple components that you want to look the same, then you’ll end up repeating a lot of your code. Instead, you can use a custom CSS file.
If you want to include your own local CSS or JavaScript files, then you need to create a folder called
assets/ in the root directory of your project and save the files you want to add there. By default, Dash automatically serves any file included in
assets/. This will also work for adding a favicon or embedding images, as you’ll see in a bit.
Then you can use the
className or
id arguments of the components to adjust their styles using CSS. These arguments correspond with the
class and
id attributes when they’re transformed into HTML tags.
If you wanted to adjust the font size and text color of the
H1 element in
app.py, then you could use the
className argument as follows:
html.H1( children="Avocado Analytics", className="header-title", ),
Setting the
className argument will define the class attribute for the
H1 element. You could then use a CSS file in the
assets folder to specify how you want it to look:
.header-title { font-size: 48px; color: red; }
You use a class selector to format the heading in your CSS file. This selector will adjust the heading format. You could also use it with other element that needs to share the format by setting
className="header-title".
Next, you’ll style your dashboard.
How to Improve the Looks of Your Dashboard
You just covered the basics of styling in Dash. Now, you’ll learn how to customize your dashboard’s looks. You’ll make these improvements:
- Add a favicon and title to the page
- Change the font family of your dashboard
- Use an external CSS file to style Dash components
You’ll start by learning how to use external assets in your application. That will allow you to add a favicon, a custom font family, and a CSS style sheet. Then you’ll learn how to use the
className argument to apply custom styles to your Dash components.
Adding External Assets to Your Application
Create a folder called
assets/ in your project’s root directory. Download a favicon from the Twemoji open source project and save it as
favicon.ico in
assets/. Finally, create a CSS file in
assets/ called
style.css and the code in the collapsible section below.
body { font-family: "Lato", sans-serif; margin: 0; background-color: #F7F7F7; } .header { background-color: #222222; height: 256px; display: flex; flex-direction: column; justify-content: center; } ); }
The
assets/ file contains the styles you’ll apply to components in your application’s layout. By now, your project structure should look like this:
avocado_analytics/ │ ├── assets/ │ ├── favicon.ico │ └── style.css │ ├── venv/ │ ├── app.py └── avocado.csv
Once you start the server, Dash will automatically serve the files located in
assets/. You include two files in
assets/:
favicon.ico and
style.css. For setting a default favicon, you don’t have to take any additional steps. For using the styles you defined in
style.css, you’ll need to use the
className argument in Dash components.
app.py requires a few changes. You’ll include an external style sheet, add a title to your dashboard, and style the components using the
style.css file. Review the changes below. Then, in the last part of this section, you’ll find the full code for your updated version of
app.py.
Here’s how you include an external style sheet and add a title to your dashboard:
11external_stylesheets = [ 12 { 13 "href": "?" 14 "family=Lato:wght@400;700&display=swap", 15 "rel": "stylesheet", 16 }, 17] 18app = dash.Dash(__name__, external_stylesheets=external_stylesheets) 19app.title = "Avocado Analytics: Understand Your Avocados!"
On lines 11 to 18, you specify an external CSS file, a font family, that you want to load in your application. External files are added to the
head tag of your application and loaded before the
body of your application loads. You use the
external_stylesheets argument for adding external CSS files or
external_scripts for external JavaScript files like Google Analytics.
On line 19, you set the title of your application. This is the text that appears in the title bar of your web browser, in Google’s search results, and in social media cards when you share your site.
Customizing the Styles of Components
To use the styles in
style.css, you’ll need to use the
className argument in Dash components. The code below adds a
className with a corresponding class selector to each of the components that compose the header of your dashboard:
21app.layout = html.Div( 22 children=[ 23 html.Div( 24 children=[ 25 html.P(children="🥑", className="header-emoji"), 26 html.H1( 27 children="Avocado Analytics", className="header-title" 28 ), 29 html.P( 30 children="Analyze the behavior of avocado prices" 31 " and the number of avocados sold in the US" 32 " between 2015 and 2018", 33 className="header-description", 34 ), 35 ], 36 className="header", 37 ),
On lines 21 to 37, you can see that there have been two changes to initial version of the dashboard:
- There’s a new paragraph element with an avocado emoji that will serve as logo.
- There’s a
classNameargument in each component. These class names should match a class selector in
style.css, which will define the looks of each component.
For example, the
header-description class assigned to the paragraph component starting with
"Analyze the behavior of avocado prices" has a corresponding selector in
style.css:
29.header-description { 30 color: #CFCFCF; 31 margin: 4px auto; 32 text-align: center; 33 max-width: 384px; 34}
Lines 29 to 34 of
style.css define the format for the
header-description class selector. These will change the color, margin, alignment, and maximum width of any component with
className="header-description". All the components have corresponding class selectors in the CSS file.
The other significant change is in the graphs. Here’s the new code for the price chart:
38html.Div( 39 children=[ 40 html.Div( 41 children=dcc.Graph( 42 id="price-chart", 43 config={"displayModeBar": False}, 44 figure={ 45 "data": [ 46 { 47 "x": data["Date"], 48 "y": data["AveragePrice"], 49 "type": "lines", 50 "hovertemplate": "$%{y:.2f}" 51 "<extra></extra>", 52 }, 53 ], 54 "layout": { 55 "title": { 56 "text": "Average Price of Avocados", 57 "x": 0.05, 58 "xanchor": "left", 59 }, 60 "xaxis": {"fixedrange": True}, 61 "yaxis": { 62 "tickprefix": "$", 63 "fixedrange": True, 64 }, 65 "colorway": ["#17B897"], 66 }, 67 }, 68 ), 69 className="card", 70 ),
In this code, you define a
className and a few customizations for the
config and
figure parameters of your chart. Here are the changes:
- Line 43: You remove the floating bar that Plotly shows by default.
- Lines 50 and 51: You set the hover template so that when users hover over a data point, it shows the price in dollars. Instead of
2.5, it’ll show as
$2.5.
- Lines 54 to 66: You adjust the axis, the color of the figure, and the title format in the layout section of the graph.
- Line 69: You wrap the graph in an
html.Divwith a
"card"class. This will give the graph a white background and add a small shadow below it.
There are similar adjustments to the sales and volume charts. You can see those in the full code for the updated
app.py in the collapsible section below.=dcc.Graph( id="price-chart", config={"displayModeBar": False}, figure={ "data": [ { "x": data["Date"], "y": data["AveragePrice"], "type": "lines", "hovertemplate": "$%{y:.2f}" "<extra></extra>", }, ], "layout": { "title": { "text": "Average Price of Avocados", "x": 0.05, "xanchor": "left", }, "xaxis": {"fixedrange": True}, "yaxis": { "tickprefix": "$", "fixedrange": True, }, "colorway": ["#17B897"], }, }, ), className="card", ), html.Div( children=dcc.Graph( id="volume-chart", config={"displayModeBar": False}, figure={ "data": [ { "x": data["Date"], "y": data["Total Volume"], "type": "lines", }, ], "layout": { "title": { "text": "Avocados Sold", "x": 0.05, "xanchor": "left", }, "xaxis": {"fixedrange": True}, "yaxis": {"fixedrange": True}, "colorway": ["#E12D39"], }, }, ), className="card", ), ], className="wrapper", ), ] ) if __name__ == "__main__": app.run_server(debug=True)
This is the updated version of
app.py. It has the required changes in the code to add a favicon and a page title, update the font family, and use an external CSS file. After these changes, your dashboard should look like this:
In the next section, you’ll learn how to add interactive components to your dashboard.
Add Interactivity to Your Dash Apps Using Callbacks
In this section, you’ll learn how to add interactive elements to your dashboard.
Dash’s interactivity is based on a reactive programming paradigm. This means that you can link components with elements of your app that you want to update. If a user interacts with an input component like a dropdown or a range slider, then the output, such as a graph, will react automatically to the changes in the input.
Now let’s make your dashboard interactive. This new version of your dashboard will allow the user to interact with the following filters:
- Region
- Type of avocado
- Date range
Start by replacing your local
app.py with the new version in the collapsible section below.
import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd import numpy as np from dash.dependencies import Output, Input data = pd.read_csv("avocado.csv")=[ html.Div(children="Region", className="menu-title"), dcc.Dropdown( id="region-filter", options=[ {"label": region, "value": region} for region in np.sort(data.region.unique()) ], value="Albany", clearable=False, className="dropdown", ), ] ), html.Div( children=[ html.Div(children="Type", className="menu-title"), dcc.Dropdown( id="type-filter", options=[ {"label": avocado_type, "value": avocado_type} for avocado_type in data.type.unique() ], value="organic", clearable=False, searchable=False, className="dropdown", ), ], ), html.Div( children=[ html.Div( children="Date Range", className="menu-title" ), dcc.DatePickerRange( id="date-range", min_date_allowed=data.Date.min().date(), max_date_allowed=data.Date.max().date(), start_date=data.Date.min().date(), end_date=data.Date.max().date(), ), ] ), ], className="menu", ), html.Div( children=[ html.Div( children=dcc.Graph( id="price-chart", config={"displayModeBar": False}, ), className="card", ), html.Div( children=dcc.Graph( id="volume-chart", config={"displayModeBar": False}, ), className="card", ), ], className="wrapper", ), ] ) @app.callback( [Output("price-chart", "figure"), Output("volume-chart", "figure")], [ Input("region-filter", "value"), Input("type-filter", "value"), Input("date-range", "start_date"), Input("date-range", "end_date"), ], ) def update_charts(region, avocado_type, start_date, end_date): mask = ( (data.region == region) & (data.type == avocado_type) & (data.Date >= start_date) & (data.Date <= end_date) ) filtered_data = data.loc[mask, :] price_chart_figure = { "data": [ { "x": filtered_data["Date"], "y": filtered_data["AveragePrice"], "type": "lines", "hovertemplate": "$%{y:.2f}<extra></extra>", }, ], "layout": { "title": { "text": "Average Price of Avocados", "x": 0.05, "xanchor": "left", }, "xaxis": {"fixedrange": True}, "yaxis": {"tickprefix": "$", "fixedrange": True}, "colorway": ["#17B897"], }, } volume_chart_figure = { "data": [ { "x": filtered_data["Date"], "y": filtered_data["Total Volume"], "type": "lines", }, ], "layout": { "title": {"text": "Avocados Sold", "x": 0.05, "xanchor": "left"}, "xaxis": {"fixedrange": True}, "yaxis": {"fixedrange": True}, "colorway": ["#E12D39"], }, } return price_chart_figure, volume_chart_figure if __name__ == "__main__": app.run_server(debug=True)
Next, replace
style.css with the code in the collapsible section below.
body { font-family: "Lato", sans-serif; margin: 0; background-color: #F7F7F7; } .header { background-color: #222222; height: 288px; padding: 16px 0 0 0; } ); } .menu { height: 112px; width: 912px; display: flex; justify-content: space-evenly; padding-top: 24px; margin: -80px auto 0 auto; background-color: #FFFFFF; box-shadow: 0 4px 6px 0 rgba(0, 0, 0, 0.18); } .Select-control { width: 256px; height: 48px; } .Select--single > .Select-control .Select-value, .Select-placeholder { line-height: 48px; } .Select--multi .Select-value-label { line-height: 32px; } .menu-title { margin-bottom: 6px; font-weight: bold; color: #079A82; }
Now you’re ready to start adding interactive components to your application!
How to Create Interactive Components
First, you’ll learn how to create components that users can interact with. For that, you’ll include a new
html.Div above your charts. It’ll include two dropdowns and a date range selector that the user can use to filter the data and update the graphs.
Here’s how that looks in
app.py:
24html.Div( 25 children=[ 26 html.Div( 27 children=[ 28 html.Div(children="Region", className="menu-title"), 29 dcc.Dropdown( 30 id="region-filter", 31 options=[ 32 {"label": region, "value": region} 33 for region in np.sort(data.region.unique()) 34 ], 35 value="Albany", 36 clearable=False, 37 className="dropdown", 38 ), 39 ] 40 ), 41 html.Div( 42 children=[ 43 html.Div(children="Type", className="menu-title"), 44 dcc.Dropdown( 45 id="type-filter", 46 options=[ 47 {"label": avocado_type, "value": avocado_type} 48 for avocado_type in data.type.unique() 49 ], 50 value="organic", 51 clearable=False, 52 searchable=False, 53 className="dropdown", 54 ), 55 ], 56 ), 57 html.Div( 58 children=[ 59 html.Div( 60 children="Date Range", 61 className="menu-title" 62 ), 63 dcc.DatePickerRange( 64 id="date-range", 65 min_date_allowed=data.Date.min().date(), 66 max_date_allowed=data.Date.max().date(), 67 start_date=data.Date.min().date(), 68 end_date=data.Date.max().date(), 69 ), 70 ] 71 ), 72 ], 73 className="menu", 74),
On lines 24 to 74, you define an
html.Div on top of your graphs consisting of two dropdowns and a date range selector. It will serve as a menu that the user will use to interact with the data:
The first component in the menu is the Region dropdown. Here’s the code for that component:
41html.Div( 42 children=[ 43 html.Div(children="Region", className="menu-title"), 44 dcc.Dropdown( 45 id="region-filter", 46 options=[ 47 {"label": region, "value": region} 48 for region in np.sort(data.region.unique()) 49 ], 50 value="Albany", 51 clearable=False, 52 className="dropdown", 53 ), 54 ] 55),
On lines 41 to 55, you define the dropdown that users will use to filter the data by region. In addition to the title, it has a
dcc.Dropdown component. Here’s what each of the parameters means:
idis the identifier of this element.
optionsis the options shown when the dropdown is selected. It expects a dictionary with labels and values.
valueis the default value when the page loads.
clearableallows the user to leave this field empty if set to
True.
classNameis a class selector used for applying styles.
The Type and Date Range selectors follow the same structure as the Region dropdown. Feel free to review them on your own.
Next, take a look at the
dcc.Graphs components:
90html.Div( 91 children=[ 92 html.Div( 93 children=dcc.Graph( 94 id="price-chart", config={"displayModeBar": False}, 95 ), 96 className="card", 97 ), 98 html.Div( 99 children=dcc.Graph( 100 id="volume-chart", config={"displayModeBar": False}, 101 ), 102 className="card", 103 ), 104 ], 105 className="wrapper", 106),
On lines 90 to 106, you define the
dcc.Graph components. You may have noticed that, compared to the previous version of the dashboard, the components are missing the
figure argument. That’s because the
figure argument will now be generated by a callback function using the inputs the user sets using the Region, Type, and Date Range selectors.
How to Define Callbacks
You’ve defined how the user will interact with your application. Now you need to make your application react to user interactions. For that, you’ll use callback functions.
Dash’s callback functions are regular Python functions with an
app.callback decorator. In Dash, when an input changes, a callback function is triggered. The function performs some predetermined operations, like filtering a dataset, and returns an output to the application. In essence, callbacks link inputs and outputs in your app.
Here’s the callback function used for updating the graphs:
111@app.callback( 112 [Output("price-chart", "figure"), Output("volume-chart", "figure")], 113 [ 114 Input("region-filter", "value"), 115 Input("type-filter", "value"), 116 Input("date-range", "start_date"), 117 Input("date-range", "end_date"), 118 ], 119) 120def update_charts(region, avocado_type, start_date, end_date): 121 mask = ( 122 (data.region == region) 123 & (data.type == avocado_type) 124 & (data.Date >= start_date) 125 & (data.Date <= end_date) 126 ) 127 filtered_data = data.loc[mask, :] 128 price_chart_figure = { 129 "data": [ 130 { 131 "x": filtered_data["Date"], 132 "y": filtered_data["AveragePrice"], 133 "type": "lines", 134 "hovertemplate": "$%{y:.2f}<extra></extra>", 135 }, 136 ], 137 "layout": { 138 "title": { 139 "text": "Average Price of Avocados", 140 "x": 0.05, 141 "xanchor": "left", 142 }, 143 "xaxis": {"fixedrange": True}, 144 "yaxis": {"tickprefix": "$", "fixedrange": True}, 145 "colorway": ["#17B897"], 146 }, 147 } 148 149 volume_chart_figure = { 150 "data": [ 151 { 152 "x": filtered_data["Date"], 153 "y": filtered_data["Total Volume"], 154 "type": "lines", 155 }, 156 ], 157 "layout": { 158 "title": { 159 "text": "Avocados Sold", 160 "x": 0.05, 161 "xanchor": "left" 162 }, 163 "xaxis": {"fixedrange": True}, 164 "yaxis": {"fixedrange": True}, 165 "colorway": ["#E12D39"], 166 }, 167 } 168 return price_chart_figure, volume_chart_figure
On lines 111 to 119, you define the inputs and outputs inside the
app.callback decorator.
First, you define the outputs using
Output objects. These objects take two arguments:
- The identifier of the element that they’ll modify when the function executes
- The property of the element to be modified
For example,
Output("price-chart", "figure") will update the
figure property of the
"price-chart" element.
Then you define the inputs using
Input objects. They also take two arguments:
- The identifier of the element they’ll be watching for changes
- The property of the watched element that they should take when a change happens
So,
Input("region-filter", "value") will watch the
"region-filter" element for changes and will take its
value property if the element changes.
Note: The
Input object discussed here is imported from
dash.dependencies. Be careful not to confuse it with the component coming from
dash_core_components. These objects are not interchangeable and have different purposes.
On line 120, you define the function that will be applied when an input changes. One thing to notice here is that the arguments of the function will correspond with the order of the
Input objects supplied to the callback. There’s no explicit relationship between the names of the arguments in the function and the values specified in the Input objects.
Finally, on lines 121 to 164, you define the body of the function. In this case, the function takes the inputs (region, type of avocado, and date range), filters the data, and generates the figure objects for the price and volume charts.
That’s all! If you’ve followed along to this point, then your dashboard should look like this:
Way to go! That’s the final version of your dashboard. In addition to making it look beautiful, you also made it interactive. The only missing step is making it public so you can share it with others.
Deploy Your Dash Application to Heroku
You’re done building your application, and you have a beautiful, fully interactive dashboard. Now you’ll learn how to deploy it.
Dash apps are Flask apps, so both share the same deployment options. In this section, you’ll deploy your app on Heroku.
Before you get started, make sure you’ve installed the Heroku command-line interface (CLI) and Git. You can verify that both exist in your system by running these commands at a command prompt (Windows) or at a terminal (macOS, Linux):
$ git --version git version 2.21.1 (Apple Git-122.3) $ heroku --version heroku/7.42.2 darwin-x64 node-v12.16.2
The output may change a bit depending on your operating system and the version you have installed, but you shouldn’t get an error.
Let’s get to it!
First, there’s a small change you need to make in
app.py. After you initialize the app on line 18, add a new variable called
server:
18app = dash.Dash(__name__, external_stylesheets=external_stylesheets) 19server = app.server
This addition is necessary to run your app using a WSGI server. It’s not advisable to use Flask’s built-in server in production since it won’t able to handle much traffic.
Next, in the project’s root directory, create a file called
runtime.txt where you’ll specify a Python version for your Heroku app:
python-3.8.6
When you deploy your app, Heroku will automatically detect that it’s a Python application and will use the correct
buildpack. If you also provide a
runtime.txt, then it’ll pin down the Python version that your app will use.
Next, create a
requirements.txt file in the project’s root directory where you’ll copy the libraries required to set up your Dash application on a web server:
dash==1.13.3 pandas==1.0.5 gunicorn==20.0.4
You may have noticed that there’s a package in
requirements.txt you haven’t seen until now:
gunicorn. Gunicorn is a WSGI HTTP server that is frequently used for deploying Flask apps to production. You’ll use it to deploy your dashboard.
Now create a file named
Procfile with the following content:
web: gunicorn app:server
This file tells the Heroku app what commands should be executed to start your app. In this case, it starts a
gunicorn server for your dashboard.
Next, you’ll need to initialize a Git repository. To do that, go to your project’s root directory and execute the following command:
$ git init
This will start a
Git repository in
avocado_analytics/. It’ll start tracking all the changes you make to the files in that directory.
However, there are files you don’t want to track using Git. For example, you usually want to remove Python compiled files, the contents of your virtual environment folder, or metadata files such as
.DS_Store.
To avoid tracking unnecessary files, create a file called
.gitignore in the root directory. Then copy the following content in it:
venv *.pyc .DS_Store # Only if you are using macOS
This will make sure your repository doesn’t track unnecessary files. Now commit your project files:
$ git add . $ git commit -m 'Add dashboard files'
Before the final step, make sure you have everything in place. Your project’s structure should look like this:
avocado_analytics/ │ ├── assets/ │ ├── favicon.ico │ └── style.css │ ├── venv/ │ ├── app.py ├── avocado.csv ├── Procfile ├── requirements.txt └── runtime.txt
Finally, you need to create an app in Heroku, push your code there using Git, and start the app in one of Heroku’s free server options. You can do that by running the following commands:
$ heroku create APP-NAME # Choose a name for your app $ git push heroku master $ heroku ps:scale web=1
The first command will create a new application on Heroku and an associated Git repository. The second will push the changes to that repository, and the third will start your app in one of Heroku’s free server options.
That’s it! You’ve built and deployed your dashboard. Now you just need to access it to share it with your friends. To access your app, copy in your browser and replace
APP-NAME with the name you defined in the previous step.
If you’re curious, take a look at a sample app.
Conclusion
Congratulations! You just built, customized, and deployed your first dashboard using Dash. You went from a bare-bones dashboard to a fully interactive one deployed on Heroku.
With this knowledge, you can use Dash to build analytical applications to share with others. As more companies put more weight on the use of data, knowing how to use Dash will increase the impact you have in your workplace. What used to be a task only experts could perform, you can now do in an afternoon.
In this tutorial, you’ve learned:
- How to create a dashboard using Dash
- How to customize the styling of your Dash application
- How to make your app interactive by using Dash components
- What callbacks are and how you can use them to create interactive applications
- How to deploy your application on Heroku
Now you’re ready to develop new Dash applications. Find a dataset, think of some exciting visualizations, and build another dashboard!
You can download the source code, data, and resources for the sample applications you made in this tutorial by clicking the link below:
Get the Source Code: Click here to get the source code you’ll use to learn about creating data visualization interfaces in Python with Dash in this tutorial. | https://realpython.com/python-dash/ | CC-MAIN-2021-17 | refinedweb | 6,511 | 57.47 |
Abstract
The article exposes the procedure of how to programmatically change parameters for a generic RTSP resource. Manual invocation of API calls is being discovered in step by step manner in order to make possible the procedure be automated by a script.
The API methods used below can modify the most basic structure of the resource, which makes use of these methods dangerous. These methods have to be used carefully.
Back your databases up before proceeding with activities described hereafter.
Identifying your resource
1.1. Log in to your System with Nx Witness.
1.2. In the resource tree select the RTSP resource of your interest.
1.3. Right-click on the camera, select “Camera Settings...”
1.4. Copy camera ID from the “Camera ID” field on the “Advanced” tab into a text file.
Getting the list of parameters
Log in with a web browser to your server which the camera is connected to.
http://<your server address>:<port>
For example:
Select the “For Developers” menu item. Then click the link “API Testing Tool (new)”
In the search field type “getResourceParams”
Click the link “getResourceParams” appeared in the method tree below.
On the page appears
- in the “id” field type the ID you got in the step 1.4;
- click “Test method” button;
- copy content of the “Response” field to the text editor of your choice.
Pay your attention, the opening square bracket in the beginning of the “Response” field means the method returns an array of json objects.
Find the “streamUrl” string. The json object for the parameters has to be similar to the following:
{
"name": "streamUrls",
"resourceId": "{c6c4978e-01a8-92d0-a330-d2833596f6bd}",
"value": "{\n \"1\": \"rtsp://192.168.0.64:554/ISAPI/Streaming/channels/103\",\n \"2\": \"rtsp://192.168.0.64:554/ISAPI/Streaming/channels/104\",\n \"3\": \"rtsp://192.168.0.64:554/ISAPI/Streaming/channels/105\"\n}\n"
}
The “value” is a serialized json object.
Changing resource parameters
Ir order to change resource parameters the setResouceParams API method should be used. Note, this method is not documented in version 3.2 and below.
Parameters has to be passed as a JSON object in POST message body with content type "application/json".
This is a System API method. The /ec2/ string has to be put in the URL
http://<your_server_address>:<port>/ec2/setResouceParams
Let’s consider an example to demonstrate how this method works.
If we want to set URLs of two streams for the generic RTSP resource, we have to change the streamUrls parameter of the resource. As it was shown above we have to construct json object of the following structure:
{
"name": "streamUrls",
"resourceId": "{c6c4978e-01a8-92d0-a330-d2833596f6bd}",
"value": ""
}
Here is the structure of “value”:
"value": {
"2": "rtsp://192.168.0.64:554/ISAPI/Streaming/channels/102"
}
That means the stream number 2 of the resource with resourceId will have the value assigned rtsp://192.168.0.64:554/ISAPI/Streaming/channels/102
If you want to change several streams at once you have to enumerate all of them in the “value” object. Here is the example for our case:
"value": {
"1": "rtsp://192.168.0.64:554/ISAPI/Streaming/channels/110",
"2": "rtsp://192.168.0.64:554/ISAPI/Streaming/channels/102"
}
Note: The “value” object has to be serialized before passing to the setResouceParams method.
Now the object of streamUrls parameter has to be put to the json array before passing to setResouceParams method. The final view of the structure to be passed looks like this:
[
{
"name": "streamUrls",
"resourceId": "{c6c4978e-01a8-92d0-a330-d2833596f6bd}",
"value": {
"1": "rtsp://192.168.0.64:554/ISAPI/Streaming/channels/110",
"2": "rtsp://192.168.0.64:554/ISAPI/Streaming/channels/102"
}
]
Here the example code in python for our case:
import requests
import json
# constructing the json array with one object for the streamUrls parameter to be changed.
payload = [
# constructing the object for streamUrls parameter
dict(
# the ID of the resource got in the step 1.4
resourceId = '{c6c4978e-01a8-92d0-a330-d2833596f6bd}',
name = 'streamUrls',
# constructing value object
# the json.dumps - serializes the object to the string
value = json.dumps({
"1": "rtsp://192.168.0.64:554/ISAPI/Streaming/channels/110",
"2": "rtsp://192.168.0.64:554/ISAPI/Streaming/channels/102"
})
]
nx_method = 'setResourceParams'
request_url = server_url+nx_method
res = requests.post(
request_url,
auth=(username,password),
json=payload
)
res = res.json()
print(res)
Related articles:
Adding a camera or a RTSP stream using API
Questions
If you have any questions related to this topic or you want to share your experience with other community members or our team, please visit and engage in our support community or reach out to your local reseller.
Article is closed for comments. | https://support.networkoptix.com/hc/en-us/articles/360026019253-Changing-resource-attributes-using-API | CC-MAIN-2021-17 | refinedweb | 781 | 57.67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.