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 |
|---|---|---|---|---|---|
Working with the Amazon Maps API on the Kindle Fire
<google>BUY_KINDLE_FIRE</google>
One can argue with a reasonable degree of certainty that Google has created one of the best and most accurate digital map services available on the market today. In the early versions of iOS, Apple made the wise decision to rely on Google Maps for navigation on the iPhone. Rather than continue to use Google Maps, however, Apple instead invested a considerable amount of effort in developing a replacement to Google Maps in iOS 6. The result was an unreliable service that became a public relations problem for Apple and resulted in the departure of a number of senior Apple executives.
When a mobile device manufacturer chooses to use Android as the operating system for a new device, Google Maps comes bundled as part of the overall package. The typical Android based phone or tablet, therefore, includes a Google Maps application and provides access to the Google Maps API for use by app developers. This, however, is not the case for the Kindle Fire. Amazon has, instead, removed Google Maps from both the operating system and the SDK, and replaced it with the Amazon Maps system.
This aversion to using the Google Maps system on the part of Apple and Amazon is not entirely irrational. Consider, for example, that the provider of the map service on a mobile device gets to learn a great deal of information about a user. Each time a user accesses the map system, the provider finds out not only where the user is, but also where they might be going. Understandably, neither Apple nor Amazon were comfortable letting Google (in many ways a competitor) have this level of information about their customers.
This chapter is intended to provide an overview of the Amazon Maps system and API. Once the basics have been covered, the following chapters will work through some tutorials demonstrating the use of this API.
Amazon Maps vs. Google Maps
When Amazon took the decision not to use Google Maps on the Kindle Fire it became evident that this might present a problem for the large number of existing Android applications that would potentially need to be migrated to the Kindle Fire. In recognition of this fact, the Amazon Maps API largely mirrors that of Google Maps. Most existing Google Maps code will, therefore, migrate over to Amazon Maps without requiring a significant amount of work.
One key issue, however, is that Amazon Maps lacks some of the main features of Google Maps, street views and traffic information being two notable examples. Whilst the Amazon Maps API includes these API features so that existing code will compile, they do nothing when called by the application.
The Elements of Amazon Maps
The Amazon Maps API consists of a core set of classes that combine to provide mapping capabilities in Android applications on the Kindle Fire. The key classes are:
- MapActivity – A subclass of the Android Activity class, this provides the base class for activities that need to provide map support. Any activity that needs to work with maps must be derived from this class.
- MapView - Provides the canvas onto which the map is drawn.
- MapController – Provides an interface for managing an existing map. This class includes capabilities such as setting both the center coordinates of the map and the current zoom level.
- ItemizedOverlay – A class specifically designed to overlay information onto a map. For example, an overlay might be used to mark all the locations of the public libraries in a town. A single overlay can contain multiple items, each represented by an OverlayItem instance. An onTap() callback method may be implemented to pop up additional information about a location when tapped by the user.
- OverlayItem – Used to represent each item in an ItemizedOverlay. Each item has associated with it a location on the map and an optional image to mark the location.
- MyLocationOverlay – A special-purpose overlay designed specifically to display the current location of the device on the map view.
- Overlay – A general-purpose overlay class provided primarily to allow transparent effects or content to be placed on top of the map.
Getting Ready to Use Amazon Maps
The use of Amazon Maps in an application is somewhat unusual since there is more work involved in setting up the environment than there is in actually writing the Java code. Each step must be performed carefully to ensure that maps will function within an application.
Downloading the Amazon Mobile SDK
Amazon Maps are part of the Amazon Mobile SDK, which will need to be downloaded and integrated into any Eclipse project for which maps are to be included. The SDK can be downloaded using the following link:
Once downloaded, unzip the archive into a suitable location.
Adding the Amazon Mobile SDK to an Eclipse Project
The Maps SDK JAR file will need to be added to the build path of any application that requires map functionality. To add map support to a project, locate it <sdk path> is replaced by the location on your file system where the Amazon Mobile SDK was installed in the previous step):
as illustrated in Figure 40-1:
Figure 40-1
Assuming the JAR file is now listed, click on OK to close the Properties dialog.
Obtaining Your Developer Signature
Before an application can make use of the Amazon Maps API, it must first be registered in the Amazon Mobile App Distribution portal. Before an app can be registered, however, the developer signature (also referred to as the MD5 debug fingerprint) associated with your development environment must be obtained. This is achieved by running the keytool utility that is supplied in the bin directory of the Java Development Kit (JDK) installed on the development system as outlined in Setting up a Kindle Fire Android Development Environment. One of the arguments passed to the keytool utility is the path to a file named debug.keystore. To find the location of this file, select the Eclipse Windows -> Preferences menu option and in the resulting dialog select Android -> Build from the left hand panel. In the Build Settings panel, the location of the file can be found in the Default debug keystore: field. Once the location has been identified, execute the following command within a terminal or command prompt window (where <key path> is replaced by the path to the debug.keystore file):
keytool -v -list -alias androiddebugkey -keystore <key path> -storepass android
Upon execution, the above command will generate output similar to the following example:
Alias name: androiddebugkey Creation date: Nov 30, 2011 Entry type: PrivateKeyEntry Certificate chain length: 1 Certificate[1]: Owner: CN=Android Debug, O=Android, C=US Issuer: CN=Android Debug, O=Android, C=US Serial number: 503f6f0b Valid from: Wed Nov 30 13:26:24 EST 2011 until: Fri Nov 22 13:26:24 EST 2041 Certificate fingerprints: MD5: DF:86:AB:19:DC:28:BF:62:4C:49:82:6E:BA:77:45:B4 SHA1: 6F:AD:25:3F:90:56:6C:9B:7D:29:95:54:AF:E3:E0:29:64:DB:BD:22 SHA256: B8:3B:C7:43:4A:0A:77:E6:38:E1:66:18:E4:FF:EE:AA:55:66:88:99:F6: 6B:16:11:4D:E9:DA:DD:4E:0F:D0:B8 Signature algorithm name: SHA256withRSA Version: 3
The MD5 fingerprint is the sequence of hexadecimal number pairs on the MD5: line of the output.
Registering the Application in the Amazon Mobile App Distribution Portal
The next step is to register the application in the Amazon distribution portal and input the MD5 debug fingerprint to enable Map support. To achieve this, open a web browser and navigate to the following URL:
On the welcome page, click on the Sign In link in the top right hand corner of the page and enter your login credentials. If you do not yet have a developer account, click on the Create an Account button to create one now.
Once logged in, click on the Add a New App button located within the dashboard panel as shown in Figure 40-2:
Figure 40-2 and then cut and paste the MD5 fingerprint into the Developer Signature field before clicking on the Submit button.
At this point, the development environment is set up to enable Maps to be used within a specific application. The next step is to set up the application itself to use maps. This begins with making some additions to the application’s Android manifest file.
Adding Map Support to the AndroidManifest.xml File
Before maps can be used in an application, an additional entry needs to be added to the application’s Android Manifest file. Within Eclipse, locate the manifest file for the project for which the Maps JAR file was added to the build path and load the AndroidManifest.xml file into the editing panel. The line that needs to be added reads as follows:
xmlns:amazon=""
This directive needs to be added as part of the existing <manifest> element. For example:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns: . .
In addition, the Amazon Maps API requires that a number of permissions be requested within the manifest file:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns: <uses-permission android: <uses-permission android: <uses-permission android: . .
Finally, the application element of the Manifest file must include the following tag:
<amazon:enable-feature android:
For example:
. . . <application android: <amazon:enable-feature android: <activity android: . . .
Enabling Location Based Services on the Kindle Fire Device
By default, Kindle Fire devices are shipped with location based services disabled. Before testing a map-based application on a physical device, therefore, this feature must first be enabled. To do this, display the settings app on the device (via a downward swipe from the top edge of the screen). Select the More option followed by Location Based Services. Within the location settings screen (Figure 40 3) change the Enable location-based Services setting from Off to On.
Figure 40-3
Registering an Emulator
When using an AVD Kindle Fire emulator to test maps within an application, that emulator must be registered with Amazon. An attempt to access maps on an unregistered emulator will result in the application crashing. To register an emulator, start it running and display the settings app (on an emulator this is displayed by clicking at the top of the device display and dragging the mouse to the bottom of the screen). Select More followed by My Account.
On the My Account screen, click on the Register button and enter the login and password details associated with your Amazon.com account. Once the information has been entered, click on Register and wait for the process to complete. The emulator should now support use of the Amazon Maps API.
Adjusting the Emulator Location Settings
When testing an application in the emulator, the location will be set using IP information from the internet connection of the computer system on which the emulator is running. Different locations can be simulated using the Debug Perspective within Eclipse. This can be displayed by selecting the Window -> Show Perspective -> DDMS option. When the DDMS perspective appears, select the Emulator Control tab in the main panel. At the bottom of the panel is a section named Location Controls where new Longitude and Latitude values may be entered.
Having covered the steps involved in enabling maps support in Kindle Fire applications, the remainder of this chapter will provide an overview of how map functionality may be implemented within an application.
Checking for Map Support
All Kindle Fire devices with the exception of the first generation Kindle Fire support the Amazon maps runtime library. This means that any application that intends to use the Maps API must check whether the device on which it is running supports the maps feature before attempting to make any Maps API calls. The recommended way to perform this task is to check for the presence or otherwise of the maps runtime. The following method can be included in applications and subsequently called to check whether maps are supported:
public boolean hasMapSupport() { boolean result = false; try { Class.forName( "com.amazon.geo.maps.MapView" ); result = true ; } catch (Exception e) {} return result; }
When called, the method will return a true value if maps are supported on the device and false if not.
Understanding Geocoding and Reverse Geocoding
It is impossible to talk about maps and geographical locations without first covering the subject of Geocoding. Geocoding can best be described as the process of converting a textual based geographical location (such as a street address) into geographical coordinates expressed in terms of longitude and latitude.
Geocoding can be achieved using the Android Geocoder class. An instance of the Geocoder class can, for example, be passed a string representing a location such as a city name, street address or airport code. The Geocoder will attempt to find a match for the location and return a list of Address objects that potentially match the location string, ranked in order with the closest match at position 0 in the list. A variety of information can then be extracted from the Address objects, including the longitude and latitude of the potential matches.
The following code, for example, requests the location of the National Air and Space Museum in Washington, D.C.:
double latitude; double longitude; List<Address> geocodeMatches = null; geocodeMatches = new Geocoder(this).getFromLocationName("600 Independence Ave SW, Washington, DC 20560", 1); if (!geocodeMatches.isEmpty()) { latitude = geocodeMatches.get(0).getLatitude(); longitude = geocodeMatches.get(0).getLongitude(); }
Note that the value of 1 is passed through as the second argument to the getFromLocationName() method. This simply tells the Geocoder to return only one result in the array. Given the specific nature of the address provided, there should only be one potential match. For more vague location names, however, it may be necessary to request more potential matches and allow the user to choose the correct one. The above code is an example of forward-geocoding in that coordinates are calculating based on a text location description. Reverse-geocoding, as the name suggests, involves the translation of geographical coordinates into a human readable address string. Consider, for example, the following code:
List<Address> geocodeMatches = null; String Address1; String Address2; String State; String Zipcode; String Country; geocodeMatches = new Geocoder(this).getFromLocation(38.8874245, -77.0200729, 1); if (!geocodeMatches.isEmpty()) { Address1 = geocodeMatches.get(0).getAddressLine(0); Address2 = geocodeMatches.get(0).getAddressLine(1); State = geocodeMatches.get(0).getAdminArea(); Zipcode = geocodeMatches.get(0).getPostalCode(); Country = geocodeMatches.get(0).getCountryName(); }
In this case the Geocoder object is initialized with latitude and longitude values via the getFromLocation() method. Once again, only a single matching result is requested. The text based address information is then extracted from the resulting Address object. It should be noted that the geocoding is not actually performed on the Kindle Fire device, but rather on a server to which the device connects when a translation is required and the results subsequently returned when the translation is complete. As such, geocoding can only take place when the Kindle Fire has an active internet connection.
Adding a MapView to an Application
The simplest way to add a MapView to the application is to specify it in the user interface layout XML file for an activity. The following example layout file shows a MapView instance added as the child of a RelativeLayout view:
<RelativeLayout xmlns: <com.amazon.geo.maps.MapView android: </RelativeLayout>
Next, the activity with which the layout file is associated must be derived from the MapActivity class, instead of the Activity class. Failure to follow this rule will result in the application crashing when the map is invoked. The following code, for example, shows the activity implementation for the above layout:
public class MapViewActivity extends MapActivity { private static MapView mapView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map_view); mapView = (MapView) findViewById(R.id.mapview); } . . }
When executed, the above code would create and display a map, which, by default, will show the entire world. The user will be able to interact with the map, panning using swipes and zooming in and out using pinch gestures. In addition, a set of built-in zoom controls can be enabled on the map view via a call to the setBuiltInZoomControls() method of the MapView object:
mapView.setBuiltInZoomControls(true);
Once enabled, the controls will appear for a brief period of time when the map first appears. Subsequent taps on the map view will re-display the controls for a limited time before they again recede from view.
Customizing a Map View using the MapController
Each MapView instance has associated with it a MapController object. A reference to this controller can be obtained via a call to the getController() method of the corresponding MapView instance. Once this reference has been obtained, a variety of methods may be called on the controller to perform tasks such as setting the zoom level and center point of the map, animating zoom effects and scrolling by specified numbers of pixels.
The following code sets the zoom level (which must be an integer between 1 and 21 inclusive) to 18 before setting the center of the map view to a specific set of coordinates:
MapControler mapController = mapView.getController(); GeoPoint newLocation = new GeoPoint((int)(address.getLatitude() * 1E6), (int)(address.getLongitude() *1E6)); mapController.setZoom(18); mapController.setCenter(newLocation);
When setting the center of the map, the location needs to be provided in the form of a GeoPoint object which can be created by specifying the longitude and latitude as microdegrees (equivalent to degrees * 1E6).
Displaying the User’s Current Location
The user’s current location can be marked on the map view by making use of the MyLocationOverlay class. This is achieved by enabling access to the user’s current location, getting a list of the current overlays assigned to the map view, creating a new MyLocationOverlay object and adding it to the overlay list.
If the map is not currently displaying an area that includes the user’s current location, the location marker will not be visible on the map. The center of the map, however, can be changed to match the current location as demonstrated in the following code fragment:
myLocationOverlay = new MyLocationOverlay(this, mapView); mapView.getOverlays().add(myLocationOverlay); myLocationOverlay.enableMyLocation(); GeoPoint myLocation = myLocationOverlay.getMyLocation(); mapController.setCenter(myLocation); mapController.setZoom(18);
When executed, the map will center on the user’s current location and display a marker at that point on the map.
Creating an Itemized Overlay
The purpose of the itemized overlay is to allow multiple locations to be marked on a map view. The steps involved in working with itemized overlays will be covered in detail in the chapter entitled Marking Android Map Locations using Amazon Map Overlays, but can be summarized as follows:
1. A new class needs to be created that subclasses the ItemizedOverlay<OverlayItem> class.
2. A set of required methods must be implemented in the class created in step 1.
3. An instance of the new ItemizedOverlay subclass is created in the map activity class and initialized with the drawable image that is to be used as the location marker.
4. An OverlayItem object is created for each location on the map for which a marker is required to be displayed. Each object is initialized with the location at which the marker is to appear together with optional text that may be displayed when the location is tapped by the user.
5. Each OverlayItem object created in step 4 is added to the ItemizedOverlay instance created in step 3.
6. The ItemizedOverlay instance is added to the map view overlays.
Summary
Along with the introduction of location awareness in the more recent Kindle Fire generations came the Amazon Maps API. This API is intended to be compatible with the Google Maps API and allows mapping capabilities to be built into Kindle Fire based Android applications.
This chapter has provided an overview of the key classes that make up the Amazon Maps API and outlined the steps involved in preparing both the development environment and an application project to make use of the Amazon Maps API.
<google>BUY_KINDLE_FIRE</google> | http://www.techotopia.com/index.php/Working_with_the_Amazon_Maps_API_on_the_Kindle_Fire | CC-MAIN-2017-39 | refinedweb | 3,361 | 50.46 |
Why Functional Programming?
As software becomes more and more complex, it is more and more important to structure it well. The well-structured software is easy to write and debug and provides a collection of modules that can be reused to reduce future programming costs. Here I will share how functional programming inherently comes up with more scalability and modularity. Compared to imperative programming, in functional programming, you have less chance of creating spaghetti code programs.
The fundamental operation in functional programming is the application of functions to arguments. Typically, the main function is defined in terms of other functions, which in turn are defined in terms of still more functions, until at the bottom level the functions are language primitives. A functional programmer is an order of magnitude more productive than his or her conventional counterpart because functional programs are an order of magnitude shorter. All of these functions are much like ordinary mathematical functions. Functional programming enables and encourages a more abstract way of solving a problem. A more mathematical programming way. You build a program as a mathematical abstraction. The result is less prone to error, cleaner, more elegant and more functional.
One of the biggest advantages of functional programming is: it avoids states during the runtime. i.e. the value of a term is always predetermined by the input. Functional programs contain no assignment statements, so variables, once given a value, never change. i.e the concept of immutability. This allows creating side effect free functions as basic building block in the language. The functions are more like expressions. Since expressions can be evaluated at any time, one can freely replace variables by their values and vice versa. A function call can have no effect other than to compute its result. This eliminates a major source of bugs and also makes the order of execution irrelevant. This is because functional languages do a better job when it comes to parallel computations. Since CPU clocks are nowadays limited and cores are cheaper, multi-core programming is the way to go, and it is made easier with functional programming through immutability and higher order functions. This explains why functional programming has gained so much ground recently.
But this characterization of functional programming is inadequate. All the things discussed until now focused more on what functional programming isn’t (i.e. no assignment, no side effects, no flow of control). Now let’s talk about something that explains the power of functional programming.
One of the very crucial thing a programmer should strive for while creating any real world application is Modularity. It is now generally accepted that modular design is the key to successful programming. One can achieve this in any programming language. When writing a modular program to solve a problem, one first divides the problem into subproblems, then solves the subproblems, and finally combines the solutions. The ways in which one can divide the original problem depend directly on the ways in which one can glue solutions together. Therefore, to increase one’s ability to modularize a problem conceptually, one must provide new kinds of glue in the programming language.
Functional programming comes with two new, very important kinds of glue i.e higher-order functions and lazy evaluation. This is the key to functional programming’s power — it provides a powerful modularization.
Higher order functions:
Higher-order functions is another key area in the functional programming paradigm. Functional languages treat functions as first class values. This provides a flexible way to compose programs. Functions that take other functions as arguments and can return functions as a result are called higher order function. Creating higher order functions improves modularity. To demonstrate it let me take an example of performing some operation (may be an addition, multiplication or division) on each iteration starting from some integer a to some integer b.
I am going to create two functions here. Function 1 returns sum of integers from a to b and function 2 returns sum of cubes of integers from a to b.
Definition of function 1: Sum of Integers
int sumOfIntegers(int a, int b) { int sum =0; for(int i=a; i<b; ++i){ sum = sum+i; } return sum; }
similarly, Definition of function 2: Sum of cubes of Integers
int sumOfCubesOfIntegers(int a, int b) { int sum =0; for(int i=a; i<b; ++i){ sum = sum+(i*i*i); } return sum; }
Thus, In any first-order function (which take primitives like int, long as arguments), I will iterate from a to b and perform my operation in that loop. Let’s say I have n different kinds of operation. In this case, I will be writing n first order functions. I am writing the logic of iteration n times. How amazing it would be if I pass one function as an additional argument along with the two arguments a and b and use the one common function for iteration every time.
For this, I will define my n operations as n different functions (pure functions) and pass them into this common function to compute the result.
To Illustrate it, I am using the syntax of scala in the below code snippet.
Let me define a common function sum which takes another function as its first argument and performs the function operation on each iteration from its second argument to the third argument.
Definition of my Sum function will be like this:
def sum(f:Int=>Int, a:Int, b:Int): Int = if(a>b) 0 else f(a) + sum(f, a+1, b)
Let sumInts and sumCubes be the fuctions which return sum of integers and sum of cubes of integers respectively. I can now describe these functions in terms of sum function as given below:
def sumInts(a:Int, b:Int) = sum(id,a,b)
where id is an identity function defined as
def id (x:Int) => x
And
def sumCubes(a:Int, b:Int) = sum(cube,a,b)
where cube is defined as
def cube(x:Int) => x*x*x
Here, the first argument of sum function is another predicate function which is an identity function in case 1 and a cube function in case 2. Both of these are pure functions.
In this way, I am creating a more modular program and reusing my common function for every computation. Thus, Functional programming provides useful abstractions to specify modules with generic functionality.
The function sum, id and cube are examples of useful abstraction in the above example.
This is an important goal for which functional programmers must strive i.e smaller and simpler and more general modules, glued together with the new glues we shall describe.
Lazy evaluation:
The other new kind of glue that functional languages provide enables whole programs to be glued together.
Lazy evaluation means waiting until the last possible moment to evaluate an expression, especially for the purpose of optimization. Lazy evaluation ensures non-evaluation of an expression when not needed at all. This saves us if an expression is expensive or impossible to evaluate.
A complete functional program is just a function from its input to its output. If f and g are such programs, then (g. f) is a program that, synchronization. Program f is started only when g tries to read some input and runs only for long enough to deliver the output g is trying to read. Then f is suspended and g is run until it tries to read another input. As an added bonus, if g terminates without reading all of f’s output, then f is aborted. Program f can even be a nonterminating program, producing an infinite amount of output, since it will be terminated forcibly as soon as g is finished. This allows termination conditions to be separated from loop bodies — again a powerful modularization.
One should learn functional programming even if he/she is not working in any functional programming language. Understanding functional programming will improve your coding style and make you a better developer. It will definitely improve your way of thinking and add up a new perspective on your code and programming in general. | http://www.tothenew.com/blog/why-functional-programming/ | CC-MAIN-2017-51 | refinedweb | 1,357 | 54.32 |
POJ---3352-Road Construction(双连通分量)
Description
It's almost summer time, and that means that it's almost summer construction time! This year, the good people who are in charge of the roads on the tropical island paradise of Remote Island would like to repair and upgrade the various roads that lead between the various tourist attractions on the island.
The.
So,.
Input
The first line of input will consist of positive integers n and r, separated by a space, where 3 ≤ n ≤ 1000 is the number of tourist attractions on the island, and 2 ≤ r ≤ 1000 is the number of roads. The tourist attractions are conveniently labelled from 1 to n. Each of the following r lines will consist of two integers, v and w, separated by a space, indicating that a road exists between the attractions labelled v and w. Note that you may travel in either direction down each road, and any pair of tourist attractions will have at most one road directly between them. Also, you are assured that in the current configuration, it is possible to travel between any two tourist attractions.
Output
One line, consisting of an integer, which gives the minimum number of roads that we need to add.
Sample Input
Sample Input 1 10 12 1 2 1 3 1 4 2 5 2 6 5 6 3 7 3 8 7 8 4 9 4 10 9 10 Sample Input 2 3 3 1 2 2 3 1 3
Sample Output
Output for Sample Input 1 2 Output for Sample Input 2 0
思路:
tarjan->缩点(割边)
(num(出度为1节点)+1)/2
#include <cstring> #include <cstdio> #include <iostream> #include <cmath> #include <vector> using namespace std; int num; int cnt[1005]; int deep[1005]; int now[1005]; vector<int> node[1005]; void tarjan(int u,int father) { now[u]=deep[u]=++num; for(int i=0; i<node[u].size(); ++i) { int p=node[u][i]; if( p!=father && deep[p]<deep[u]) { if(!deep[p]) { tarjan(p,u); now[u]=min(now[p],now[u]); } else now[u]=min(now[u],deep[p]); } } } int main() { int n,m,i,j,k,a,b; while(~scanf("%d%d",&n,&m)) { for(i=0; i<=n; ++i) node[i].clear(); while(m--) { scanf("%d%d",&a,&b); node[a].push_back(b); node[b].push_back(a); } memset(deep,0,sizeof(deep)); memset(now,0,sizeof(now)); memset(cnt,0,sizeof(cnt)); num=0; tarjan(1,1); for(i=1; i<=n; ++i) for(j=0; j<node[i].size(); ++j) if(now[i]!=now[ node[i][j] ]) ++cnt[ now[i] ]; int sum=0; for(i=1; i<=n; ++i) if(cnt[i]==1)++sum; printf("%d\n",(sum+1)/2); } return 0; } | http://blog.csdn.net/qq978874169/article/details/49933299 | CC-MAIN-2017-43 | refinedweb | 457 | 58.42 |
- Introduction to Unliner
You could also put a shebang line at the top of your script,
chmod +x it and run it directly. (name precedent for def: CL, Python). below if you need to do this).
We can parameterise other aspects of the unliner program too. For example, let's suppose we wanted to control the number of lines that are included in the report. To do this we add a "prototype":
def main(head|h=i) { is required to be an integer number. Because
h is an alias we could also use that as the argument:
$ unliner log-report access.log -h 5
However, if you forget to add an h argument, the head process will die with an error like
head: : invalid number of lines.
In order to have a default value for a paramater, you put parentheses around the argument definition followed by the default value (precedent: lisp):
def main((head|h=i 5)) { grep "GET /report.cgi" $@ | ip-extractor | tally | head -n $head }
Environment variables are also available so
$HOME and such will work.
Defs internal to your program accept arguments in exactly the same way:
def main { grep "GET /report.cgi" $@ | ip-extractor | tally | my-head -n 5 } def my-head((n=i 10)) { head -n $n }
Def Modifiers
The contents of all the defs we've seen so far are in a custom unliner language called sh which is mostly like bourne shell/bash but a little bit different (differences are explained here FIXME).
However, def modifiers can be used to change how the def body is interpreted. while catch it and then exit. wil only be created if the
--filter-localhost option is passed in.
Remember that templates are processed as strings before the language even sees them. For example, here is how you could take advantage of the head "negative number" trick:
def my-head((n=i 5)) : template { head -[% n %] }
Above is OK because
n is guaranteed to be an integer, but when using templates always be careful about escaping or sanitising values.
Debugging
In order to see the actual pipeline being run, you can set the environment variable
UNLINER_DEBUG and it will print some information to standard error:
$ UNLINER_DEBUG=1 unliner log-report access.log --filter-localhost TMP: /tmp/GPtXapOfib. | https://metacpan.org/pod/release/FRACTAL/App-Unliner-0.005/README.pod | CC-MAIN-2017-04 | refinedweb | 380 | 61.16 |
I have written a lot of blog posts on using PYMC3 to do bayesian analysis. And I have a few where I have even dealt with Time-Series datasets. To name a one, I have done one on time varying coefficients. In this post, I want to explore a really simple model, but it is one that you should know about. That is the AR(1) model. Typically, you will see this model in a frequentist setting. It is really about patching up the errors of a model so that they are normally distributed. Really, what is going on under the hood is a partial differencing of the time-series to achieve stationarity. You can read more about my thoughts on the subject here. So today we’ll explore the Bayesian Auto-Regressive model.
Anyway, the nice thing about this model is that it is already available in the form of a PYMC3 distribution. So we just need some data that we can plug into the model and it should be as simple as running it as is. There is no special coding needed to do the the analysis fit the data.
So we will use a familiar dataset. The data is the Prussian Calavry horse kick data set. We used it previously in the post about doing A/B testing on count data when we have multiple categories, or versions/groupings of the counts. You can of course get the count data from here.
Cleaning the Data
As always the first step in doing an analysis is getting the data into a useable format. So we need to do some cleaning on this dataset. We will collapse the dataset into yearly counts, instead of having counts for every unit per year. But in order to do that we need to import some of our favorite libraries and get our data into a pandas dataframe.
import pandas as pd import pymc3 as pm import matplotlib.pyplot as plt df=pd.read_csv('/home/ryan/Documents/HorseKicks.csv')
As advertised the code above just imports libraries and loads the data. If you ran this code, you would find that the data isn’t in a very useable format. So we need to change the data into a simple time series by aggregating on the year. To do that we need to make the year the index variable, and then sum up the columns. This is pretty easy to do with the code below.
df.index = df['Year'] df.drop('Year',axis=1,inplace=True) df = df.sum(1)
Let’s have a look at what this data looks like, shall we?
df.plot() plt.show()
That will give you the following plot:
It looks pretty stationary to me. But there may be some autocorrelation going on. So I think this model would be good to use, just eyeballing it. You can of course run all kinds of statistical tests like we did to look at whether ARIMA was a solid model, I won’t drag you through that again though and we will proceed with the technique.
So we will need the model to do an AR(1) likelihood. Fortunately for us, PYMC3 already has that likelihood prebuilt we just have to use it. So the code below develops the full bayesian model.
with pm.Model() as model: k_=pm.Uniform('k',-1,1) tau_=pm.Gamma('tau',mu=1,sd=1) obs=pm.AR1('observed',k=k_,tau_e=tau_,observed=df) trace=pm.sample()
You will notice that I am breaking with my traditional approach of using a flat prior and using a Uniform prior. I’m doing that, because AR coefficients should be bound between -1 and 1. Which you can see is the prior that I placed on the parameter k. k is the coefficient on the AR process.
Running this will give you output that should look like this:
Auto-assigning NUTS sampler... Initializing NUTS using ADVI... Average Loss = 77.368: 5%|▍ | 9773/200000 [00:03<01:05, 2913.42it/s] Convergence archived at 9800 Interrupted at 9,800 [4%]: Average Loss = 369.97 100%|██████████| 1000/1000 [00:03<00:00, 291.06it/s]
But that doesn't let you analyze anything so you need to have a look at the trace for this model which you can do using the following code:
pm.plot_posterior(trace,'k') print(pm.summary(trace))
That will give you the following output:
k: Mean SD MC Error 95% HPD interval ------------------------------------------------------------------- 0.842 0.095 0.007 [0.662, 0.995] Posterior quantiles: 2.5 25 50 75 97.5 |--------------|==============|==============|--------------| 0.633 0.780 0.848 0.916 0.989 tau: Mean SD MC Error 95% HPD interval ------------------------------------------------------------------- 0.038 0.011 0.000 [0.018, 0.061] Posterior quantiles: 2.5 25 50 75 97.5 |--------------|==============|==============|--------------| 0.020 0.030 0.037 0.044 0.063
This output shows that there is a 50% probability that the coefficient on the AR(1) term is greater than 0.848. And its most likely value is 0.842. That makes a lot of sense given what I typically see in frequentist statistics on these AR terms, so I'm going to throw this into the reasonable pile.
The code above should also display this figure:
And that shows the posterior distribution of the coefficient on the AR(1) term. So you can see that it is fairly wide but it looks about like what we would expect. And that's it with the Bayesian AR(1) model. | https://barnesanalytics.com/bayesian-auto-regressive-time-series-analysis-pymc3 | CC-MAIN-2018-09 | refinedweb | 923 | 75.1 |
Ruby Array Exercises: Compute the sum of the numbers of a given array except the number 17 and numbers that come immediately after a 17
Ruby Array: Exercise-32 with Solution
Write a Ruby program to compute the sum of the numbers of a given array except the number 17 and numbers that come immediately after a 17. Return 0 for an empty array.
Ruby Code:
def check_array(nums) sum = 0 i = 0 while i < nums.length if(nums[i] == 17) i= i + 1 else sum = sum + nums[i] end i += 1 end return sum end print check_array([3, 5, 17, 6]),"\n" print check_array([3, 5, 1, 17]),"\n" print check_array([3, 17, 1, 7]),"\n"
Output:
8 9 10
Flowchart:
Ruby Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Ruby program to compute the average values of a given array, except the largest and smallest values. The array length must be 3 or more.
Next: Write a Ruby program to check whether the sum of all the 3's of a given array of integers is exactly | https://www.w3resource.com/ruby-exercises/array/ruby-array-exercise-32.php | CC-MAIN-2021-21 | refinedweb | 183 | 55.27 |
This preview shows
page 1. Sign up
to
view the full content.
Unformatted text preview: Using the Lab∼jburkardt/isc/week01/
lecture 02.pdf
..........
ISC3313:
Introduction to Scientific Computing with C++
Summer Semester 2011
..........
John Burkardt
Department of Scientific Computing
Florida State University Last Modified: 09 May 2011 s C cienfic ompung Florida Sta Universi 1 / 28 Introduction to Scientific Computing with C++ Introduction
Logging In
Directories
Compile and Run
Exercise: Create and Run a C++ Program
Conclusion s C cienfic ompung Florida Sta Universi 2 / 28 INTRO:
Today we will not have a regular lecture, because your instructor
is out of town on a business trip.
Today we will concentrate on helping you explore the lab
computers, and the software programs installed there.
We will have you go through some simple exercises:
logging in;
setting up your directory;
downloading a file using the browser;
editing a C++ program;
compiling a C++ program;
running an executable program;
We end with an in-class exercise that you must complete for credit.
s C cienfic ompung Florida Sta Universi 3 / 28 Introduction to Scientific Computing with C++ Introduction
Logging In
Directories
Compile and Run
Exercise: Create and Run a C++ Program
Conclusion s C cienfic ompung Florida Sta Universi 4 / 28 LOGIN: Local Access Students in this class can log into any computer in this lab.
You may also use the hallway computers on the fourth floor of
Dirac Science Library, from 8-5 every weekday.
The lab computers and hallway computers have a single, shared file
system. It doesn’t matter which machine you log into; you will
always have access to the same set of files.
To log in, you need to use your FSU ID and password.
Try it now! If you are unable to log in, please let us know! s C cienfic ompung Florida Sta Universi 5 / 28 LOGIN: Remote Access
You may find it useful to be able to move files between the lab
machines and your home computer.
You can access your files from your computer at home or another
lab, using programs such as
ssh for interactive use;
sftp to transfer files.
For instance, if your computer uses the Unix system, and you run
the ssh program from a terminal window, you can type:
ssh pamd.sc.fsu.edu
which will let you access your files on our system.
Windows users can get the free putty program for remote access.
s C cienfic ompung Florida Sta Universi 6 / 28 Introduction to Scientific Computing with C++ Introduction
Logging In
Directories
Compile and Run
Exercise: Create and Run a C++ Program
Conclusion s C cienfic ompung Florida Sta Universi 7 / 28 DIRECTORIES: The Visual Interface
The lab computers run a version of the Linux operating system,
which includes a convenient visual interface.
You will see items on the top menu bar, including:
Applications,
Accessories
Terminal for command line interface;
Text Editor to create and modify files. Programming
KDevelop C/C++ an IDE for C++ programming; Places
System
logout from the system;
s C cienfic ompung Florida Sta Universi 8 / 28 DIRECTORIES: Use the Browser to Get a File
You will also have icons on the left side, such as:
Web browser
Home for storing and organizing files;
Trash for deleting files.
Double click on the browser to start it, then go to∼jburkardt/isc
Move to the Week 1 subdirectory.
Select the hello.cpp program.
Then, from the browser’s File menu, choose Save page as. The
default name and location are fine. Choose OK. The file will be
saved to the Desktop.
Choose Quit from the browser’s menu. s C cienfic ompung Florida Sta Universi 9 / 28 DIRECTORIES: Store the File in a Directory
Double click on the Home icon, which should open up your
home directory. There’s probably almost nothing there right now.
We want to put your file there, but in a separate subdirectory.
From the Edit menu item on your Home Directory window, choose
Create New... and then Folder. When asked for a name for the
folder, type week1. You should now see the image of a folder in
your Home Directory window.
Locate hello.cpp on your Desktop, and drag to the week1 folder.
When you “let go” of the file, you will be asked if you want to
copy or move the file. Choose move.
Click on the week1 folder, so you see the file hello.cpp there.
This suggests some of the ways in which the visual interface can
be used to view your folders and files, to create new folders and to s
move files around. C cienfic ompung Florida Sta Universi 10 / 28 DIRECTORIES: Using the Command Line Interface
While the visual interface is easier to use, there are times when
it is necessary to use what is called the command line interface.
This involves running the Terminal program, which opens a
command window. You type your commands in the window. The
terminal program uses the same file system as the visual interface.
What the visual interface calls folders we will now call directories.
You start in your home directory. You can use commands to move
to a new directory, to get a list of files in a directory, to create new
directories, and to move or copy files.
The commands we will use are known as unix commands; these
commands are very common across almost all computer systems
these days, except for Windows PC’s.
s C cienfic ompung Florida Sta Universi 11 / 28 DIRECTORIES: Open a Terminal in Home Directory
The terminal program is available from the
Applications/Accessories menu.
The terminal always has a present working directory, that is, the
directory (or folder) where it is working. When the terminal
program begins, it starts in your home directory. Because
everything is done with words, not pictures, your home directory
can be identified by a long complicated name. We can always ask
the terminal program to give the name of its present working
directory with the pwd command:
pwd
/panfs/panasas1/users/jburkardt
Luckily, we rarely need to type this long name in. And there is a
shortcut name for your home directory: $HOME. s C cienfic ompung Florida Sta Universi 12 / 28 DIRECTORIES: Listing Directories and Files
Since we don’t have a visual interface, we need a command to
“see” what’s in the current directory. The ls command will “list”
the files it sees, as well as any subdirectories:
ls
week1
You probably don’t have any files in your home directory, so all we
see is the subdirectory we created with the visual interface.
Since week1 is a directory, we can use the ls command to take a
peek inside it:
ls week1
hello.cpp
and sure enough, the file you copied earlier shows up. s C cienfic ompung Florida Sta Universi 13 / 28 DIRECTORIES: Making Directories We already created the week1 directory with the visual interface.
We can make subdirectories with the command line interface as
well. Let’s create a folder for next week’s work now, using the
mkdir command:
mkdir week2
Now the ls command will display two directories:
ls
week1 week2 s C cienfic ompung Florida Sta Universi 14 / 28 DIRECTORIES: Moving Down to a New Directory
The cd command (change directory) is used to move from one
directory to another in the command line interface.
If we are moving down, that is, into a subdirectory of the current
directory, we just type the (short) name of our destination:
pwd
/panfs/panasas1/users/jburkardt
ls
week1 week2
cd week1
pwd
/panfs/panasas1/users/jburkardt/week1
ls
hello.cpp
s C cienfic ompung Florida Sta Universi 15 / 28 DIRECTORIES: Moving Up to a New Directory
A directory can only have one directory “above” it. The
abbreviation .. (two dots) indicates this directory.
Let’s take a journey up from week1 to home, down to week2, back
up again to home, and finally back to week1:
pwd
/panfs/panasas1/users/jburkardt/week1
cd ..
pwd
/panfs/panasas1/users/jburkardt
cd week2
pwd
/panfs/panasas1/users/jburkardt/week2
cd ..
cd week1
pwd
/panfs/panasas1/users/jburkardt/week1 s C cienfic ompung Florida Sta Universi 16 / 28 Introduction to Scientific Computing with C++ Introduction
Logging In
Directories
Compile and Run
Exercise: Create and Run a C++ Program
Conclusion s C cienfic ompung Florida Sta Universi 17 / 28 COMPILE: Finally, Let’s Compile!
One reason for the command line interface is that it’s a simple
way to compile and run programs.
The compiler for C++ on our system is called g++.
Its full name is the Gnu C++ compiler.
The short and simple command to compile hello.cpp is:
g++ hello.cpp
If no errors occurred, we have a new file in our directory, the
executable program a.out. We can run this by the command:
./a.out
Hello, world!
s C cienfic ompung Florida Sta Universi 18 / 28 COMPILE: Renaming a Program
You can change the name of a program (or any file) with the mv
command.
Every time we use the compiler to make an executable program, it
will be called a.out by default. So it might make sense to issue the
following command:
mv a.out hello
This way, if we compile another program, we won’t lose the ”Hello,
world!” program. Moreover, the name of the program reminds us
of what it does. To run the renamed program, we would say:
./hello
Hello, world!
s C cienfic ompung Florida Sta Universi 19 / 28 COMPILE: Saving Program Output
Most programs print some kind of message to the user’s screen.
In C++, output to the user’s screen is called standard output.
Sometimes, it is useful store program output in a file. You might
want to mail it to someone, print it out, or save it for reference.
This is easy to do, using the output redirection operator, which
is the “greater than” sign >.
If we issue the ls command, for instance, we can save the results by
ls > my_files.txt
and if we have renamed our ”Hello, world!” program, we can save
its output by
./hello > hello.txt s C cienfic ompung Florida Sta Universi 20 / 28 COMPILE: Saving Program Output
You can also save program output using the visual interface.
1
2
3
4 Run the program as usual.
Use the mouse to select the output on the screen.
Under the Edit menu on the Terminal, select Copy.
Start an editor (such as kedit or gedit and under the Edit
menu, select Paste. ./hello
Hello, world!
gedit hello.txt
(Now cut and paste the output on the screen into the empty file.
Then save and close the file.)
s C cienfic ompung Florida Sta Universi 21 / 28 Introduction to Scientific Computing with C++ Introduction
Logging In
Directories
Compile and Run
Exercise: Create and Run a C++ Program
Conclusion s C cienfic ompung Florida Sta Universi 22 / 28 PROGRAM: Edit a Program It is too soon to expect you to create a C++ program on your
own. However, we can go through the motions, by entering the
text of a program that has already been written.
It’s possible you have used an IDE (Interactive Development
Environment) for doing programming, which is a more visual way
to work on code.
But to start with, we will look at the simplest technique, using the
same kind of text editor you would use to write a letter. s C cienfic ompung Florida Sta Universi 23 / 28 PROGRAM: Edit a Program You can start up an editor in the Terminal:
Type pwd to make sure you are in the week1 directory.
Type kedit add ints.cpp to start the editor;
Type in the lines on the next page, then save and exit.
or, using the Visual Interface:
Choose Applications / Accessories / Text editor
A blank window opens up; type in the lines on the next page.
Choose the editor Menu item File/Save;
Name the file add ints.cpp, and use Browse for other
folders to save it in the week1 directory.
Exit the editor
s C cienfic ompung Florida Sta Universi 24 / 28 PROGRAM: Edit a Program
# include <iostream>
using namespace std;
int main ( )
{
int number1, number2, number3;
cout << "Enter first integer: ";
cin >> number1;
cout << "Enter second integer: ";
cin >> number2;
number3 = number1 + number2;
cout << "The sum is " << number3 << "\n";
} s C cienfic ompung Florida Sta Universi 25 / 28 PROGRAM: Compile and Run Your Program
Using the terminal application in the week1 directory, compile
your program:
g++ add ints.cpp
If any errors occurred, you may have to go back into the editor and
try to correct them.
Now run your program, with the following input:
./a.out
Enter first integer: 123456789
Enter second integer: 987654321
The sum is _______
This is the end of the in-class exercise. To get credit, please show
Detelina your computer screen with the results, or save the output
and email it to her at [email protected] s C cienfic ompung Florida Sta Universi 26 / 28 Introduction to Scientific Computing with C++ Introduction
Logging In
Directories
Exercise: Create and Run a C++ Program
Conclusion s C cienfic ompung Florida Sta Universi 27 / 28 CONCLUSION:
When you work on the lab computers, you need to become
familiar with the visual interface and the terminal interface.
We have learned some basic Unix commands today:
cd to change directories
ls to list files;
mv to rename a file;
pwd to report the present working directory;
and how to start some programs from the command line:
./a.out, a user program with the default name of a.out
g++, the compiler
kedit, the editor;
s C cienfic ompung Florida Sta Universi 28 / 28 ...
View Full Document
This note was uploaded on 01/15/2012 for the course ISC 5315 taught by Professor Staff during the Spring '11 term at FSU.
- Spring '11
- staff
Click to edit the document details | https://www.coursehero.com/file/6694229/lecture-02/ | CC-MAIN-2017-17 | refinedweb | 2,322 | 60.65 |
timer_delete(3rt) [sunos man page]
timer_delete(3RT) Realtime Library Functions timer_delete(3RT) NAME
timer_delete - delete a timer SYNOPSIS
cc [ flag... ] file... -lrt [ library... ] #include <time.h> int timer_delete(timer_t timerid); DESCRIPTION. RETURN VALUES
If successful, the function returns 0. Otherwise, the function returns -1 and sets errno to indicate the error. ERRORS
The timer_delete() function will fail if: EINVAL The timer ID specified by timerid is not a valid timer ID. ENOSYS The timer_delete() function is not supported by the system. ATTRIBUTES
See attributes(5) for descriptions of the following attributes: +-----------------------------+-----------------------------+ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | +-----------------------------+-----------------------------+ |Interface Stability |Standard | +-----------------------------+-----------------------------+ |MT-Level |MT-Safe with exceptions | +-----------------------------+-----------------------------+ SEE ALSO
timer_create(3RT), attributes(5), standards(5) SunOS 5.10 28 Jun 2002 timer_delete(3RT)
TIMER_DELETE(2) Linux Programmer's Manual TIMER_DELETE(2) NAME
timer_delete - delete a POSIX per-process timer SYNOPSIS
#include <time.h> int timer_delete(timer_t timerid); Link with -lrt. Feature Test Macro Requirements for glibc (see feature_test_macros(7)): timer_delete(): _POSIX_C_SOURCE >= 199309L_getoverrun(2), timer_settime(2), time(7) COLOPHON
This page is part of release 3.53 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at. Linux 2009-02-20 TIMER_DELETE(2) | https://www.unix.com/man-page/sunos/3RT/timer_delete/ | CC-MAIN-2020-10 | refinedweb | 199 | 66.54 |
Introduction to Unity UI – Part 1
In this first part of a three part tutorial, series you’ll be acquainted with the Unity UI, enabling you to add an custom user interfaces to your game.
Update 20th December 2016: This tutorial was updated to Unity 5.5 by Brian Moakley. Original post by Kirill Muzykov.
In previous versions of Unity, the old UI system was downright horrific. It required you to write all your GUI code in OnGUI. It was very programmer-centric which goes against the visual centric nature of Unity itself, and not mention slow and inefficient.
Thankfully, the folks over at Unity Technologies have listened.
In this three-part series, you’re going to explore Unity’s new UI system by adding an interactive UI to a small game named Rocket Mouse.
To add a little spice and satisfy your users’ cravings for an engaging UI, you will also:
- Animate the buttons;
- Create a settings dialog that slides into the scene;
- Use more GUI controls like Text, Slider, Panel, Mask and so on;
Getting Started
You will need some images for backgrounds, buttons and other UI elements, as well as a few fonts for the labels and buttons. And no, you won’t have to draw anything yourself or scour the web for the right assets because I’ve prepared a special package that has everything you need. You’re welcome. :]
You can download the package here: RocketMouse_GUI_Assets.
Within the package you will find background images, buttons, icons and other game art, in addition to two fonts from dafont.com. The game art is provided by Game Art Guppy, where you can find a lot of other game art for your practice games:. You can thank Rodrigo Fuenzalida for the Titan One font and Draghia Cornel for the DCC Dreamer font.
Lastly, you’ll need to download the starter project containing the RocketMouse game. Download and unpack the Rocket Mouse project using the following link: Rocket Mouse starter project
This is all you need! Well, except love, if you take the Beatles song to heart. :]
Creating MenuScene
Open the RocketMouse_Starter project in Unity by selecting OPEN within Unity’s startup dialog and specifying the root folder of the project.
You’re going to spend most of your time working with a new scene that you’ll create now. From menubar, Select File\New Scene to create a new empty scene.
It’s better to save the scene straight-away, so open the Save Scenes dialog by choosing File\Save Scenes. Then, enter MenuScene as the scene name and save it to the Scenes folder, right next to the RocketMouse scene.
Take a look at the Project window to confirm that there are two scenes in one folder:
Importing Images and Fonts
First on your to do list is to add assets to the scene, so unpack the assets package. There you’ll find two folders: Menu and Fonts.
Select both folders, and then drag them to the Assets folder in Unity’s Project window:
Woo-hoo! You’ve finished the setup and you are ready to create your first UI element using the new Unity GUI system.
Adding your First UI Element
The first element you’ll make is the background image for the menu scene.
From the top bar, select GameObject \ UI \ Image. This adds an object named Image to the scene. You should see it in the Hierarchy as a child of Canvas. All elements must be placed on a Canvas, so if you don’t already have one, Unity will create one for you.
To ensure you can see the image in the scene view, select Image in the Hierarchy and set both its Pos X and Pos Y to 0.
You’ll set the correct position and size in a moment – right now, there is another interesting thing to muse upon. Look carefully in the Hierarchy, and you’ll see there are three new objects in the scene:
- Image
- Canvas
- EventSystem
The Image is a non-interactive control that displays a Sprite and has many options to tweak.
For instance, you can apply a color to the image, assign a material to it, control how much of the image that displays, or even animate how it appears on the screen using a clockwise wipe.
The Canvas is the root object for all your UI elements and, as previously stated, it’s created automatically when you add your first UI element. It has multiple properties that allow you to control how your UI renders, and you’ll explore some of them during this tutorial.
The EventSystem processes and routes input events to objects within a scene. It is also responsible for managing raycasting. Like the Canvas, it is required for the UI to work so it is also added automatically by Unity.
Setting Up the Menu Background Image
The first thing to do is rename your image. In the Hierarchy, select Image and rename it to Img_Background.
Next, open the Menu folder in the Project window and find the menu_background image. Drag it to the Source Image field of the Image component in Img_Background in the Inspector:
Now you have a background image instead of the default white image. However, it doesn’t look like a good background because it’s too small and the aspect ratio is incorrect.
To fix this, find the Set Native Size button in the Inspector and click it to set the size to 1136 x 640.
Now it looks like a proper background.
However, there is still one issue:
- Shrink your Scene view, and you’ll see the Canvas (the white rectangle) covers only part of the image. If you switch to the Game view, you’ll see only a part of the background image, as if the camera is too close to the image to capture it completely.
You’ll tackle this issue by using a Canvas Scaler.
Using the Canvas Scaler
You will use the Canvas Scaler to adjust the way the background image displays.
First, however, you need to know that the display is not the result of a bug. From Unity’s point of view, you have the Game view — or viewport — set to such a small size that it just displays a portion of the image that fits within the Game view.
If you were to run the game on a device with a large enough resolution or simply stretch the Game view to fit the whole image, you would see the entire background image.
Although Unity’s settings make sense in most scenarios, there are times when you need different behavior. An example is when you have a small monitor that doesn’t fit your target device’s resolution.
Additionally, many games support only one resolution. Designers use this reference resolution to dictate sizes, positions, and other data. When you develop a game based on a single reference resolution, you want to make sure to enter the designer’s specifications without additional calculations so that the user sees everything exactly as intended.
If you’ve ever ignored your designer’s directions, surely you know there’s a price to pay. Really though, the user’s experience and the varying resolutions out there are more important, but you have to keep your designer happy, too. :]
Fortunately, a special component comes to the rescue. This component is called Canvas Scaler and you will find it attached to every Canvas by default.
Select Canvas in the Hierarchy, and in the Inspector, you should see the Canvas Scaler component:
The Canvas Scaler has three scale modes:
- Constant Pixel Size: Makes all the user interface elements retain the same pixel size, regardless of the screen size. This is the default value of the Canvas.
- Scale With Screen Size: User interface elements are sized and positioned in accordance to a referenced resolution. If the current resolution is larger than the referenced resolution, then the Canvas will maintain the reference resolution, while scaling up the elements to match the target resolution.
- Constant Physical Size: Positions of the user interface elements are specified in physical units such as millimeters or points. This requires the correct reporting of the screen DPI.
Change the component mode to Scale With Screen Size and set its Reference Resolution to 1136 x 640. Also, slide the Match Width or Height all the way to the right, or simply enter 1 in the input field.
After making those changes, you’ll immediately see the full background image, even in a small Game view window.
Change the Game view resolution to see how your game might look in a different resolution, for example on iPhone Wide 480×320. You’ll notice it still looks good!
Unity will reprocess all your assets so it may take a while. At the end, you should now have access to the various iOS screen sizes.
Now switch to the Scene view, and you’ll see the Canvas’s size doesn’t change when you resize the Scene view.
The side edges of the screen are neatly cropped, while the central part is fully visible. This is the result of setting Match Width or Height to 1 (match height). It works perfectly for your target resolutions.
But what about the buttons? What happens when they’re too close to the left or the right edge of the screen? You sure don’t want to crop or hide them.
Fortunately, Unity has a feature that will help you sidestep this rookie mistake. You’ll learn about it soon.
Adding a Header Image
It might have seemed a bit time consuming to add just the background image, but that’s mostly because you were setting up the initial UI. Plus, after doing this a couple of times you’ll find the setup to be so fast and easy that you’ll barely have time to blink before you’re done.
Before moving on to buttons and other UI controls, you’ll add one more image — the header image. For this exercise, you’ll use a non-fullscreen image to demonstrate a few other important concepts of Unity’s new UI system.
Open the Scene view and from the top bar, select GameObject \ UI \ Image. This will add another image as a child of Canvas:
Now, turn that white rectangle into an actual image by following these steps:
- Select Image in the Hierarchy and rename it to Img_Header.
- Open the Menu folder in the Project window and search for the header_label image.
- Drag the image to the Source Image field on the Inspector.
- Click Set Native Size in the Inspector.
As you can see, it was easy enough to add another image. Now you just need to work on its positioning, which brings you to your next exercise: working with the Rect Transform component.
Rect Transform, Anchors, Pivot and You
If you worked with Unity before, or at least completed some Unity tutorials on this website, then you’ve probably had some exposure to the Transform component.
If not, that’s fine too. It’s simply a tool that can position, rotate and scale objects in a scene. Here’s what it looks like:
You will see the Transform component when you select any type of non-UI GameObject in your Hierarchy view. However, if you select any UI element, for example Img_Header, you’ll see a different component named Rect Transform.
As you can see, Transform and Rect Transform look a bit different. Additionally, the Rect Transform can change the way it looks, depending on its Anchor settings. For example, it can look like this:
Here, instead of Pos X, Pos Y, Width and Height, you have Left, Top, Right and Bottom.
Are you wondering about the Anchors setting that changes the look of Rect Transform so dramatically? You’ll find the answers you seek in the next section.
Anchors
Setting anchors is a simple, elegant and powerful way to control the position and size of your UI elements, relative to their parent. It’s especially handy when you have to resize the parents.
When you set anchors, you specify several positions in the parent, usually one in each corner of the parent’s UI element Rect. When the parent is resized, your UI element will try to maintain a uniform distance to the anchor points, thus forcing it to move or resize right along with its parent.
To see different Anchor Presets just select Img_Header in the Hierarchy and click on the rectangle right above the Anchors field in the Rect Transform component.
After clicking, you’ll see various Anchor Presets: these are the most common settings for anchors. However, you are not restricted to them and you can customize any of them. You can also select different horizontal and vertical behavior for your UI element.
This will all make more sense once you work with it. If you look at the next image, which has the background image disabled, you’ll be able to see the Canvas size changes a bit better.
As you can see, the anchors settings control how your UI element adapts to screen size changes.
Anchors are represented by 4 triangular handles which kind of look like a flower. Here is how it looks with anchors set to the top-center preset:
I’m sure you want to try some different settings to understand how they work, but before you do be sure to at least read through the next section. It’ll help you understand Anchors a little better so that you can get more out of your experimentation.
Custom Anchors
You can manually move Anchors to a custom position as the presets are entirely optional — they are just for your convenience.
In this case, just select the anchor icon by choosing an anchor preset (for example, the left-hand side of the screen). The anchor icon will shift to that part of the screen, allowing you to select and move it at will.
See how the image moves to the right when you resize the Canvas? It moves only a little in relation to the right edge of the Canvas, this happens because these anchors are set to 25% width of the Canvas.
Splitting Anchors
You can split anchors to make them stretch an UI Element horizontally, vertically or both.
Look for the word Preview next to the cursor when you try to resize it. Use this technique to experiment and see how your UI elements adapt to different screen sizes.
Rect Transform Depends on the Current Anchors Setting
Depending on the anchors setting, the Rect Transform provides different ways to control the size and position of your UI element.
If you set anchors to a single point without stretching, you’ll see the Pos X, Pos Y, Width and Height properties.
However, if you set anchors in a way that stretches your UI Element, you’ll get Left and Right instead of Pos X and Width (if you set it to stretch horizontally) and Top and Bottom instead of Pos Y and Height (if you set it to stretch vertically).
In this screenshot, Img_Header’s Anchors are set to middle-stretch. This means that the image stays in the middle of the Canvas vertically and stretches horizontally.
Pivot
There is one final property to discuss in the Rect Transform component, and this is Pivot.
The pivot is the point around which all transformations are made. In other words, if you change your UI Element position, you also change the pivot point position. If you rotate your UI Element, it’ll rotate around that point.
The pivot is set in normalized coordinates. This means that it goes from 0 to 1 for both height and width where (0,0) is the bottom left corner and (1,1) is the top right corner.
You can change pivot in the Rect Transform component in the Inspector or you can use the Rect Tool.
Take a look at the following two images that demonstrate the UI Element with the same Pos X and Pos Y values, yet each shows different placement in the scene.
The first image shows the pivot at its default value of (0.5 , 0.5), which is the center of the UI element. The Position is set to (0, 0) and the anchors are set to top-left.
Now take a look at the second image. As you can see, the position is unchanged at (0,0), but since the Pivot is set to left bottom corner (0,0) you can see that the image’s bottom corner, and not the center, is now placed at the Canvas’s top-left.
It’s harder to show how pivot affects rotation and size using a still image, so here are few animations:
Observe how the image rotates around the pivot point indicated by a blue circle, which is an element you can freely move.
As you can see, the pivot also affects how your UI Element resizes.
Be aware that there are a few differences between size and scale. For example, size can’t be negative, but scale can be. Also, using a negative scale value will flip your UI element. In most cases, you should only change the size of your UI Elements.
Placing a Header Image
Phew! That was quite a few words dedicated to Rect Transform, Anchors and Pivot. Believe me, you’ll be grateful you spent the time working through the exercise, as understanding them is essential to awesome UI in your games.
Going forward, you’ll concentrate on actually creating the menu scene. The rest of the sections will go by in the twinkle of an eye.
All those manipulations completely exhausted the poor little img_header. It’s time to place it where it should be and leave it alone to recover.
Before you continue, re-enable Img_Background if you disabled it to see the Canvas border.
Then select Img_Header in the Hierarchy and set its properties in the Inspector as follows:
- Click Set Native Size to reset the size, as you probably messed with it while playing around with the pivot.
- Set Anchors to top-center.
- Set Pos X to 0 and Pos Y to -100.
You should see something like this in your Scene view:
That’s it! Now, leave the header image alone. It’s a little tired, too. :]
Adding the Start Button
Now, that your game has a nice background with a label, it’s time to add some buttons.
From the top bar, choose GameObject \ UI \ Button. This will add a Button object to the scene, you should see it in the Hierarchy. If you expand it in the Hierarchy, you’ll see that the button contains a Text child — you’ll learn about these later.
Look at the button in the Inspector, and you’ll see it has a familiar Image component, the same as you used to add the background and the header label.
Additionally, there is a Button component. In other words, a button is just an image with a child Text element and an attached button script.
Positioning the Button
Now it’s all about positioning and resizing the button. Follow these steps:
- Select Button in the Hierarchy view and rename it to Btn_Start.
- Set its Anchors to bottom-stretch, since you want it to stretch horizontally if the screen size changes.
- Set both Left and Right to 350.
- Set Height to 80.
- Set Pos Y to 300.
Then select the nested Text element and set its Text to Start Game. Change the Font Size to 32 to make the text of the button larger.
This is what you should see in the Scene view:
Well… you definitely have a button now, that’s for sure, and it’s in need of a facelift. To make the button look good, you’ll set an image as its background and then use a fancier font.
9-Slice Scaling
You set the image for the Button the same way you set an image for the Image. After all, they use exactly the same component. However, unlike images that rarely scale, especially non-uniformly, buttons often come in completely different sizes.
Of course, you could create a background image for every single button size in your game, but why waste all that space? You’ll use a technique called 9-Slice scaling, which allows you to provide one small image that scales to fit all the sizes.
There is no magic involved here, you won’t have to put your images in a magic fountain before you can use them. :]
This technique works by creating different images for each of nine zones, all of which scale differently.
This ensures the image will look good at any scale.
Preparing Button Images
Before you can use a sliced image, you need to set those 9 zones. To do this, open the Menu folder in the Project window and select btn_9slice_normal image.
In the Inspector’s Import Settings, set Texture Type to Sprite (2D and UI) and apply the change. Next, click on the Sprite Editor button to open the Sprite Editor view.
In the Sprite Editor, set the Border values to L:14, R:14, B:16, T:16. Remember to click Apply!
Repeat the same process for btn_9slice_highlighted and btn_9slice_pressed images, which you’ll use for different button states.
Setting Button Images
After preparing all images, you only need to drag them to the corresponding fields in the Inspector. Select Btn_Start in the Hierarchy and follow these steps:
- Change Image Type to Sliced in the Image component.
- Change the Transition property in the Button component to SpriteSwap.
- Drag btn_9slice_normal to Source Image in the Image component.
- Drag btn_9slice_highlighted to Highlighted Sprite in the Button component.
- Drag btn_9slice_pressed to Pressed Sprite in the Button component.
Before running the scene and enjoying your cool buttons you are going to take a few seconds to change the font used by the nested Text label. This will make the button mega-awesome.
Setting a Custom Font for the Button
Using a custom font is easy. Remember the Fonts folder in the package you downloaded and added to the project? Now it’s time to break it out and use one of those fonts.
Select the Text element nested within Btn_Start in the Hierarchy. Then open the Fonts folder in the Project window and drag the TitanOne-Regular font into the Font field. Also set the Color to white.
Now run the scene and enjoy your new mega-awesome button! :]
Adding the Settings Button
There are only few things left to do before moving on to the next part, and one of them is adding the Settings button.
You can probably do this yourself, so you’re only getting the size and position of the button to start. The rest is almost identical to how you created the Start Game button.
So, here are the properties of the Settings button that are different:
- Name: Btn_Settings
- Rect Transform: Left and Right are 400, Height is 70 and Pos Y is 180
- Text: Settings
- Fontsize: 24
[spoiler title=”Solution Inside: Need help creating the Settings button?”]
If you couldn’t quite do it, just follow these steps:
- From the top bar, select GameObject \ UI \ Button. This will create a Button object in the scene.
- Select Button in the Hierarchy view and rename it to Btn_Settings.
- Set the button Anchors to bottom-stretch.
- Set both Left and Right in Rect Transform to 400.
- Set Height to 70 and Pos Y to 180.
- Set Transition in the Button component to SpriteSwap.
- Make sure to set Image Type in the Image component to Sliced.
- Open the Menu folder in the Project Browser and drag btn_9slice_normal to Source Image.
- Then drag btn_9slice_highlighted to Highlighted Sprite.
- And finally, drag btn_9slice_pressed to Pressed Sprite.
- Double-click on Color inside the Image component and check if A is set to 255 to remove any transparency.
- Select nested Text label.
- Change Text to Settings.
- Set Font Size to 24.
- Change Color to White.
- Open the Fonts folder in the Project Browser and drag TitanOne-Regular font into the Font field in the Inspector view.
[/spoiler]
This is what you should see in the Scene view after adding the Settings button:
Now Save Scenes your work.
Starting the Game
The final task for this part is to actually click the Start Game button and run the second scene in the game itself.
Adding Scenes to Build
Before you can run different scenes, you need to add them to the Scenes in Build list in the Project Settings, so that they are included in the final application.
To do this, on the menu select File \ Build Settings. This will open the Build Settings dialog. Then open the Scenes folder in the Project Browser and drag the MenuScene first, and then the RocketMouse scene to the Scenes in Build list.
Finally, close the Build Settings dialog.
Creating UIManager
When you add an event handler to the button, you need to specify which method to call when you click the button. Since you cannot use static methods, you will need to select a public method from a script that is attached to a GameObject.
From the top bar, choose GameObject \ Create Empty. Then select GameObject in the Hierarchy view and rename it to UIManager.
After that, click Add Component in the Inspector and select New Script. Name it UIManagerScript. Make sure the Language is set to CSharp and click Create and Add.
This is what you should see in the Hierarchy view and the Inspector view:
Double-click on the UIManagerScript in the Inspector to open the script in MonoDevelop. Once the script loads, remove both
Start() and
Update().
Next add the following statement underneath the previous `using` statements.
using UnityEngine.SceneManagement;
This allows you to load other scenes. Next add the following:
public void StartGame() { SceneManager.LoadScene("RocketMouse"); }
Save the script and move on to the next step:
Calling the StartGame method when the Player Clicks the Button
Switch back to Unity and follow these steps:
- Select Btn_Start in the Hierarchy and scroll down in the Inspector to the On Click() list.
- Click the + button to add new item.
- Then drag UIManager from the Hierarchy to the newly added item in the list.
- Click on the dropdown to select the function. Right now, it’s set to No Function.
- In the opened menu select UIManagerScript and the select StartGame () in the menu that opens next.
Save Scenes your work and then Run the scene and click the Start Game button, this should open the game scene.
Where to go From Here?
Stuck on any issues? Feel free to download the completed project for this part.
It might feel like you didn’t do much in this last section but this is not true. You set up the UI, added images and buttons, and even wrote the code that starts the game when you click on the button!
In many games, that’s all that comprises the UI.
You also learned a lot about Rect Transform, Anchors, Pivot and so on. What’s cool is now that you understand them, you’ll be able to move much faster when you apply these new skills to your own projects.
In the next part of this series, you’ll learn how to animate UI elements, create dialogs, and use controls like Slider and Toggle. By the end of it you’ll have a working menu scene.
If you have any questions or comments please leave them below! See you in Part 2! | https://www.raywenderlich.com/795-introduction-to-unity-ui-part-1 | CC-MAIN-2018-51 | refinedweb | 4,615 | 71.75 |
Previously SAP AIF- Simple Outbound Scenario Part-1 we have covered the basic process for SAP PI and Proxy.
Here we will be dealing with SAP AIF Customization for Outbound Scenario .
SAP AIF Customization
Here I’ll be using the same namespace ZAIF_D (as it was created for Inbound Scenario )
Define Interface– Select the namespace (ZAIF_D), New Entries.
Select-(as highlighted in below figure )
Proxy Class Outbound.
SAP DataStrucutre
Specify interface engine – Enter the details as shown below.
Define Structure Mapping – Select Namespace, InterfaceName,Interface Version
Select the Source Structure ( this is created in SE11)
Now select destination structure –
Define field Mapping
For simplicity, No action has been added here
For triggering an Outbound data.
Go to SE38 – Create a report which will give the total number of records updated, using CALL FUNCTION ‘/AIF/SEND_WITH_PROXY’
SXMB_MONI (ECC)
T-code –AIF/ERR – Shows successful message
Related Content —
SAP Application Interface Framework – SAP Library……
SAP AIF – Simple Inbound Scenario – Part-3
nice blog 🙂
Can you also post the different methodology for connectivity to PI and other systems ?
Thanks for the info by the way.
Can we send data from a report / OData service to AIF? Please explain with steps. I checked many forums in SAP, but didn’t find any document for that | https://blogs.sap.com/2015/08/14/sap-aif-simple-outbound-scenario-part-2/ | CC-MAIN-2017-30 | refinedweb | 211 | 52.8 |
NextPrevious ReadMe.txt SimpleScripting=============== ABOUT: This sample illustrates the initial steps required to make an application scriptable. Other samples in the SimpleScripting* series build on top of this sample to show how to add additional scripting functionality. Step 1: Setting up Create a new .sdef file that includes the standard scripting suite and add it to your Xcode project. Usually, this file will have the same name as your application. Going along with that convention, the .sdef file in this sample has been named "SimpleScripting.sdef". In the contents of that file, enter an empty dictionary that includes the standard AppleScript suite as follows: <dictionary xmlns: <xi:include <!-- add your own suite definitions here --> </dictionary> The important parts of this definition are as follows: 1. The 'xi' namespace declaration in the opening dictionary element declares that enclosed elements using the 'xi' namespace will follow conventions defined by the XInclude standard. This will allow us to include the standard definitions. 2. The 'xi:include' element includes the Standard Suite in the .sdef. NOTE: Prior to Mac OS X 10.5 developers would copy the standard suite from the ScriptingDefinitions sample () directly into their .sdef file. For backwards compatibility with Mac OS X 10.4, you may continue to use that technique, but moving forward the XInclude technique described above is recommended. Step 2: Advertise your scriptability Add these two entries to your application's Info.plist file: <key>NSAppleScriptEnabled</key> <string>YES</string> <key>OSAScriptingDefinition</key> <string>Simple.sdef</string> The first marks your application as one that supports scripting, the second lets the system know where to look for your application's scripting definition file. You should use the file name you used in step 1. Step 3: Start editing your Scripting Definition (.sdef) file In Xcode, select your .sdef file and select "File > Open As... > Plain Text File", and edit the file to include definitions for your own application. IMPORTANT: You can use the Script Editor application to view your application's dictionary in a dictionary viewer and to write test scripts. Whenever you make changes to your .sdef file you will have to quit and run Script Editor again for it to see the changes, because it caches dictionaries while it is running. Step 4: Add a starting suite Add a new suite to your .sdef file at the end of the dictionary just before the closing </dictionary> tag: <suite name="Simple Scripting Suite" code="SScr" <!-- put your application specific scripting suite information here --> </suite> It is inside of this suite definition where you will put your application specific scripting information. You can add additional suites if you like and use them to group related scripting functionality together, but for most purposes one should be sufficient. Step 5: Add an application class to your new script suite. Here is our new suite with the application class added in: <suite name="Simple Scripting Suite" code="SScr" description="SimpleScripting application specific scripting facilities."> <!-- put your application specific scripting suite information here --> <class name="application" code="capp" description="Our simple application class." inherits="application"> <cocoa class="NSApplication"/> <property name="ready" code="Srdy" type="boolean" access="r" description="we're always ready"/> </class> </suite> Note, the application class we have added inherits from the application class defined in the Standard Suite in Skeleton.sdef. Also, to get started we have added a single property to our specialized application class named 'ready'. Note that I have defined this property as 'read only' by specifying an access attribute of "r". The application class is the root container class for an AppleScriptable application. All of the root functionality provided by your application will be contained in this class and the other classes and objects that it contains. Important points to note of here: - the suite has a unique four-character code associated with it 'SScr'. - the 'ready' property has a unique code associated with it. When picking that code, I first consulted the AppleScript Terminology and Apple Event Codes table here: to see if 'ready' was already associated with a four letter code. If it was I would have used that code, but I didn't find the word 'ready' listed there so I made up a four-character code for it. And, of course, I double checked it against the codes in the Apple Event Codes table to make sure I wasn't swiping a code that was already in being used for another term). Step 6: Add a category to the NSApplication class. Add the files SimpleApplication.h and SimpleApplication.m to your project and add a definition for a category of NSApplication to them that implements the 'ready' property accessor. in SimpleApplication.h: #import <Cocoa/Cocoa.h> @interface NSApplication (SimpleApplication) - (NSNumber*) ready; @end and in SimpleApplication.m: #import "SimpleApplication.h" @implementation NSApplication (SimpleApplication) - (NSNumber*) ready { return [NSNumber numberWithBool:YES]; } @end Since we specified the 'ready' property as read only, we only need to provide an accessor for reading its value. There's no point in implementing a setter method function as it's a read only property. Step 7: The big test Build and run your application. Then, run the following script in the Script Editor: tell application "SimpleScripting" propertiesend tell It should report the following result showing the 'ready' property: {name:"SimpleScripting", frontmost:false, version:"0", class:application, ready:true} If you've gotten this far, then congratulations you have made your first scriptable application. Step 8: One last thing... As you begin to add scripting to your application you will more than likely want to debug it and see what's going on. But, in doing that you will be confronted with the fact that the way scripting operates, using a debugger isn't always the most convenient way to figure out what's going on. While processing a script your application is likely to receive many callbacks (hundreds in many cases) and what you need to do is track those callbacks to discover what is going on. So, what do you do? Well, we recommend that you add logging statements to the methods implementing your scripting callbacks. In this step we'll add a new file to the project called scriptLog.h containing the following definitions: #define scriptLoggingMasterSwitch ( 1 ) #if scriptLoggingMasterSwitch #define SLOG(format,...) NSLog( @"SLOG: File=%s line=%d proc=%s " format, strrchr("/" __FILE__,'/')+1, __LINE__, __PRETTY_FUNCTION__, ## __VA_ARGS__ ) #else #define SLOG(format,...) #endif And then we'll modify SimpleApplication.m so it contains: #import "SimpleApplication.h" #import "scriptLog.h" @implementation NSApplication (SimpleApplication) - (NSNumber*) ready { SLOG(@"Here we are!"); return [NSNumber numberWithBool:YES]; } @end Now, if we add in those changes, build and run the result, and run the same test script from before, we'll find the following entry in our application's run log: 2007-02-21 17:36:56.913 SimpleScripting[4905] SLOG: File=SimpleApplication.m line=15 proc=-[NSApplication(SimpleApplication) ready] Here we are! It shows the file name, line number, method name and the string we provided. Later as we add additional scripting functionality we'll find these log messages valuable for tracking what's going on with our scripting. Step 9: Where to next? Well, now that you have the very basics in hand, you're all ready to start adding scriptability to your application. But, careful planning before you start adding in scripting features will be well worth your while. So, please consider reading the following documentation. - The items listed in the section "Implementing a Scriptable Application" on this page are essential reading. Everyone new to scripting should read through these documents and familiarize themselves with the topics discussed. - "Designing for Scriptability in Cocoa Scripting Guide provides a high-level checklist of design issues and tactics: - This Scripting Interface Guidelines document provides more detailed information you should consider when adding scriptability to your application: - The AppleScript terminology and Apple Event Codes document provides a listing of four character codes that area already defined for use with specific terms. As you are adding terminology to your application you should always check there to see if a four character code has already been defined for a term you would like to use AND to make sure a four character code you would like to use is not already being used by some other terminology. - NSScriptCommand class is the one you use for implementing verbs (aka commands) Step 10: And after that? This sample is part of a suite of samples is structured as an incremental tutorial with concepts illustrated in one sample leading to the next in the order they are listed below. SimpleScripting (you are here) SimpleScriptingProperties SimpleScriptingObjects SimpleScriptingVerbs ===========================================================================BUILD REQUIREMENTS Xcode 3.2, Mac OS X 10.6 Snow Leopard or later. ===========================================================================RUNTIME REQUIREMENTS Mac OS X 10.6 Snow Leopard or later. ===========================================================================CHANGES FROM PREVIOUS VERSIONS Version 1.1- Project updated for Xcode 4.Version 1.0- Initial Version ===========================================================================Copyright (C) 2008-2011 Apple Inc. All rights reserved. NextPrevious Copyright © 2011 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2011-09-07 | https://developer.apple.com/library/mac/samplecode/SimpleScripting/Listings/ReadMe_txt.html | CC-MAIN-2014-10 | refinedweb | 1,504 | 56.45 |
Created on 2018-11-08 14:41 by hroncok, last changed 2019-02-14 16:26 by josh.r.
The collections.abc — Abstract Base Classes for Containers documentation says:
> This module provides abstract base classes that can be used to test whether a class provides a particular interface; for example, whether it is hashable or whether it is a mapping.
However this is not true for Sequence.
When I implement a class that provides a particular interface (defined in the Collections Abstract Base Classes table in that very page), I cannot check whether it implements a Sequence.
See an example:
from collections import abc
class Box:
def __init__(self, wrapped):
self._w = wrapped
def __len__(self):
return len(self._w)
def __iter__(self):
yield from self._w
def __getitem__(self, i):
return self._w[i]
def __reversed__(self):
yield from reversed(self._w)
def __contains__(self, i):
return i in self._w
def index(self, value, start=0, stop=None):
return self._w.index(value, start, stop)
def count(self, value):
return self._w.count(value)
b = Box([1, 2, 3])
for t in 'Sized', 'Iterable', 'Reversible', 'Container', 'Collection', 'Sequence':
print(f'{t}: {isinstance(b, getattr(abc, t))}')
My class is Reversible.
My class is a Collection (as it is a Sized Iterable Container).
It implements __getitem__, __len__, __contains__, __iter__, __reversed__, index, and count.
Yet my class instance is not an instance of Sequence.
I suppose this behavior might be intentional, as discussed in issue16728 - or it might as well not be.
The main concern was that dict also provides these methods, but is not considered a Sequence,
however dict does not provide index() or count().
Regardless whether this is right or wrong behavior, as documented this should be a Sequence.
See also
As I see it, either:
collections.abc.Sequence needs a __subclasshook__ so it can be used as the documentation implies.
Or:
the documentation should not say that "abstract base classes (from abc module) can be used to test whether a class provides a particular interface" if it doesn't generally apply
Or:
the Sequence documentation should say: "this particular abstract base class cannot be used to test whether a class provides a particular interface because reasons" (yet I don't really get those reasons)
Yeah, the docs need to be clarified.
I fail to understand what abc classes can be used to test whether a class provides a particular interface, and what abc classes cannot be used that way. What is the difference between those abc classes and why are all those abc classes listed together when they behave differently?
The separation may look arbitrary, but the idea is quite simple. Only those classes with few methods support structural checks. Those classes have few independent abstract methods (or even just one method), while in classes with large APIs like `Sequence`, the methods are not logically independent, so you can't say a class is 100% a `Sequence` even if types/signatures of all methods are correct, because e.g. `__contains__()` and `index()` should behave in agreement with `__getitem__()`.
We might explicitly document which ABCs support structural checks, and which require explicit subclassing. Also we might clarify what "abstract methods" and "mixin methods" mean in the table at the top. In the case of `Sequence` one can just implement two abstract methods and the other will behave in a "coordinated way". Then, simple purely abstract classes (called "One-trick ponies" in the source code) support structural checks.
> The collections.abc — Abstract Base Classes for Containers documentation says:
>> This module provides abstract base classes that can be used to test whether a class provides a particular interface; for example, whether it is hashable or whether it is a mapping.
Btw, Mapping also doesn't support structural checks, so the docs are quite outdated.
This looks like a duplicate of issue23864 and issue25737.
I would propose to keep this one open as a superseding and close the latter (assuming we are not going to make all classes protocols, we I think we really shouldn't, and instead we should improve the docs).
Wait, why should #25737 be closed? This bug is a docs issue; collections.abc shouldn't claim that all the ABCs do duck-typing checks since Sequence doesn't. But #25737 is specific: array.array *should* be registered as a Sequence, but isn't; that requires a code fix (to make array perform the registration), not a doc fix. | https://bugs.python.org/issue35190 | CC-MAIN-2021-21 | refinedweb | 741 | 54.52 |
Next.js provides server-side rendering for React applications. In this post, we will learn how to translate the text in a Next.js app by using
next-translate.
Before we proceed ensure you have the following installed on your system:
First, we need to create a project. We will do this by using the
create-next-app that is provided by the NextJS team.
In terminal type :
npx create-next-app
This will run an interactive prompt that will ask for the project name. You can name it whatever you like. For the sake of this post, we named ours
next-translate. It will also install all the required dependencies for the project to work. After that go inside the newly created project and run
yarn dev command. After that visit
localhost:3000 and you will see the starter page template that looks like this.
We don't need these components and pages from the starter template so now you'll need to delete the
styles/Home.module.css file, and
api directory that can be found inside of
pages. Open up
pages/index.js, delete everything from there, and paste this
const Home = () => { return ( <h1>Home</h1> ) } export default Home
We will also have an
about page so let's create one now.
const About = () => { return ( <h1>About</h1> ) } export default About
After getting this done we need to install a library for translating our pages. Open up a terminal in your project directory and type
yarn add next-translate IF everything is installed and working correctly we can move on to translating our app.
First, we need to create
next.config.js in the project root, and after doing that paste the code below. It is required for the plugin to be properly loaded.
const nextTranslate = require('next-translate') module.exports = nextTranslate()
After that, we need to add the
i18n.json configuration file in the project root. We need this so that
next-translate knows what locales are we going to have and which translation file is assigned to which page.
{ "locales": ["en", "me"], "defaultLocale": "en", "pages": { "/": ["home"], "/about": ["about"] } }
localesarray we specify all the locales that we want to use in our project (uses ISO format)
defaultLocaleis required so that
next-translateknows what is our default language (uses ISO format)
pageswe specify namespaces used in each page. To add namespaces to all pages use
(eg:{"*": "common"}`). You can also use regex to specify what locales are used in pages.
After creating configuration files we now need to specify namespaces. By default, they are specified inside the
/locales root directory.
├── en │ ├── about.json │ └── home.json └── me ├── about.json └── home.json
In these
.json files we will specify translations for all our pages. Note that file names match ones from the
i18n.json configuration that we wrote earlier. The basic content of
en/home.json looks like this
locales/en/home.json
{ "title": "Home Page", "description": "This is a home page description written in the English language.", "current-language": "Current locale is set to /{{language}}" }
You probably noticed
{{language}} syntax. This allows us to use variables in our translations if we have dynamic content. Using translation in the app is pretty simple and straightforward. First we import
useTranslation hook from
next-translate/useTranslation. Using that hook we then import namespace and function that will allow us to use translations from
.json files that we specified in
/locales directory. This is what our updated
index.js looks like.
import useTranslation from "next-translate/useTranslation" const Home = () => { const { t, lang } = useTranslation("home") const title = t("title") const description = t("description") const language = t("language", { language: lang }) return ( <> <h1>{title}</h1> <h4>{description}</h4> <p>{language}</p> </> ) } export default Home
Let's explain line by line what is happening here.
By using the
useTranslation hook we got access to 2 variables,
t, and
lang.
t is used for translating, and in
lang we have access to the currently active locale.
By adding a parameter to the
useTranslation hook we are specifying the default namespace for that page.
That parameter is optional since the
next-translate plugin will load only the namespace that the page
needs. It does so by reading the
i18n.json configuration that we created in the
root directory.
t("title") will load translation from
/locales/(en/me)/home.json file.
We can then assign it to a variable and use it on the page.
By using
t("language", { language: lang }) we are loading translation that is assigned to
language,
while also passing variable to it. It will return as a translation with a variable added to it.
From version
10 of NextJS
Internationalized Routing is supported by default, which means that we can load different locales without using external libraries.
Let's say that you have 2 different locales
en and
me. We need to give the user an option to switch to a different locale if he/she wants to. We can achieve this easily by using the
Link component from
next/link.
In NextJS
Link component is used for client-side routing, and if we want to send the user to another page we
can use this code snippet
import Link from "next/link"; <Link href="/about"> <a>About</a> </Link>
but if we want to send the user to the
/about page with a different locale we can pass the
locale prop to
Link
component like this
<Link href="/about" locale="en"> <a>About</a> </Link>
This also means that
next-translate will automatically read that locale and serve translated content
without any additional checks.
As we can see, translation in NextJS is convenient, easy to set-up, and use. You can find the code by clicking here. It is a GitHub repository with the code from this article that you can use and modify. The project in this repository contains basic styling and routing.
If that is the case, always know that you can shoot us an email or give us a call, as we don't like leaving things in the air.Contact Us | https://netboxify.com/blog/translating-your-next-js-application/ | CC-MAIN-2021-17 | refinedweb | 1,011 | 65.62 |
What’s New?
We’ve updated the four parts of this blog series and versioned the code along with it to include the following new technology components.
Jenkins Plugin Kubernetes Continuous Deploy has been added to deployments.
Kubernetes RBAC and serviceaccounts are being used by applications to interact with the cluster.
We are now introducing and using Helm for a deployment (specifically for the deployment of the etcd-operator in part 3)
All versions of the main tools and technologies have been upgraded and locked
Fixed bugs, refactored K8s manifests and refactored applications’ code
We are now providing Dockerfile specs for socat registry and Jenkins
We’ve improved all instructions in the blog post and included a number of informational text boxes
The software industry is rapidly seeing the value of using containers as a way to ease development, deployment, and environment orchestration for app developers..
Install Docker
Docker is one of the most widely used container technologies and works directly with Kubernetes.
Install Docker on Linux
To quickly install Docker on Ubuntu 16.04 or higher, open a terminal and enter the following commands (see the Linux installation instructions for other distributions):
sudo apt-get update curl -fsSL |:
# Display the Docker version docker version # Pull and run the Hello-World image from Docker Hub docker run hello-world # Pull and run the Busybox image from Docker Hub docker run busybox echo "hello, you've run busybox" # View a list of containers that have run docker ps -a
For more on Docker, see Docker Getting Started. For a complete listing of commands, see The Docker Commands.
Install Minikube and Kubectl
Minikube is a single-node Kubernetes cluster that makes it easy to run Kubernetes locally on your computer. We’ll use Minikube as the primary Kubernetes cluster to run our application on. Kubectl is a command line interface (CLI) for Kubernetes and the way we will interface with our cluster. .
Install Kubectl
The last piece of the puzzle is to install kubectl so we can talk to our Kubernetes node. Use the commands below, or go to the kubectl install page./
Install Helm
Helm is a package manager for Kubernetes. It allows you to deploy Helm Charts (or packages) onto a K8s cluster with all the resources and dependencies needed for the application. We will use it a bit later in Part 3, and highlight how powerful Helm charts are.
On Linux or macOS, install Helm with the following command.
curl > get_helm.sh; chmod 700 get_helm.sh; ./get_helm.sh. Within a chosen directory, clone your newly forked repository.
git clone
d. Change directories into the newly cloned repo.
Clear out Minikube
Let’s get rid of any leftovers from previous experiments you might have conducted with Minikube. Enter the following terminal command:
minikube stop; minikube delete; sudo rm -rf ~/.minikube; sudo rm -rf ~/.kub
Run a Test Pod
Now we’re ready to test out Minikube by running a Pod based on a public image on Docker Hub.
Inspect the pods in the cluster. You should see the add-ons heapster, influxdb-grafana, and nginx-ingress-controller.
kubectl get pods --all-namespaces
3. View the Minikube Dashboard in your default web browser. Minikube Dashboard is a UI for managing deployments. You may have to refresh the web browser if you don’t see the dashboard right away.
minikube service kubernetes-dashboard --namespace kube-system
4. Deploy the public nginx image from DockerHub into a pod. Nginx is an open source web server that will automatically download from Docker Hub if it’s not available locally.
kubectl run nginx --image nginx --port 80
After running the command, you should be able to see nginx under Deployments in the Minikube Dashboard with Heapster graphs. (If you don’t see the graphs, just wait a few minutes.)
5. Create a K8s service for deployment. This will expose the nginx pod so you can access it with a web browser.
kubectl expose deployment nginx --type NodePort --port 80
6. The following command will launch a web browser to test the service. The nginx welcome page displays, which means the service is up and running. Nice work!
minikube service nginx
7. Delete the nginx deployment and service you created.
kubectl delete service nginx kubectl delete deployment nginx
Create a Local Image Registry
We previously.
8. From the root directory of the cloned repository, set up the cluster registry by applying a .yaml manifest file.
kubectl apply -f manifests/registry.yaml
9. Wait for the registry to finish deploying using the following command. Note that this may take several minutes.
kubectl rollout status deployments/registry
10. View the registry user interface in a web browser. Right now it’s empty, but you’re about to change that.
minikube service registry-ui
11. Let’s make a change to an HTML file in the cloned project. Open the /applications/hello-kenzan/index.html file in your favorite text editor, or run the command below to open it in the nano text editor.
nano applications/hello-kenzan/index.html
Change some text inside one of the <p> tags. For example, change “Hello from Kenzan!” to “Hello from Me!”. When you’re done, save the file. (In nano, press Ctrl+X to close the file, type Y to confirm the filename, and press Enter to write the changes to the file.)
12. Now let’s build an image, giving it a special name that points to our local cluster registry.
docker build -t 127.0.0.1:30400/hello-kenzan:latest -f applications/hello-kenzan/Dockerfile applications/hello-kenzan
First, build the image for our proxy container:
docker build -t socat-registry -f applications/socat/Dockerfile applications/socat
14. Now run the proxy container from the newly created image. (Note that you may see some errors; this is normal as the commands are first making sure there are no previous instances running.)
docker stop socat-registry; docker rm socat-registry; docker run -d -e "REG_IP=`minikube ip`" -e "REG_PORT=30400" --name socat-registry -p 30400:5000 socat-registry
15. With our proxy container up and running, we can now push our hello-kenzan image to the local repository.
docker push 127.0.0.1:30400/hello-kenzan:latest
Refresh the browser window with the registry UI and you’ll see the image has appeared.
16. The proxy’s work is done for now, so you can go ahead and stop it.
docker stop socat-registry
17. With the image in our cluster registry, the last thing to do is apply the manifest to create and deploy the hello-kenzan pod based on the image.
kubectl apply -f applications/hello-kenzan/k8s/manual-deployment.yaml
18. Launch a web browser and view the service.
minikube service hello-kenzan
Notice the change you made to the index.html file. That change was baked into the image when you built it and then was pushed to the registry. Pretty cool!
19. Delete the hello-kenzan deployment and service you created.
kubectl delete service hello-kenzan kubectl delete deployment hello-kenzan
We are going to keep the registry deployment in our cluster as we will need it for the next few parts in our series.
If you’re done working in Minikube for now, you can go ahead and stop the cluster by entering the following command:
minikube stop
Up Next
In Part 2 of the series,.. | https://www.linux.com/tutorials/set-cicd-pipeline-kubernetes-part-1-overview/ | CC-MAIN-2019-47 | refinedweb | 1,234 | 65.42 |
i18n_screwdriver
Translating applications is often a pain in the ass. The problem with rails i18n is that you have to use keys for every string to translate. That is one too many abstraction layers - I love the gettext syntax but I want to stick to the rails standard libraries. Therefor I created this small toolbox.
Installation
Just include the screwdriver gem in your Bundler Gemfile
gem 'i18n_screwdriver'
Then run the generator that copies the translation rake task to your application task dir.
rails g screwdriver
Usage
Set these constants to make i18n screwdriver aware of the languages you are using
I18n.default_locale I18n.available_locales
In your views, helpers and controllers use the convenient underscore helper method for all your translations
_("your translation")
Starting with version 6.0 you can also use symbols as keys
_(:my_long_text)
Starting with version 7.0 we added namespaces. A translation in the form of _(“User|Name”) will use the full string as a key but only display the part after the pipe, so “Name”. This is useful if you want to have text translated differently according to the context in some languages but have it the same in the source language. For example “User|Name” (in German “Benutzername”) and “Account|Name” (in German “Accountname”).
Variable interpolation works as for normal strings
_("Hello %{name}!") % {name: "Liah"}
For awesome support for links inside translations you can use this syntax, which uses the normal rails view/ route helpers internally
_("Please <<click here>> for more details or visit <<this link>> to continue."){ [@item, ""] } _("Open this <<fancy link>> in new window or visit <<this link>> to continue."){ [[@item, target: "_blank"], ""] }
When you are done you have 2 helper rake tasks. The first one scans all your views, controllers and helpers for translations. It removes unused translation strings and creates an application.<lang>.yml file for each of your I18n.available_locales.
rake i18n:update
The second one lets you translate your application.<lang>.yml file line by line. Of course you can edit the application.<lang>.yml file itself - but dont do that for your default language file. It gets recreated everytime you run the tasks - edit those translations in your views e.g. itself.
TRANSLATE=en rake i18n:translate
Test Helpers
In your tests (functionals and integration) you can use the same translation helper
_("your translation")
Next steps
also recognize model validation error messages
DRY the code
test more (= test at all)
use ruby_parser instead of regex
support interpolation like the following (take care about naming - could be different in other languages)
_(“my name is %name and I am living in %location”, :name => @name, :location => @location)
Contributing to i18n_screwdriver - 2013 Tobias Miesel & Corin Langosch. Released unter the MIT license. | https://www.rubydoc.info/gems/i18n_screwdriver/7.5 | CC-MAIN-2019-18 | refinedweb | 457 | 63.09 |
Technology has been growing very fastly from year to year, and we will see new versions in your treasured programming language like Java, Spring Boot2, etc. From the last couple of years, new versions of programming are realised for every six months in the market. While I started I thought Java 9 is new before I can complete the Java 9, Java 10, Java 11 is released.
So, the new versions are coming fast with engaging features like GC improvement, API enhancements, Thread Local handshake, var with local variables and many more. From last couple of years developers are not up to date with recent tools of a Javascript framework like React and Angular and Git programming, recent changes on integration and unit testing and a new release of popular frameworks like spring boot, spring and spring security.
10. Jira
Atlassian Jira is an essential tool in the modern world of Agile development. It is used for project management, bug tracking and issue tracking. If your company follows Agile methodology development like Scrum & Sprint, then you should know about Jira. It permits you to track the progress of your software and make Spring cycles for software development.
If you desire to become a Scrum Master, I strongly intimate you learn Jira Certification with Real-time examples. Undoubtedly Atlassian Jira is the best tool for Agile practitioner, if you want to become a Master in Agile, then take a look of Agile Courses.
9. Linux
Linux is an open source & community developed operating system for computers, embedded devices, mobile devices, mainframes and servers. It collaborates with all major computing platforms like x86 support Linux, ARM and SPARC. Most of the developers are like to do their work and create anything new concepts in Linux. The major features for choosing the Linux is stability, compatibility, power and flexibility.
8. Gradle
Gradle is other open source automation tool that uses the most exceptional ideas of Apache Maven and Apache Ant and driving it into a next level. It is a default build tool for Android, and it introduces the Domain Specific Language(DSL) in place of XML used by Maven for reporting the project configuration. According to our need, it makes it easier to configure project dependencies and its customization.
Most of the developers are chosen Gradle over Maven and Ant, because of its features like flexibility, control of Ant, Ivy dependency management, Maven plugins, convention over configuration and it uses Groovy DSL this formulates it is the most exceptional build tool for Java projects.
7. Spock
Spock is a Java and Groovy testing and specification framework. Its main aim is to become a reliable replacement to the traditional JUnit stack. Groovy is a language based on JVM, and it smoothly incorporates with Java, and it also supports some other languages such as dynamic and metaprogramming. By utilizing of Groovy, Spock presents expensive and new ways of testing in our java projects, which are not possible with your ordinary Java code
6. Maven
The developers who are having more than three years experience are familiar with Maven, but if the developers newer with 1-2 years experience then Maven tool is perfect for learning. Maven is a build, dependency management tool and project management tool. The following snippet displays a maven dependency:
<dependency> <group>org.spockframework</group> <artifact>spock-core</artifact> <ver>1.0-groovy-2.4</ver> <scope>Mindmajix</scope> </dependency> <dependency> <group>org.codehaus.groovy</group> <artifact>groovy-all</artifact> <ver>2.4.7</ver> <scope>test</scope> </dependency>
According to POM concept, it is used to manage documentation information, reporting and projects build. Before Maven we can use a bunch of third party libraries in your Java project for controlling the JAR files and their dependencies, Maven solves it by downloading the JAR files automatically.
5. Docker
Present days most of IT professionals prefer Docker for automating the application deployment on cloud server as well physical server. It is an open source tool, and it allows admins, developers to build and run the distributed applications on cloud, data centre VMs and laptops etc. Docker supports collaboration with Linux, Cloud and Windows and various companies focusing on IT automation.
4. Apache Groovy
Apache Groovy is an object-oriented programming language for the Java platform. It is one of the most important languages for Java developers because it's supplemented Java language. By using Groovy language in Java project, we can do much more. We could use groovy by writing test scripts, build scripts and use Spock and Gradle framework. Groovy is a dynamic language with similar features of Ruby, Small talk, Python and Perl and it prolongs the Java with supplying of short and robust syntax. Let see the Java vs Groovy in the following example, first with Java:
// 18 lines with Java public class Mindmajix { private string name; public void setName(String name) { this.name = name; } public string sayHello(){ Return "Hello" + name + "."; } public static void main (string[] args) { Mindmajix hw = new Mindmajix(); Hw.setName("Bruno"); system.out.printin(hw.sayHello()); } }
And Groovy:
// In Groovy 4 lines Class Mindmajix{ Def sayHello = name{name.> "Hello ${name}"} } Print new Mindmajix(). sayHello.call("Bruno")
3. Selenium
Selenium tool is one of the most excellent Testing frameworks for web-applications. It provides a tool for creating test scenarios without require to learn a scripting language. With this feature, Java developers test their JSP and HTML files with the help of selenium.
Selenium provides a different kind of tools and libraries for browser automation. If you are working on testing space or automation, then selenium is a need for you. If you are unable to decide what to learn in selenium, then select Selenium with Java is very good for Java developers.
2. Jenkins
Jenkins is one of the open source automation server scripted tools in Java. It serves to automate the humanoid part of the software development process, e.g. uploading aircraft on the remote and local repository, running unit and integration test, compiling projects and document generation.
Jenkins is one of the best-known tools for continuous implementing and integration in your project. If you want to start or improve your Jenkins skills, then achieving Jenkins Certification is highly beneficial and also convenient.
1. Git
Git and Github have been around some time, while in the past, developers are using Git with eclipse but now most of the developers are using the Git with a command line. Previously developers are not much familiar with Git, the projects directly downloaded from Github and ran in eclipse, but now developers are using Git commands for handling errors and reverting changes. From right now, most companies emigre their projects from CVS, SVN to Git, now it's time to learn and master in Git.
That all over the list of tools Java developers should learn in 2019. I have discovered a strong relationship between tools and good programmers and they have good knowledge of their tools compared to ordinary programmers. If you are serious in your career and try to improve your understanding of tools, then spend some time to learn the above-discussed tools. Finally the more expertise you gain on different tools, then the more knowledgeable you become.
Become a more social person | https://ourcodeworld.com/articles/read/863/top-10-tools-java-programmers-should-learn-in-2019 | CC-MAIN-2019-18 | refinedweb | 1,208 | 52.8 |
WordPress is the most popular QuickStart on OpenShift Hub. Here are some tips to make the most of it!
Tip 1: Use PHP 5.4 and MySQL 5.5
This is an easy win if you’re on PHP 5.3 or MySQL 5.1. The newer versions of PHP and MySQL came with bug fixes, new features, and performance enhancements.
For new deployments, make sure you use PHP 5.4 and MySQL 5.5. Don’t get started yet! We began here to lead into tip #2.
Tip 2: Move your Database to a Separate Gear
Another easy win. It’s not immediately obvious how to do this in OpenShift Online, but it’s very easy once you’re aware it’s possible.
The solution: deploy WordPress as a ‘scalable’ application with PHP set to scale to a maximum of 1 gear. OpenShift will run PHP on one gear and MySQL on a separate gear. Your database will have a separate set of resources (memory, storage, and CPU).
For new deployments from the web console, select the option to “Scale with web traffic”:
IMPORTANT: Make sure you update your scaling settings after your app is created! Click on your app, then click the link under ‘Scales’ to adjust your scaling settings. Set PHP to scale to a max of 1 gear.
For new deployments from the command line:
$ rhc create-app <app name> php-5.4 mysql-5.5 --from-code= -s $ rhc cartridge scale php -a <app name> --min 1 --max 1
Tip 3: Upgrade to Bronze to Disable Idling (it’s free)
If you live in the US, Canada, Europe, or Israel and you haven’t upgraded to the OpenShift Bronze Plan you’re missing out on a completely free upgrade. ‘Upgrading’ to the OpenShift Online Bronze Plan disables application idling for any gears running on your account. And, I can’t re-iterate this enough, it’s FREE. You get all the benefits of the Free Plan, but with application idling disabled, support for private SSL certificates, and team management with the OPTION to pay to use extra gears and storage.
If this isn’t absolutely clear on our pricing or plan comparison pages please let me know in the comments! If you live outside of our supported regions for OpenShift Online Bronze/Silver plans, help us help you by filling out the Geo Request Form to let us know you’re interested.
Tip 4: Enable Hot Deployment
If you’re using source control to manage your plugins and themes, you can enable hot deployment to prevent your WordPress site from having downtime when you push your changes. Learn how.
Tip 5: Install the W3 Total Cache Plugin
Using the W3 Total Cache plugin with your WordPress installation will significantly speed up your site. Install it from the WordPress admin panel or download it from wordpress.org and check it in through source control.
Update: I recommend enabling both page and database caching in the W3 Total Cache general settings menu with ‘Opcode: Alternative PHP Cache (APC)’ as the caching method for both.
Tip 6: Use CloudFlare
Have a custom domain name for your WordPress site? Route your custom domain through CloudFlare’s DNS service.
CloudFlare will automatically detect images and static assets on your site and serve them to your visitors using their global CDN. CloudFlare also offers free SSL for custom domains. If you haven’t heard of CloudFlare, check out their features page.
If you followed tip #5, CloudFlare is provided as a W3 Total Cache extension. Setup instructions can be found here.
If you aren’t planning to use W3 Total Cache, follow this blog post.
Tip 7: Use SendGrid for Email Notifications
We recommend replacing the built-in WordPress mail system with SendGrid for improved deliverability and enhanced reporting. There’s even a note about this in our latest version of the WordPress QuickStart in the wp-config file.
Check out the Developer Portal article to learn how to install SendGrid for WordPress on OpenShift.
Tip 8: Add the WP Optimize Plugin
WordPress can generate a lot of waste in your database. Clean it up with WP Optimize. Install it from the WordPress admin panel or download it from wordpress.org and check it in through source control.
Tip 9: Enable ‘Development’ Mode During Development
The latest version of our WordPress QuickStart offers support for advanced debugging. Learn how to enable ‘development’ mode.
Tip 10: Throw Some Money at It
Need to support more traffic? Do you have resource-intensive plugins or themes? Step up to a larger gear size for PHP, your database, or both. We run this blog using the WordPress QuickStart with Large gears – one for the database and another for PHP.
Is your user base largely in Europe? Switch over to any of our Production gears (Small.highcpu, Medium, and Large gears) and re-deploy your site closer to your users in our European hosting region. Learn how.
Tip 11: Backup WordPress with OpenShift Backup Server
If you used tip #2, this step will require you to pay for an extra gear on your account. Still, it’s worth mentioning if you take your application seriously.
Use the OpenShift Backup Server to create one-time or scheduled backups for your WordPress site. It’s the easiest, most complete way to backup your OpenShift applications using OpenShift’s built-in
snapshot system for backup/restore.
Tip 12: Risk it with Scaling (experts only)
I wouldn’t recommend scaling the current WordPress QuickStart (beyond separating the database from tip #2 or using larger gears from tip #10). For the more daring and hopefully expert users out there, we plan on releasing an experimental ‘Scalable WordPress’ QuickStart available on the OpenShift Hub shortly. There are quite a few downsides to scaling WordPress without a shared file system, namely that plugins, themes, and updates will have to be managed through source control. Nevertheless, we can try to create a workable solution…together :)
Have your own tips for using WordPress on OpenShift? Share your tips in the comments!
44 Responses to “12 Tips for Hosting WordPress on OpenShift - Archived”
John Poelstra
Great post! Thanks for all the WordPress tips. Curious what kind of improvements you’ve seen with W3 Total Cache. I disabled it on some some sites at another shared hosting provider and actually saw an improvement.
OpenShift
When we enabled W3 Total Cache on this blog with fairly conservative settings the average “Time spent downloading a page” reported in Google Webmaster Tools was cut in half. I strongly recommend using “Opcode: Alternative PHP Cache (APC)” for both page and database caching.
Fahad M Rafiq
Is Varnish Compatible with WordPress. What About Nginx, memcached solution?
Christopher Grello
Fahad,
Varnish is indeed compatible with WordPress, though implementing Varnish in OpenShift is a little more complicated than in an IaaS environment.
Fahad M Rafiq
Thanks for the clearing this doubt. I think you should see Cloudways WordPress solution as they are providing a WordPress solution that comes with a special recipe of varnish, nginx, apache and memcache. Having said that its a single click solution over multiple cloud or IaaS providers including DigitalOcean, GCE and AWS.
OpenShift
For anyone looking to run Varnish, check out:
For Nginx the HHVM QuickStart is a great starting point:
Jennifer Galas
I prefer WP Super Cache. Can I expect it to work as well as W3 with OpenShift?
OpenShift
WP Super Cache should work fine with OpenShift. W3 Total Cache is a more modern approach to caching that takes advantage of some features OpenShift offers that you wont find in shared hosting environments (like in-memory caching with APC) so I wanted to make sure to point people in that direction.
Stefan van Oirschot
“If this isn’t absolutely clear on our pricing or plan comparison pages please let me know in the comments!”
A little remark. When comparing the free with the bronze plan, the free plan shows “3 small gears (free)”. This “free” note is not available in the “Bronze plan specs”. So do you pay the 0.02 cents as of the 1st gear or just from the 4th gear and up? If so, the Free tier is nice for some really “Free” testing up-to 3 gears.
OpenShift
All plans include 3 small gears for free. Just curious – where were you looking when comparing the plans?
Stefan van Oirschot
I’ve upgraded to the “Bronze” so i’m not entirely sure about the exact text but….
My steps:
Immediately after logging in to OpenShift online I clicked “Upgrade my account” (or something like this) just besides my e-mail address on the top of the screen.
A new screen with the Free, Bronze and Silver plans compared appears.
Now knowing I read the “specs” wrong I immediately know where I made the mistake. I read the “Gear sizes” field in the Bronze column and saw a price for the Small gear compared to No price in the Free column. I totally “ignored” the part where it says: “Included(!) gears” as in, for free.
Thank you for your support.
OpenShift
Got it – yeah that’s definitely not as clear as it could be. Thanks for your feedback! We’re working on an update for that page and a few others in the interface now to make this more clear :)
Mark Berry
I was looking forward to trying WordPress on OpenShift, moving from a shared host. I have no interest in maintaining a local LAMP server and using git; I just want to manage it online as I always have. But after deploying the quick-start, I’ve discovered that the structure of app-root/data is non-standard for WordPress, with plugins, themes, and uploads at the root level and not under wp-content. So I won’t be able to bulk-restore the current site, and I guess I’ll have lots of changes to make since all photos etc. will have changed paths?
Is there a guide for migrating existing sites? I’ve seen several references to but that no longer exists.
Offirmo
Completely agree. The strange file structure breaks a lot of plugins, most importantly backup/restore plugins used to move the site between dev and prod. This is a no go. Too bad…
Jacob Lucky
Just use OpenShift’s built-in backup and restore features instead of a plugin. See tip #11.
Offirmo
As I said in my comment, backup/restore is also a way to move the WP site from development (my machine) to production (openshift ?). OpenShift’s built-in backup cannot provide that.
Jacob Lucky
Got it – I assume you’ve tried the plugins and they didn’t work? Let me know what plugins you’re using and I’ll see if I can come up with anything.
Lee Wasilenko
I was hoping for a workflow like this as well. My team and I want to make changes locally in our dev environment and then commit and push them to the gear when they’re ready to go live, just like we do with our application code. Will this ever be possible on OpenShift?
Jacob Lucky
Paths will not need to be changed. The deploy process creates symlinks to map the default WordPress file locations to the new locations in OpenShift’s persistent storage directory. I’ll see if I can put a migration guide together this week, but really the README.md sums things up for the most part:
Jacob Lucky
You’re storing all of your data in ephemeral storage. Any changes you make in production, such as changes made via the WordPress admin panel (WordPress updates, plugins, .htaccess modifications, images, etc), will be discarded on your next git push. That’s the reason for the awkward file structure we’re currently using. All of the themes/plugins are copied over to persistent storage ($OPENSHIFT_DATA_DIR) on deployment. Look for a much friendlier WordPress file structure when OpenShift 3 is released – check out openshift.org for details on OpenShift 3 :)
Mark Berry
Jacob, thanks for your reply and for the explanation of the file structure. As I mentioned, I don’t have or want a local copy of my site, and I don’t use git or the “deploy” process. So far I haven’t needed the OpenShift command-line tools. All I did was restore my site and set up a cron script to back up the site and database as usual.
Maybe this approach makes me an odd duck in the OpenShift world, but I have to think that 95% of WordPress sites run solely on the host. Perhaps OpenShift could develop a simple, non-git, “host-only” WordPress option for those of us who simply want to move from a shared host to PaaS.
Guillermo Conde
Great post.
I have a WordPress app deployed 5 month ago whit php 5.3 and Mysql 5.1. When I try to upgrade as you say in Tip 1 or Tip 2 the system gives me an error. Can you help me?
I tried> rhc create-app wp-new php-5.4 mysql-5.5 –from-app wp-old
The error was >
Do not specify cartridges when creating an app based on another one. All
cartridges will be copied from the original app.
Usage: rhc app-create [… ] [… VARIABLE=VALUE]
[-n namespace]
Pass ‘–help’ to see the full list of options
Jacob Lucky
Good catch. The post has been updated – follow the instructions in tip #2.
Guillermo Conde
Thanks.
I’m trying the tip2 another time, but I get several errors.
In windows I get an “out of memory” and in linux I get a “timeout”.
… Work in progress …
:)
Guillermo Conde
The next problem that I found is:
– Restore a little snapshot in a non scaling app works.
– Restore a little snapshot in a sclaling app (wordpress or php 5.4+myslq 5.5) doesn’t work. It seems that the problem is in mysql, it doesn’t import the data.
Jacob Lucky
Interesting – are you trying to move from a non-scaled application to a scaled application? I just ran the steps from tip #2 with a scaled application and everything ran fine. I created a PHP 5.3 / MySQL 5.1 scaled app and migrated to a scaled PHP 5.4 / MySQL 5.5 app without any issues:
PHP 5.3:
PHP 5.4:
Mark Berry
It’s not clear if SQL data is exported/imported as part of the snapshot creation and restore. (See the unanswered.) What happens if you add a new WordPress post before upgrading?
Jacob Lucky
The database is copied over (along with my username and password). If in doubt, you can find the database backup within the {app-name}.tar.gz at: /app-root/data/mysql-5.1.tar.gz
Jacob Lucky
Alright – I see the combinations that don’t work. When migrating from a non-scaled to a scaled application (or vice versa), the database will not be imported during the snapshot restore. I’ll post a workaround for this in a second. The database does get backed up during the snapshot save, so restoring shouldn’t be a big deal.
Guillermo Conde
Yes, that is what I am trying. Move a non-scaled wordpress to an scale app.
Alhikmah University
My website simply DISAPPEARED!!!
I followed everything to the letter and to my surprise after getting “DONE” report while restoring, my website still displays the default page and NOT the restored site.
Julian Puerta
I think this is due to changing the scale from “Maximum : All available” to enything else while using a QuickStart WordPress installation.
Tony Thijs
Using cloudflare, which IP adress should I register in the A record at my domain registrar? What if I cannot assign a new DNS at the registrars site
neotec
Thanks for the great post! But I have two questions that I couldn’t find an official answer from OpenShift:
1) For hosting WordPress on OpenShift and use OpenShift’s modified WordPress code structure, how do I set up a local development environment? For example, after I’ve cloned the repository to my local machine, there’s no WordPress core code at all. How should I set up the complete code locally so that I can run WordPress locally? Is there a step-by-step tutorial for that?
2) If I don’t run WordPress locally, but only modify code locally and push it to OpenShift, how should I upgrade the WordPress core code when there’s a new release? I would see the release notice in my Admin control panel, but I guess I shouldn’t click and update code from there, right (because the changes wouldn’t be committed to the repo)? What is the correct way to do that (especially whenI don’t have a complete wordpress core code in my local repo)?
Thanks!
Jacob Lucky
I’ll reply back if I come up with anything reasonable for #1 (possibly involving symlinks from a separate WordPress directory and port forwarding for the database). For #2, simply use the admin panel to upgrade WordPress since we’re not storing the WordPress Core files in the git repo.
Deepak
Hi, I just upgraded from free plan to bronze because of gear idling, but my intention is to stay free by limiting myself to 3 gears. It is not clear from the documentation if I will get charged if I use ssl for my custom domain on the bronze plan?
Jacob Lucky
There is no cost for the use of SSL. Check out for more information on plans and pricing.
John Crooks.
Kirtan
Exactly. This also doesn’t break any plugins and works smoothly. For the users migrating from shared hosting this can be difficult to understand and using git for wordpress — I am still not getting it.
It is very useful to just simply put wordpress as it is with the php instance. Thanks for the wonderful blog post. Helped me to save my bunch of time with the troubleshooting.
Tom
Thanks for the post. But how can I add the phpMyadmin to this application, I need to change something in the database but I cannot do it here without the phpMyAdmin.
Jacob Lucky
When you move your database to a separate gear phpMyAdmin can no longer be installed.
Fortunately, OpenShift still makes connecting to your database easy. I use Sequel Pro or MySQL Workbench on my local machine to manage my databases on OpenShift. Install the OpenShift command line tools (RHC) locally, run `rhc setup` to get the tools setup, and then run `rhc port-forward -a ` to setup port forwarding for your application. The port-forward command returns a local IP Address and Port you can use to connect to your database. You can get the name of your database, username, and password from the OpenShift web console.
Eugene Pik
It seems the option #3 (Upgrade to Bronze to Disable Idling) is no more free. Is there per CPU hour billing, or I do not understand the pricing correctly?
Roxy Chan
I have been hosting my first WP site on Open shift. It gave me quite good learning process. Thanks for sharing these tips was useful to me.
Chirag
Thanks for such a nice post.
I have a small doubt regarding #6 after adding the two cname
what about the attribute “A” do we need to remove the attribute “A” in DNs settings as it expect the IP address only and in case of openshift we don’t have any static IP address.
Also in openshift application what should be used as Alias one with www or without www | https://blog.openshift.com/12-tips-for-hosting-wordpress-on-openshift/ | CC-MAIN-2018-22 | refinedweb | 3,290 | 73.17 |
Implementing transformers
This page describes how to implement your own Cocoon transformer. See WritingPipelineComponents for a general introduction on SAX pipelines.
The diagram below shows the class and interface hierarchy for transformers.
Transformer class diagram
Note that many interfaces shown in this diagram don't specify new methods but just combine other interfaces. As you can see, a Cocoon Transformer is an XMLPipe. An XMLPipe in itself an XMLConsumer and an XMLProducer. An XMLConsumer is basically a SAX ContentHandler and LexicalHandler combined. XMLProducer itself only defines one method, setConsumer, which will be called by Cocoon when it sets up the pipeline. A Transformer is also a SitemapModelComponent. This interface defines one method, setup, which provides the transformer with access to the current runtime environment (sitemap-defined parameters; a so called "object model" containing among others the request and response objects; a sourceresolver for resolving URI's; and the value specified in the 'src' attribute in the sitemap).
Since the ContentHandler and the LexicalHandler interfaces contain quite some methods, there is an AbstractTransformer which has already implemented a default behaviour for all these methods. The default behaviour is to simply pass on the received SAX-events to the consumer, thus effectively implementing an identity transformation. The only method which is really unimplemented is the setup method.
Suppose now that we would like to create a transformer which changes all elements called "foo" to elements called "bar". The code below shows just such a transformer.
package yourpackage; import org.apache.cocoon.transformation.AbstractTransformer; import org.apache.cocoon.environment.SourceResolver; import org.apache.cocoon.ProcessingException; import org.apache.avalon.framework.parameters.Parameters; import org.xml.sax.SAXException; import org.xml.sax.Attributes; import java.util.Map; import java.io.IOException; public class FooToBarTransformer extends AbstractTransformer { public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par) throws ProcessingException, SAXException, IOException { } public void startElement(String namespaceURI, String localName, String qName, Attributes attributes) throws SAXException { if (namespaceURI.equals("") && localName.equals("foo")) super.startElement("", "bar", "bar", attributes); else super.startElement(namespaceURI, localName, qName, attributes); } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (namespaceURI.equals("") && localName.equals("foo")) super.endElement("", "bar", "bar"); else super.endElement(namespaceURI, localName, qName); } }
Make sure you understand the code above. Note that it is recommended to always write your transformers in a namespace-safe manner. In this example above only elements which are in no namespace will be changed, elements called "foo" in any other namespace will stay untouched.
To try out the transformer, you'll need to compile it. For this to succeed, you will need to put the Cocoon-jars in your classpath. The resulting class file should then be placed in a jar file, and this jar file should be placed in the WEB-INF/lib directory of your deployed Cocoon.
To use the new transformer in the sitemap, declare it as follows in the map:transformers section of the sitemap:
<map:transformer
and specify a simple pipeline such as:
<map:match <map:generate <map:transform <map:serialize </map:match>
For this to work, you will of course need to create a foo.xml file and place some foo-tags in it. And now you can try it out.
Further details on transformers
Each transformer is actually an Avalon component. Avalon is a component framework from the Apache Jakarta project, on which Cocoon is heavely based. Basically, it boils down to it that all components, and thus all transformers, are managed by a container (the "component manager"). By implementing certain interfaces, a component can specify how it should be handled by the container, and can get access to certain external resources such as a logger or other components (datasources, ...). If you're really serious about developing Cocoon-components, you should learn these Avalon-interfaces (contracts), which is described here.
One important thing to note is that if you extend your transformer from AbstractTransformer, it also implements the Recyclable interface, which in itself extends the Poolable interface. When a component implements this interface, the instances of this component will be pooled and reused. The important thing about this is that you will most probably need to reset the values of the instance variables of the transformer object between usages (if any). This is usualy done in the setup method.
One question I have is why is a simple transformer so much faster than a simple xslt script? I notice that the identity transform in xslt (Xalan) takes about 10 times longer than the same transformer in Java. Shouldn't it be I/O bound? Has anyone else noticed this?
Good question. The reason is simple: an XSLT transformer (at least Xalan and Saxon) will always build a complete data structure containing the contents of the incoming SAX-events. This not only consumes a lot of memory, but also takes a lot of time. This also happens when using Xalan in streaming mode (which only advantage is that the output could get faster down the pipeline, but is slower in the end since it creates an additional thread). So it is a good practice to always keep the number of XSLT transforms in a pipeline as low as possible, especially in situations where caching is not an option. -- BrunoDumon
XSLT also performs a lot of XPath expression evaluations which require traversing the input document tree, which adds some CPU cost. Simple transformers like the one above do their job "on the fly", but cannot restructure the document like XSLT can. An alternative to manual coding and XSLT could be STX, Streaming Transformations for XML that is maturing quickly and its Joost Java implementation (OpenSource, MPL). -- SylvainWallez
For those who were looking (I know I was) for information about writing a DOM-based transformer, here are some quick notes to get started: The class to extend is AbstractDOMTransformer. A DOM document will be built for you and the notify() function will be invoked upon completion. Afterward, the transform() function will be invoked. This function is the location to begin implementing your transformer. The DOM document built from the SAX data is passed in as an argument, and the final DOM document to be passed down the pipeline should be returned. Any corrections or "best practice" comments would be appreciated! -- WillDrewry | http://wiki.apache.org/cocoon/ImplementingTransformers | crawl-003 | refinedweb | 1,042 | 55.54 |
Blog for the .NET WCF and WF Teams.
To submit a nomination to the “Dublin” TAP:!
As you have probably noticed, the WCF Dev Center has changed quite a bit recently. If you are a returning visitor, you may be wondering where your favorite links went.
The driving principle behind the redesign is to better cater to the different audiences that visit our page.
In its previous format, the WCF Dev Center catered very well to the return visitor looking for fresh content. The various content feeds on the main page made it very easy to check back periodically and see new content.
However, our usage data shows that a lot of our traffic comes from first time visitors through search engines. Our redesign is an effort to present a friendlier face to those folks, and to help them find introductory materials.
The main page now has links to three main areas:
1) Get it: This page gives simple instructions for what you need to install to use WCF. It also gives links to additional WCF Tools that are available in the Windows SDK and how to download them.
2) Get Started: This page has a streamlined set of content that we feel is most useful for programmers just getting started with WCF. As part of this, we are introducing a new series of “Learning WCF Tutorials”.
3) Learn More: This page is the portal into all of the available learning resources and community content. If you miss the old site, you might want to just bookmark this page as it is now the “one-stop shop” for experienced WCF programmers.
There are also two feeds on the main page:
1) The “WCF Highlights” area where we will make important announcements such as Beta releases, important new content, and conference events.
2) The “What’s New” feed which will be a fast moving feed combining blog entries from the WCF Team Blog, syndicated MVP blogs, and the Social Network Bookmarking.
Please let us know what you think of the new design and make suggestions for any future improvements you’d like to see.
Last week we introduced the new Workflow Tracking features in .NET 4.0. In this post we’ll do a deep dive into tracking profiles and explain how to use them to track workflow execution in a flexible way.
Tracking Profile Overview
Tracking profiles let you subscribe to events that are emitted by the runtime when the state of a Workflow instance changes. Depending on your monitoring needs you may craft a profile that is very coarse, subscribing to a small set of high level state changes on a Workflow. On the other hand you may create a very granular profile whose output is rich enough to reconstruct the execution later. Tracking profiles can satisfy these extreme scenarios and anything in between.
Tracking profiles manifest themselves in one of two ways. You can create tracking profiles programmatically in .NET or configure them as XML elements in the <system.serviceModel> section of a standard .NET configuration file. This post covers configuration based profiles. Here is an example tracking profile in .NET 4.0 Beta 1:
<system.serviceModel>
…
<tracking>
<trackingProfile name="High_Level_Tracking_Profile">
<workflow>
<workflowInstanceQuery>
<states>
<state name="Started"/>
<state name="Completed"/>
</states>
</workflowInstanceQuery>
</workflow>
</trackingProfile>
</profiles>
</tracking>
</system.serviceModel>
Tracking Profile Structure
Tracking profiles are structured as declarative subscriptions to events, or tracking queries that let you “query” the Workflow Runtime for specific event records. There are a handful of query types that let you subscribe to different classes of events. Here are the most common query types that you can try out in .NET 4.0 Beta 1:
· WorkflowInstanceQuery – Use this to track Workflow instance lifecycle changes like Started and Completed.
· WorkflowInstanceQuery – Use this to track Workflow instance lifecycle changes like Started and Completed.
· ActivityQuery – Use this to track lifecycle changes of the activities that make up a Workflow instance. For example, you may want to keep track of every time the “Send E-Mail” activity completes within a Workflow instance.
· ActivityQuery – Use this to track lifecycle changes of the activities that make up a Workflow instance. For example, you may want to keep track of every time the “Send E-Mail” activity completes within a Workflow instance.
· FaultPropagationQuery – Use this to track the handling of faults that occur within an activity. This event occurs each time a FaultHandler processes a fault.
· FaultPropagationQuery – Use this to track the handling of faults that occur within an activity. This event occurs each time a FaultHandler processes a fault.
· UserTrackingQuery – Use this to track events that you define in your code activities. There will be a follow up to this post that shows you how to create user tracking records.
· UserTrackingQuery – Use this to track events that you define in your code activities. There will be a follow up to this post that shows you how to create user tracking records.
Variable Extractions
When tracking the execution of a Workflow it is often useful to extract data. This provides additional context when consuming the tracking records post execution. Tracking profiles make this easy. In .NET 4.0 you can extract variables from any activity in a Workflow. The following example activity query comes from the monitoring hands on lab that shipped with the WCF and WF samples for .NET 4.0 Beta 1. It shows how to extract the “StockSymbol” variable whenever the “GetStockPrice” activity completes.
<activityQueries>
<activityQuery activityName="GetStockPrice">
<states>
<state name="Closed"/>
</states>
<variableQueries>
<variableQuery variable="StockSymbol"/>
</variableQueries>
</activityQuery>
</activityQueries>
Annotations
Annotations in Workflow 4.0 let you arbitrarily tag tracking records with a value that can be configured after build time. For example, you might want several tracking records across several Workflows to be tagged with “Data Center” == “Contoso Data Center”. This makes it easy to find all records with this tag when querying tracking records later. To accomplish this, you would add an annotation to a tracking query like this:
<states>
<state name="Closed"/>
<annotations>
<annotation name="Data Center" value="Contoso Data Center"></annotation>
</annotations>
</activityQuery>
What’s Next
In the next post in the series, we will talk about the extensibility of Workflow tracking in .NET 4.0. This topic will dive into the following concepts:
· Programmatically emit your own tracking events by creating UserTrackingRecords.
· Programmatically emit your own tracking events by creating UserTrackingRecords.
· Programmatically consume events within the runtime by creating custom TrackingParticipants.
· Programmatically consume events within the runtime by creating custom TrackingParticipants.
· Programmatically create tracking profiles in .NET.
· Programmatically create tracking profiles in .NET.
We feel that learning by example is one of the easiest ways to get started with Windows Workflow Foundation (WF) and Windows Communication Foundation (WCF). In fact, we find that we often use code samples internally to get people from different feature teams all on the same page. Therefore, it seemed only natural to think that others outside of Microsoft would benefit from the same types of samples. We took these existing samples, cleaned them up and added more to fill in gaps to cover as much of the product as we could. The result was our current sample set: downloadable here and documented here.
With beta1, the product unit authored and shipped 88 new samples for WCF and WF 4. The samples themselves have been organized by type: Basic, Scenario and Application for WF and Basic, Scenario and Extensibility for WCF. Basic samples are samples that demonstrate basic usage of a specific feature. Think of these samples as the hello world of each feature. Scenario samples show the usage of a set of features used in tandem. They show specific use cases of our product and apply basic features to demonstrate common patterns. The extensibility section for WCF exists to conform to the 3.0 WCF sample layout in MSDN Library. Think of these samples as demonstrating ways to extend WCF beyond its built-in feature set. Application samples show how many patterns can be used together to provide an end-to-end solution to a common problem.
We see each type of sample fulfilling the needs of different learning and usage styles. For example, basic samples can be used to quickly familiarize yourself with specific features. Scenario samples can be used to see what we feel are common patterns for WF and WCF. These were common enough patterns that several scenario samples actually started as product code that was later move to a sample for one reason or another. Of the scenario samples, I’d like to specifically call out the WF Activity Library. This provides a number of activities that were not built into the product but we felt to could be used in many different applications (for example, there’s a SendMail activity, a Regex activity, a For Activity, and many more).
The WCF sample set, like the product changes, are additive. This means that most of the pre-4 WCF samples are still relevant. However, the samples currently shipped in the download linked to above are just for new features in Beta1. In Beta2, the samples download will also include most of these samples shipped with 3.0-3.5sp1. The new WCF samples include, Discovery, Event Tracing for Windows, Routing services, and more.
Look them over, let us know what you think by commenting on this post and responding to the WF and WCF code sample survey. We do take your feedback seriously. Need help with a particular scenario but couldn’t find a sample that demonstrated a similar pattern? Others are probably in the same boat – letting us know can help us make learning WF and WCF easier for you and others moving forward..
A sequential workflow executes a set of contained activities in sequential order. The Sequence activity in WF 4 allows you to model workflows in the sequential modeling style. A Sequence contains a collection of activities that are scheduled in the order in which they have been added to the collection. Hence, the order of execution of the activities is predictable.
You can add any activity to a Sequence – control flow procedural constructs like ForEach, If, Switch, While, DoWhile; or parallel constructs like Parallel and ParallelForEach to model parallel execution of logic; or any other activity we provide in the WF 4 activity palette (or your own custom activity or a third party activity).
The next figure shows a Vacation Approval workflow modeled as a sequential workflow using the Sequence activity and other activities. In this workflow, we first check if the employee has enough available days, wait for his manager approval, and finally update his vacation information in the company’s HR database. The activity highlighted in the orange box (Get Manager Approval) is actually a While activity (collapsed in the main Sequence) that executes another Sequence of activities (AskForApproval) while the approvedByManager variable value is False.
Workflows modeled using the sequential modeling style are easy to understand and author. They can be used to model simple to moderately complex processes. Since procedural activities have strong parity with procedural statements in imperative programming languages, you can use this type of workflows to model almost any type of process. Sequential workflows are also a good fit to model simple processes with no human interactions (e.g. services).
As the complexity of the process increases, the workflow will become more complex. In comparison to code, with workflows, you will get the benefit of visually looking at your process and visual debugging, however, you may want to factor out the logic into re-usable custom activities to improve the readability of large workflows.
Sequence is not a requirement to create workflows that use the sequential modeling style. As we will explain later in this post, any activity in WF 4 can be the root of a workflow. Therefore, we can create a workflow that does not contain a Sequence but still uses the sequential modeling style and procedural activities. In the figure below, we have a workflow that has as a ForEach as root activity that prints all the items in a list of strings with a length higher than 5.
Flowchart is a well known and intuitive paradigm to visually represent business processes. Business Analysts, Architects and Developers use often flowcharts as common language to express process definitions and flow of logic.
Since the release of WF 3, customers have given us feedback about what they like and don’t like. One common point of feedback from customers using WF3 was that “we want the simplicity of Sequence, Parallel, etc. but the flexibility of StateMachine.” When we dug deeper to get at the scenario behind this sentiment, we found that customers have a process (or a portion of a process) that is often quite sequential in nature but which requires “loopbacks” under certain circumstances (for some customers the circumstances are “exceptional” in nature while for other customers they are “expected” but it really doesn’t matter to this discussion). The FlowChart activity is new in WF 4 and it squarely addresses this (rather large) class of scenarios. Flowchart is a very powerful construct since it provides the simplicity of sequence plus the ability of looping back to a previous point of execution, which is quite common in real life business processes to simulate re-try of logic when handling external input.
A Flowchart contains a set of nodes and arcs. The nodes are FlowNodes – which contain activities or special common constructs such as a 2-way decision or a multi-way switch. The arcs describe potential execution paths through the nodes. The WF 4 Flowchart has a single path of execution; that is, it does not support split/join semantics that would enable multiple interleaved paths of execution.
The next figure shows a simplified recruiting process modeled using a Flowchart. In this case after a résumé is received, references are checked. If references are good, the process continues, otherwise the résumé is rejected. The next step verifies that the candidate skills are a good match for the position offered. If the candidate is a good match, then she will be offered a position. If she is not a good match for this position but interesting for future opportunities, the resume is saved in a database and a rejection letter is sent. Finally, if the candidate is not a good match, she is sent a rejection letter.
Flowchart modeling style is great to represent processes that are sequential in nature (with a single path of execution), but have loops to previous states. They use a very well known approach for modeling processes (based on “boxes and arrows”) and allow representing processes in a very visual manner. Control of flow is dominated by the transitions between the nodes and by two first-class branching activities (FlowDecision and FlowSwitch). Flowchart is a good fit to model processes with human interactions (e.g. human workflows).
WF 3 had a notion of a root activity. Only root activities could be used as the top level activity in a WF 3 workflow. WF 4 does not have a similar restriction. There is no notion of a root activity any more. Any activity can be the root of a workflow.
Let me explain this in more detail… Activities are a unit of work in WF. Activities can be composed together into larger Activities. When an Activity is used as a top-level entry point, we call it a "Workflow", just like Main is simply another function that represents a top level entry point to CLR programs. Hence, there is nothing special about using Sequence or Flowchart as the top level activity; and they can be composed at will.
The next figure shows a Flowchart inside a Sequence. The workflow below has three activities: a composite activity that does some work, a Flowchart (highlighted in green) and finally another composite activity that does some more work.
The same can be also done in a Flowchart. The next figure shows a Flowchart that has a Sequence (highlighted in green), a FlowDecision, and then two WriteLine activities for the True and False paths of the decision.
WF 4 simplified activity authoring story makes easier writing your own custom composite activities to model any control of flow approach of your choice. In future posts, we will show how to write your own custom activities and designers.
In this post we have presented the Sequential and Flowchart modeling styles. We learned that Sequence is used for modeling sequential behavior and that Flowchart is used to model processes with a single path of execution and loops to previous states. We also learned that Sequence and Flowchart can be combined and used together as any other existing activity.
The following table shows the main differences between Sequence and Flowchart.
Sequence
Flowchart
Order of execution is explicit, close to imperative/code
Order of execution expressed as a graph with nodes and arcs
Loopbacks are represented combining control of flow activities (e.g. While + If)
First class modeling of loopbacks
Parity with imperative / procedural
Parity with boxes and arrows diagrams
Activities are executed in sequential order
Activities are executed in the order dictated by the arrows between them
Simple process / no human interaction (e.g. services)
Complex processes / human interactions (e.g. human workflows / state machine scenarios)
The flow of the process is not visually obvious
Control of flow is visual, dominated by Boolean decisions (FlowDecision) or Switch (FlowSwitch)
A high level view of the tracking infrastructure is shown below
The primary components of the tracking infrastructure are
1) Tracking records emitted from the Workflow runtime.
2) Tracking Profile to filter tracking records emitted from a workflow instance.
3) Tracking Participants that subscribe for tracking records. The tracking participants contain the logic to process the payload from the tracking records (e.g. they could choose to write to a file).
The Workflow tracking infrastructure follows the observer pattern. The workflow instance is the publisher of tracking records and subscribers of the tracking records are registered as extensions to the workflow. These extensions that subscribe to tracking records are called tracking participants. Tracking participants are extensibility points that allow a workflow developer to consume tracking records and process them. The tracking infrastructure allows the application of a filter on the outgoing tracking records such that a participant can subscribe to a subset of the records. The mechanism to apply a filter is through a tracking profile.
The workflow runtime is instrumented to emit tracking records to follow the execution of a workflow instance. The types of tracking records emitted are
· Workflow instance tracking records: Workflow instance records describe the life cycle of the workflow instance. For instance a record is emitted when the workflow starts or completes.
· Activity tracking records: Activity tracking records are emitted when a workflow activity executes. These records indicate the state of a workflow activity (i.e. an activity is scheduled, activity completes or fault is thrown).
· Bookmark resumption tracking record: A bookmark resumption record tracks any bookmark that is successfully resumed
· User tracking records. A workflow author can create custom tracking records within a custom workflow activity and emit them within the custom activity. Custom tracking records can be populated with data to be emitted along with the records.
Out of the box in WF 4.0 we provide an ETW (Event Tracing for Windows) based tracking participant. The ETW tracking participant writes the tracking records to an ETW session. The participant is configured on a workflow service by adding a tracking specific behavior in a config file. Enabling ETW tracking participant allows tracking records to be viewed in the event viewer. Details of using the ETW based tracking participant will be covered in a future post. The SDK sample for ETW based tracking is a good way to get familiar with WF tracking using the ETW based tracking participant.
In future posts we will discuss the WF tracking feature in depth. Topics covered will include tracking profiles and tracking records, ETW tracking participant, writing custom tracking participants, variable extractions and unified tracking and tracing.
Cross-posted from the Silverlight Web Services Team Blog.
Silver.
This morning, I’m pleased to announce that the team has posted four initial Windows Workflow Foundation (WF) migration guidance documents to help current WF developers evaluate the new WF programming model that is being introduced in .NET Framework 4.
The documents were written by the PM team to help describe the relationship between the existing WF technology that was introduced in .NET 3.0 (defined as the types in the System.Workflow.* namespaces; referred to in the documents as WF3 for simplicity and brevity) and the new WF technology that is being released in .NET 4 (the System.Activities.* namespaces; referred to in the documents as WF4). The team explains how to think of WF features within the two programming models, and the choices you have as a user or a potential user of workflow technology in .NET 4.
Because this is a very broad topic, we’ve broken up what was initially going to be a single paper into about eight. There is an overview document and [currently] seven papers that take the form of either higher level guidance and cookbook papers. Today’s initial release introduces the higher-level guidance documents, with the cookbooks to be released in the coming weeks.
As the documents are updated, we will be releasing them to the WF Migration Guidance download on the MS Download Center, and the accompanying source code will be posted on a WF Migration Guidance project on the MSDN Code Gallery.
The document list looks like the following:
The papers will continue to be grown and updated as we move towards the RTM release – to address a larger number of usage scenarios, and to address any changes that happen between pre-releases. We’ve been working on the documents over the last month, and think that they provide some good initial thoughts on how to approach the technology; and we hope that you find them helpful
The team will be supporting feedback and requests for the documents and accompanying sample code in the WF 4 forum on MSDN. I’m told the feature PMs will be creating a thread for each document to make it easier to provide feedback and for the PMs to respond – we should have more information on that in the next few days.
This blog post introduces the Project and Item templates for Workflow 4.0. It also clarifies as to how the Workflow 3.0 templates are still available for users to create projects and then upgrade them to the 4.0 Framework.
We are putting in a deep though into what kind of templates do users want? Do they help users get kick started with the kind of application they typically want to create? How much setting changes the user might have to do for his applications? Is it an accurate reflection of the OM? Do we have too many/too less templates? So what do you think? What would you prefer to see/not to see? Are the names intuitive enough? Please let us know so that we can update them in time for the VS 2010 release.
Thanks,
Kushal.
Continuing on the theme of Workflow 4.0 blog, this blog post talks about the enhancements and features provided for debugging in Workflow 4.0.
The blog post talks specifically dwells into the seamless debugging between the Xaml view and the Designer view of the Workflows. Most of the features provided in Workflow 3.0 Debugging re still provided as well. Also, please be on the look out for the blog post as to how you can use the DebugService now public in Workflow 4.0 for creating tools like Simulators, Monitoring and Re-hosted Debugging.
WF4 beta 1 ships with a comprehensive set of activities (more than 35) that you can use to author your workflows or to create your own custom activities. This post will give you a quick tour through the activity palette and introduce you to the key characteristics of the out of the box activities..
Quick note: As you may have noticed, the activities in the toolbox are not sorted alphabetically. This is something that we are aware of and that will be fixed in the next Beta. For Beta1, if this bothers you, you can simply right-click in the toolbox and choose "Sort Items Alphabetically" and it will sort the items for you for easy discoverability.)
It’s been a long tour, hasn't it? And this is just the beginning! There are a lot of new exciting features in WF4 and we are eager to share them with you in future posts.
This post is an introduction to the activities that we are shipping in the activities toolbox. If you want to see these activities in action, please check our WF samples. A good starting point are the samples under the folder %SamplesRoot%\WF\Built-InActivities.
We are keenly interested in understanding your scenarios and ideas, and helping you accomplish your goals on WF4. We’d appreciate your feedback (both positive and critical), and we look forward to continued dialogue about the activities that you would like to see in WF toolbox. We look forward to hearing from you!
Matt Winkler, a Program Manager on the Workflow designer team has kicked off the blogging frenzy with his tour of the workflow designer.
Matt walks through how you can continue to create 3.x workflows in the VS 2010 using the same familiar experience you had in 3.x. He then walks you through the experience of creating a 4.0 workflow using the new WF designer in VS 2010 and introduces concepts along the way - Arguments, Variables, a quick tour of the Activities you will find in the toolbox, Validation in the designer, expression editing, navigating through the workflow etc. I hope the post gives you a good flavor of some of the basics. Over the next few weeks and months, the team will continue to post additional content here and on MSDN going over the various pieces in more detail. Till then, happy experimenting...
Yes!! | http://blogs.msdn.com/endpoint/ | crawl-002 | refinedweb | 4,366 | 53.92 |
19 January 2010 17:19 [Source: ICIS news]
By Nigel Davis
LONDON (ICIS news)--Plastics futures trading on the London Metal Exchange (LME) shrank in 2009 with little or no interest in some of the regional, and the exchange’s original global, linear low density polyethylene (LLDPE) and polypropylene (PP) contracts.
But the latest data on these first exchange-traded plastics futures contracts belie the increasing interest globally in chemicals risk management.
With prices falling away and margins under pressure in 2009, particularly at its start, producers were keen to lock in margins and were seeking out products and mechanisms to do just that.
The LME and some of the world’s big banks have reported a good year for over-the-counter (OTC) products referenced either to the exchange’s numbers or to other price points.
The exchange says the OTC market in monthly average financial swaps, or MAPS, referencing the LME price, is believed to be at least five times the on-exchange market.
In 2009, however, there can be no denying the fact that the LME’s plastics futures contracts continued to fail to gain support in Europe and ?xml:namespace>
Even over the course of the year the number of trades was limited. There was little or no open interest in the contracts at the year end.
Plastics activity for the exchange was centred on
LLDPE North America volumes were down 58% compared with 2008, although the LME says that there was a noticeable increase in activity in the fourth quarter.
The exchange-traded contracts have suffered with the downturn but have singularly failed to attract the attention of more than a handful of producers, traders and distributors.
This has to do with the reluctance of most producing companies to give away what little pricing power they have, but also with the complexity of the LME’s offering and the fact that it is tied into the exchange’s network of approved warehouses and trading members.
Exchange trading has a cost which most players are unwilling to pay. They want to manage risk, but on their own terms.
The exchange has sought to make plastics futures trading more attractive - by introducing regional contracts and by lengthening storage times - but has always been slow off the mark.
Its contracts, also, have in the view of many, been far too complex.
Adopting a system based on bagged lots of plastics created barriers in the
Plastics producers and converters, however, particularly in such a difficult and uncertain price environment, want to lock in margins. And increasingly, integrated producers would prefer to work with a suite of products that can allow them to hedge exposure from feedstock through to the polymer. Business is being done on chemical intermediates and price vulnerable polymers other than LLDPE and PP.
But manufacturing companies do not necessarily trust the banks following the 2008 global financial meltdown. This is leading to the development of hybrid products that are eventually cleared on an exchange.
The LME’s job, however, has been likened to “pushing a pea uphill”. With so few active traders and trades in most of the exchange’s plastics contracts, it is immense.
No-one quite understands how
The LME says its prices are increasingly being used in commercial contracts and that all parts of the chain are active in the market. That is encouraging, but its plastics products need to attract a great deal more liquidity if they are to successfully tap into a clear industry need.
For more on LLDPE and PP visit ICIS chemical intelligence
Read John Richardson and Malini Hariharan's Asian Chemical Connections blog | http://www.icis.com/Articles/2010/01/19/9327154/insight-lme-plastics-futures-slump-while-chem-makers-seek.html | CC-MAIN-2013-48 | refinedweb | 605 | 56.08 |
15. Re: Java 7 u45 Web Start application won't launchuser4754121 Oct 21, 2013 4:48 AM (in response to Wolfgang)
This work for the demo app but not for the eclipse app.
The launcher starts but the execution fail with following error.
at org.eclipse.equinox.launcher.Main.run(Main.java:1410)
at org.eclipse.equinox.launcher.WebStartMain.main(WebStartMain.java:57) line where Launcher fail:
System.getProperties().put(PROP_FRAMEWORK, fwkURL);
Seems to be insufficient permissions.
Attirbutes:
Application-Name: xxxx
Codebase: *
Permissions: all-permissions
Trusted-Only: true
Trusted-Library: false
Attirbutes Case2:
Codebase: *
Permissions: all-permissions
Trusted-Only: false
Trusted-Library: true
!ENTRY org.eclipse.osgi 2 0 2013-10-21 11:45:26.978
!MESSAGE One or more bundles are not resolved because the following root constraints are not resolved:
Bundle are not found, unknown Application ID.
So this does not help for me and anyone who want to start eclipse based app with webstart 7U45.
Andreas
16. Re: Java 7 u45 Web Start application won't launch1048020 Oct 21, 2013 7:56 AM (in response to user4754121)
I found that I had to re-sign all of the Eclipse jars and add Trusted-libarary: true and Permissions: all-permissions to each one to get the RCP app to launch without warnings.
17. Re: Java 7 u45 Web Start application won't launchWolfgang Oct 21, 2013 8:12 AM (in response to 1048020)
Exactly, I did not mention this before because it was kind of obvious to me, I also changed the manifests of all the eclipse-jars and resigned them.
18. Re: Java 7 u45 Web Start application won't launchuser9146454 Oct 21, 2013 8:28 AM (in response to 1048020)
beda304d-4f2b-4dd2-8ec7-0b5246984eb2 wrote:
I found that I had to re-sign all of the Eclipse jars and add Trusted-libarary: true and Permissions: all-permissions to each one to get the RCP app to launch without warnings.
Trusted-Library: true has known compatibility issues with Update 45, so for those landing here from a Google search, please read this article first. It may have solved some Eclipse RPC issues, but it will cause an additional dialog to be shown every time for those programmers using JavaScript/LiveConnect. Here's the link again:
Straight from the horse's mouth (so to speak), here's the quote from the article that says NOT to use Trusted-Library:.
-Tres
19. Re: Java 7 u45 Web Start application won't launchuser4754121 Oct 21, 2013 10:10 AM (in response to 1048020)
Ok, I was at this point for some day´s.
I use Trusted-Library=true eclipse starts without the warning. But it did not run. It seems for me like a missmatched jnlp config or so. If I start it Trusted-Library=false everything run but I got the warning. I`m realy confused.
Is it possible to get the a jnlp file which works for an rcp/eclipse application?
20. Re: Java 7 u45 Web Start application won't launch1048020 Oct 21, 2013 11:55 AM (in response to user4754121)
21. Re: Java 7 u45 Web Start application won't launchuser4754121 Oct 21, 2013 12:32 PM (in response to 1048020)
Pls remember my application runs. The only change I made is to the Trusted-Library=true ever things else remains. I can switch between them.
My jnlp is a part of the launch plugin with the required path an filename "JNLP-INF/APPLICATION.JNLP". I got also errors if some difference between there.
As far as I know the properties will be ignored if the JNLP is unsigned. But signed JNLP could use properties as used till now. I commit this. I try also your suggestion #10.
I think the problem is in the range of codebase of the xml jnlp tag.
Therefor I am interested on a working JNLP which a rcp/eclipse app starts.
22. Re: Java 7 u45 Web Start application won't launchuser9146454 Oct 21, 2013 12:32 PM (in response to 1048020)
beda304d-4f2b-4dd2-8ec7-0b5246984eb2 wrote:
Dylan,
I tried researching the signed JNLP and it seemed like an unofficial specification and couldn't determine how far back this was supported.
I for one would like to create a signed JNLP especially if it resolves issues. Can you link to a good tutorial for this? Since the JNLP is simply an XML file, I didn't know where to start, since most signed items in Java tend to be JAR files....
Thanks in advance.
-Tres
23. Re: Java 7 u45 Web Start application won't launchsbrodrigues Oct 21, 2013 2:06 PM (in response to 1048020)
Hi Wolfang,
I am facing the same problem of dynamically generating the JNLP and hence cannot sign it. I tried passing the properties as arguments as you suggested but could not get the property in my main class. Note that my Main Class is home grown wrapper class that calls the Eclipse Main class
Original.
<property name="webrcp.location" value=""/>
After Option # 1 ( Does not work.. gives webrcp.location not found. )
<application-desc
<argument>-webrcp.location</argument>
<argument></argument>
After Option # 2 ( Does not work.. gives webrcp.location not found. )
<application-desc
<argument>-Dwebrcp.location=</argument>
</application-desc>
Ideas... anything I am doing wrong? Thanks for your help.
-Rodrigues
24. Re: Java 7 u45 Web Start application won't launch1048020 Oct 21, 2013 2:05 PM (in response to sbrodrigues)
Rodrigues,
Is webrpc.location something you pick up in your code? I had one custom (not OSGi) argument that I was using. After changing the JNLP from property elements to argument element, I had to change my Java code from System.getProperty(MY_PROP) to
String myProp = null;
String[] commandLineArgs = Platform.getCommandLineArgs();
for (int x=0; x < commandLineArgs.length; x++){
if (commandLineArgs[x].contains(MYPROP)){
myProp = commandLineArgs[x + 1];
break;
}
}
25. Re: Java 7 u45 Web Start application won't launchuser9146454 Oct 21, 2013 2:54 PM (in response to 1048020)
I examined the JavaDetection.jar and it seems to use this technique [tinyurl.com]. I know this doesn't help the dynamically generated jnlp users out there (sorry!), but since I use a static jnlp, I'm going to try this tonight.
Coderanch to the rescue (again) [coderanch.com]
Reading the JNLP Spec (JSR-56)
Section 5.4.1 SIGNING OF JNLP FILES states:filename
-Tres
26. Re: Java 7 u45 Web Start application won't launchWolfgang Oct 21, 2013 3:26 PM (in response to sbrodrigues)
AAFAIK "-D<property>" is also considered "insecure".
I did not use arguments but simply transformed my properties into "secure" ones by adding the "jnlp."-prefix, my custom launcher iterates through all properties and removes the prefix again so that the following code works just like before.
This is what I used as wrapper:
import org.eclipse.core.launcher.WebStartMain; import java.util.Properties; class WrapperMain { public static void main(String... args) { Properties props = System.getProperties(); for (String key : props.stringPropertyNames()) { if(key.startsWith("jnlp.")) { System.setProperty(key.substring(5), props.getProperty(key)); } } org.eclipse.core.launcher.WebStartMain.main(args); } }
Probably not the most elegant solution but I did not have to modify any subsequent code and could continue to use all properties like before.
Before:
<property name="osgi.clean" value="true"></property>
After:
<property name="jnlp.osgi.clean" value="true"></property>
Hope that helps
Wolfgang
27. Re: Java 7 u45 Web Start application won't launchsbrodrigues Oct 21, 2013 6:17 PM (in response to Wolfgang)
Wolfang,
The jnlp. prefix did the wonderful trick for me ! Thank you much ! Not sure how simply adding a prefix like that makes the properties more secure though. But regardless many thanks to you and the community !!
-Rodrigues
28. Re: Java 7 u45 Web Start application won't launchWolfgang Oct 22, 2013 1:57 AM (in response to sbrodrigues)
I dont really understand that either, but its documented here:…
29. Re: Java 7 u45 Web Start application won't launchuser4754121 Oct 22, 2013 11:49 AM (in response to Wolfgang)
Read this thread:
This is exactly what I mean and the eclipse launcher do that.
So I can´t understand how you are got a rcp/swt application to run.
I use an E3.7.2 target, but I also looked at 4.3 and this launcher do the same, so the behavior should also the same.
Now I got the properties to run thanks for the sample code.
If a JNLP is signed, unsecured properties work!
Only on unsigned JNLP is a workaround necessary. I use a dynamic JNLP this is the better solution for me. | https://community.oracle.com/thread/2593583?start=15&tstart=0 | CC-MAIN-2015-22 | refinedweb | 1,438 | 65.83 |
PC Connectivity - How To Write Backup Aware Software for Symbian
The Symbian platform includes software to carry out backup and restore operations from a connected PC. In order for this software to function correctly, it requires some co-operation from other software (servers and applications) running on the phone. This document describes the required co-operation, how an application or server needs to behave in order to participate in backup and restore operations.
This document is intended for any developer creating software to run on a Symbian platform phone. This document covers behaviour of Symbian OS v9.1 and later versions.
What you should do as a developer
If you are responsible for an application that owns data then read through the following steps:
- Familiarize yourself with the backup and restore concepts so that you can then make the right decisions regarding the backup and restore of your application and its data. Read through Section 2.
- Decide what mechanism will be required in order for your application to become backup aware, refer to Section 3 for details.
- Decide which data needs to be backed up and restored and how it should be dealt with. This will require the following decisions to be made, more details can be found in Section 4
- Decide whether or not you have public or private data that needs to be backed up.
- Decide how you will react to backup and restore operations (i.e. do you need active or passive backup and restore).
- If you need to implement active backup then do so.
- Decide whether or not you wish to have your system files backed up.
- Produce a backup registration file that covers the decisions made above. Refer to Section 5 for details.
Overview and Background
File Locks and Public Files
Backup works by copying files and data from the phone to the PC. Restore works by copying the files and data in the other direction. The backup and restore operations rely on being able to copy files when they need to. If a file is locked then it cannot be copied. In normal phone use, a range of servers and applications will have files open for reading or writing and may have updates pending on some files.
Files in the public area of the filing system can be backed up and restored directly by the PC Connectivity subsystem but this requires all other processes to free up file locks when required. Platform security (introduced in Symbian OS v9), and specifically data caging, provides for ownership of private data files (see Section 2.2). Ownership of public data files is more complex.
- A backup operation needs to read files so processes must relinquish exclusive-locks on files but can retain read-locks (although in practice many processes just relinquish all locks for the sake of safety and simplicity). In order for a backup operation to take place, applications and servers must flush any pending updates to files and allow all files to be read (but cached data can be retained as backup will not alter data files). When the backup has taken place, servers and applications can re-take file locks and carry on.
- A restore operation requires exclusive access to files so processes must relinquish all locks on files. In order for a restore operation to take place, applications and servers must discard all cached data and allow files to be written or overwritten. When the restore has taken place, servers and applications must reload their data from files that can be expected to have changed.
Private data and data caging requirements
With the introduction of platform security, directories are divided into public and private areas. Public files can be viewed and altered by any application (although file locks may still get in the way). However, processes can define private data areas where they store files that only they can operate on. The system also defines some areas as private to store executables and read-only data. The choice of whether and what files should be stored in public and private areas is devolved to the servers and applications (with some audits). All of the restrictions can be overridden by executables that have the requisite privileges (the use of these is minimized on principle).
As a principle, the backup process attempts to protect private data in the following ways:
- Application executables will not be backed up without the consent of the developer. This means that if you develop an application and forget about backup, you should not find your application backed up. It is normally meaningless to restore an application without at least some of its private data.
- Private data will not be backed up without the consent of the data owner. This means that if you don’t explicitly enable the private data to be backed up, you should not discover it has been exposed without your knowledge.
- Private data may be encrypted before delivery to the backup client (normally a PC). The backup process supports encryption and provides the hooks for key access but does not guarantee that a useful key will be used. (This relies on the phone manufacturer to include a specific mechanism to provide the encryption key). It should be assumed that the user will have access to the encryption key and so application developers should not assume that data will be protected from the user. For this reason, encryption of backed up data may be omitted.
Active and passive backup
There are two ways of backing up private data:
- 'Active backup of private data. In this model', the process which owns the data, registers with the secure backup engine using a registration file. The secure backup engine will start any process registered for active backup if not already started. The data owning process then responds to a central signal when a backup or restore operation takes place and actively provides its private data to or receives it from the secure backup engine. This requires that the data-owning process include specific code to take part in backup and restore operations, and that it must be running when a backup or restore takes place. In this model the data-owning process registers with the secure backup engine but exercises complete control of which data is backed up and restored.
- 'Passive backup of private data'. In this model, the process which owns the data, registers with the secure backup engine using a registration file and records whether executables, private files or directories of private files should be backed up. The data-owning process then releases file locks for private files in the same way as for public files (described above) and the files are backed up by the secure backup engine (which has the required capability to access private data files belonging to other processes).
It can be seen that passive backup is very simple for developers to implement – all that is required is a registration file that defines which private files should be backed up or restored and the same type of lock-releasing behaviour already required for public files. Active backup requires more effort to implement but provides the data-owning process with more control over the data backed up and restored.
It should be noted that data-owning processes can also list public files or directories that should be backed up or restored along with their private data in cases of a partial backup or restore.
Base and incremental backup and restore
Backup is intended to be a routine operation for the user. Therefore, it should be as quick and painless as possible. For this reason, the Symbian platform implements base and incremental backups. A base backup (sometimes described as a full backup) is a backup of all or part of a drive that includes all the selected files. In contrast, an incremental backup is a backup of all or part of a drive that only includes files that are new or changed since a previous backup. An incremental backup is thus smaller than a base backup and will take less time.
It should be noted that there are (at least) two possible patterns of use for incremental backups.
- The first pattern involves taking one base backup and then a series of incremental backups with each increment including only the files that are new or changed since the last increment. This pattern minimises the time taken for each increment but has some drawbacks for restoring private files (because all the increments are required for restore operations).
- The second pattern involves taking one base backup and then a series of incremental backups with each increment including only the files that are new or changed since the base backup. In this pattern, the time taken for an incremental backup is not minimised and may approach the time taken for a base backup but a restore operation only requires the base and a single increment.
The choice of which pattern to use will be made by the PC software - not by the phone software. It should be noted that an incremental backup cannot be created purely based on a date and time stamp. If a new file is added with an old time-stamp then a time-based increment would omit it. Therefore, any incremental backup requires a list of the files included in the preceding backup.
Full and partial backup and restore operations
By default, a backup (whether base or incremental) aims to include all files on a specified drive. In practice, the user may only care about data belonging to one or more specific applications. By omitting other data files the time taken for the backup (or restore) is reduced. It can be seen that the choice between full and partial backups is orthogonal to the choice between base and incremental backups.
Versions of the Symbian platform prior to v9 do not support partial backup or restore well. This is because all files are public and the Symbian platform provides no means of associating specific files with specific applications. Some phone manufacturers have provided (at least partial) solutions to this problem but the extension of these categories to third-party software is problematical. Similarly, some PC suites have provided partial restore but the association of files with applications is problematical.
Because platform security requires a process (application or server - basically a private data owner) to specify the private files to be backed up, there is a close association of private files with specific applications. In addition, it is possible to associate public files with specific applications. However, there is no guarantee that more than one data owner will not lay claim to any public file and there is no guarantee that all public files will be associated with a data owner.
An additional possible benefit of partial backup and restore is that a data owner may be able to participate in backup or restore without requiring all file locks to be freed. For example, if a data owner only deals with its own private files then it may be possible to back up its data in isolation. This would allow backup operations to have less impact on the user. On platform security-enabled Symbian platform phones, installed applications are no longer backed up by default as was the case on earlier releases of the Symbian platform. The backup and restore of installed applications is now requested via a tag in the backup registration file – more details can be found in Section 4.8.
Backup aware behaviour
Backup and restore signalling
The signalling method provided to inform processes that a backup or restore is taking place is via the publish-and-subscribe API. The publish-and-subscribe server maintains a list of subscribers expressing an interest in the backup and restore flag. Any published changes to this flag by the backup and restore engine results in all subscribers being notified. The flag provides information on whether a backup or restore operation is in progress, whether a backup is base or incremental and whether the operation is full or partial.
Subscribing to the flag is done via RProperty, which must be used in conjunction with an active object to be notified when the value changes. The following key and category values should be used (these are defined in epoc32\include\connect\sbdefs.h):Category
: KUidSystemCategoryValue
: KUidBackupRestoreKey
The following code fragment demonstrates this:
#include <e32property.h>
RProperty iProperty;
iProperty.Attach(KUidSystemCategory, KUidBackupRestoreKey);
CActiveScheduler::Add(this);
iStatus = KRequestPending;
iProperty.Subscribe(iStatus);
SetActive();
// In RunL, to get the state:
TInt backupStateValue = 0;
iProperty.Get(backupStateValue);
Applications being made backup aware should use publish-and-subscribe (P&S), however there’s another mechanism still present but should not be used in favour of P&S which will be deprecated in a future platform release: the Base backup server. It is now only used to manage GUI applications during a backup or restore operation. When a backup or restore takes place, a signal is passed from a backup client on the PC or phone and a number of special servers take action. The Base backup server maintains a list of servers that have registered an interest in backup and restore and invokes observers to take appropriate action. When a backup or restore is complete, the Base backup server informs its observers that normal service has been resumed.
Default behaviour for GUI applications
The behaviour for GUI applications is deliberately straightforward: by default, all GUI applications are politely terminated when a backup or restore operation takes place. As a result of most applications exiting, many system servers release file locks. This technique avoids GUI application developers having to implement backup- and restore- aware code in most cases; the relevant server and exit code is implemented within the Uikon subsystem.
At its simplest, a GUI application can take no specific backup or restore action. If a GUI application does not have the ‘system’ status it will be terminated when file locks are required and will be re-started after the backup or restore. The terminate-restart behaviour will ensure that direct and (most) indirect file locks will be freed. A potential optimization for a GUI application is to store the current view and state when terminated and to adopt the same view when it restarts (this choice may be required or deprecated as part of UI design guidelines outside the scope of this document). This will make for a seamless restart after a backup, i.e. the application will appear the same to the user, as if it had not terminated and restarted.
The UIKON backup server terminates most running GUI applications (all GUI applications that are not registered as system applications). When a backup or restore is complete, the UIKON backup server restarts the GUI applications that were terminated. A GUI application that must not be terminated during a backup or restore, a ‘system’ GUI application, must behave in the same way as a server (see below) and manage its own file locks directly. Only phone manufacturers should develop such applications because of the possible side effects, the default behaviour should be to accept termination.
Servers that hold locks for clients
Some servers access files only as a result of calls from clients. As long as these servers only have well-behaved clients they need take no special action. Their clients will either terminate (if they are GUI applications) or will drop connections (if they are well-behaved servers or system applications) so the server will then drop locks on files. However, the developer should be aware of the sequence of actions during a backup or restore as some behaviours, which might appear to be performance optimizations, could prevent a successful backup:
- If a server was to keep a file open after all attached clients had closed that file (for example, to improve performance in case a client was likely require it again), then the backup and restore operations would be blocked.
- If a server was to keep cached data in case the same file was re-opened then a restore operation could be corrupted.
If such optimizations are required then the server must become backup-aware and drop file locks promptly and flush data caches on backup and restore operations. m ,,lvl.m,
Servers and applications that hold other locks
Servers (and other applications) that do not terminate during a backup or restore operation and do not drop file locks because of their clients’ behaviour need to become backup aware in their own right.
If a process is not liable to external events during backup and restore operations then it simply needs to react to backup and restore events and release file locks. However, if a process can receive external events during a backup or restore (such as a telephone call, an incoming message or an external request for some action) then the process needs to ensure that the event does not interfere with any files during the backup or restore. Examples of possible interference include:
- Writing to call log files when a telephone call is received;
- Storing an incoming message in the messaging store;
- Applying an incoming configuration message.
- How the process handles the event is up to the process developers but some possibilities include:
- Ignoring incoming events (only acceptable if they will be automatically re-sent later);
- Caching incoming events in memory or in a safe private file and then applying them after the backup or restore operation.
Reboot after restore
The reboot after restore flag is currently ignored. This is due to the Symbian platform, currently, providing no standard way to ensure a reboot of a phone. Applications should be written in a manner which will not require a reboot as a reboot can not be guaranteed. (When the Symbian platform support a standard mechanism for rebooting a phone then the functionality will be enabled.)
The reboot after restore flag will be made available to clients using the backup architecture so phone manufacturer-specific reboot mechanisms can be used.
Expected behaviour from data owners
If you are the developer responsible for a process (application, server or some other component) which accesses public files or which owns private data files then you need to go through a number of steps to make your process participate in the backup and restore operations:
- Decide whether any of your private data should be backed up, and if so, how much of it.
- If you have private data to back up then decide whether you will use the active or passive backup approach.
- Based on the answers to the previous stages and on whether your process is a GUI application or not, decide how your process needs to respond to backup and restore events.
Criteria for backing up private data
If you are the developer responsible for creating or maintaining a process which owns private data then you will have to decide if your processes should take part in the backup of private data or not. In general, as much private data as possible should be backed up (to help the user) but there are some criteria, which indicate data which should not be backed up:
- If the private data must not be exposed to the user then it should not be backed up. Assume that all data backed up can be read and potentially altered by the user. This might change if a phone manufacturer implements encryption which does not rely on keys provided by the user but that is a phone manufacturer-specific decision and cannot be guaranteed.
- If the process cannot keep the private data stable during a backup or restore then they cannot safely back it up. This is a poor reason for not backing up data but may be a practical one. It depends on the sources of external events and whether they can be delayed or placed in a temporary location.
- If the private data can be easily recreated by other means then it may be excluded. This may not be a good criteria, but if a process would find it difficult to back up private data (perhaps for the reasons above) and the data could easily be created (for example by receiving configuration messages) then choosing not to back it up may be more acceptable.
In addition, consider the implications on other processes of backing up the data or not. If your data must remain consistent with that in public files then the private data must be backed up. If your data must remain consistent with that owned by another process then they should both back up data or neither.
Criteria for choosing active or passive backup
As described above, passive backup and restore of private data is simpler than active backup. It also takes less system resources because processes taking part in active backup must be running during a backup or restore. However, active backup allows the data-owning process more control over the data and this can have both security and performance gains.
The choice between passive and active backup may not be a black-and-white one - it may involve weighing up a number of factors. The following list includes a range of advantages and disadvantages and you need to consider all of these and make a decision.
- The registration for passive data backup only specifies whole files or directories. It is not possible to backup only part of a file using passive backup. If you need to backup only part of a file you need to either split the file into two or use active backup.
- The registration file that defines the files and directories to be subject to passive backup is created at system build time (for a system process) or at installation time (for an installed application). The registration files cannot be modified or created at runtime. If your process will create new directories after installation then the registration file cannot be extended for these. If you want these backed up then you need to either put them under a common directory which all gets backed up or use active backup and make a run-time decision on what to backup. This aspect may be partially or wholly addressed by installing additional backup registration files.
- Backed up data is compressed en-route to speed up data transfer (this can be disabled). However, if your private data has a specific format and you can manage to backup only a fraction of it you may be able to make the backup of your data more efficient by implementing active backup.
- Backups can be base backups or incremental backups. With passive backup (as with the backing up of public files) incremental backups include all relevant files which have changed or are new since the last backup took place. If a file contains record-based data (such as a database) then the addition or changing of one record will cause the whole file to require backup. If you implement active backup then you could only backup the changed or new records (plus recording deleted records in some way). This could increase the performance of backup and restore for your data.
- Active backup requires your process to be started during a backup or restore operation. Your process will be started automatically as required by the secure backup engine if not already running. If your process normally runs at all times then this imposes no additional burden on the phone. However, if your process is not normally running then it will require additional resources during a backup or restore and you should consider if the benefits of active backup justify the additional burden.
One approach which has been considered by some developers and which may be useful is that of a hybrid approach. The secure backup engine allows a data owner to register as both an active backup client and a passive backup client. This was originally intended to allow a data owner to back up some data in each way but an alternative use is for the active backup client to prepare data for backup and then let the secure backup engine handle the actual transfer as a passive backup. The active backup client does not need to actually provide any data.
In order to support this, the secure backup engine should not retrieve data for passive backup until an active backup client has signalled that the data is ready (this set-up is configurable in the backup registration file). That is, if a data owner is registered to take part in both passive and active backup then the PC host or other client is expected to request active backup data before passive backup data. When a restore operation is carried out, the data will be restored as passive data and the data owner is responsible for dealing with it when the restore operation is complete. In order to support this, the PC host or other client is expected to restore passively backed up data before actively backed up data if a data owner has registered for both active and passive backup and restore.
Owners of private data to be actively backed up
Processes, which own private data that needs to be actively backed up, will have to register with the backup engine as an owner of private data for active. Processes which own private data that needs to be actively backed up will be started up if required by the secure backup engine in order to do the backup or restore. Therefore, they must check the backup flag on startup rather than making a normal startup (which may involve undesirable access to other servers and files).
Behaviour required of a process that takes part in active backup of private data:
- When the backup status flag gets set to ‘backup in progress’ any data that has not yet been saved may need to be saved.
- The process has to release locks on all public data files that require to be backed up (files that are excluded from backup can be kept locked but assume that all public files will be backed up) so they can be copied off and stop modify private data files. This may require that the process ‘freezes’ all sessions to external processes to avoid external events that would cause files to be written to (whether requests are blocked or errors returned depends on the context).
- The process then tries to make a connection to the secure backup engine by name.
- At the start of backing up private files, the process must ask the secure backup engine whether it is a base backup or an incremental backup using the APIs referenced in Appendix B and, if it is an incremental backup then it must wait until the file snapshot to use for the increment is provided.
- The process then sends its private data as a stream using the APIs referenced in Appendix B. The owning process is responsible for taking its data files (all or whichever subset it wants to back up) and streaming them. Reference code will be provided to take all files in a private directory and stream them. Any other behaviour will have to be implemented by the data owners.
If the backup is a base backup then all the data in the relevant files should be provided.
If it is an incremental backup then it should only stream data corresponding to the changes since the snapshot. The data-owning process has a choice of how sophisticated its behaviour is in this regard. The simplest behaviour is to always do a base backup (this will be an option, even when an incremental backup has been requested). An alternative is to provide backups of files that have changed since the last backup. The final option is to provide only that data that has changed since the last backup. Which choice is made will depend on the nature of the data to be backed up.
It should be noted that an application may have been installed after the base backup so a process must handle this (no snapshot will be provided).
The data-owning process is responsible for providing a snapshot of files that can be used as a baseline for subsequent incremental backups.
- backup is partial or has been broken off).
When the backup flag reverts to normal, files can be re-accessed and clients responded to. The process must handle the case where the backup data has only been partially received or has not been received at all.
Behaviour required of a process that responds to an active restore of private data:
- When the backup status flag gets set to ‘restore in progress’ the process has to release locks on all public data files that require to be restored (files that are excluded from restore can be kept locked) so they can be overwritten. This may require that the process ‘freezes’ all sessions to external processes to avoid external events that would cause files to be read or written to (whether requests are blocked or errors returned depends on the context).
- The process then tries to make a connection to the secure backup engine by name.
- The process then receives its private data as a stream using the APIs defined in Appendix B. The owning process is responsible for receiving the data as previously provided and recreating the relevant files. Reference code will be provided to take a stream and create files in a private directory. Any other behaviour will have to be implemented by the data owners.
The first chunk of data received will be a base backup of (potentially) multiple files.
If incremental backups have been carried out the base backup data will be followed by a sequence of increments. They will be supplied in the correct (i.e. chronological) order. The receiving process is responsible for amending the data accordingly. If the process can only provide full backups then it will not receive increments.
- The private data being restored may not be received immediately (multiple processes may be trying to receive data at the same time) and may not be received at all (if the restore is partial or has been broken off).
- When the backup flag reverts to normal, files can be re-accessed and clients responded to. The process must handle the case where the restore data has only been partially received or has not been received at all. Any cached data must be flushed after a restore.
Owners of private data to be passively backed up
Processes, which own private data that needs to be passively backed up, will have to register with the backup engine as an owner of private data for passive. During the backup or restore, the process can exit or release locks on all public and private data files. If the process is a GUI app then the default behaviour will be for it to be terminated politely so no extra code is required.
Owners that do not want private data backed
A process which accesses public data but which does not wish to have private data backed up does not have to register for backup and restore but it does have to respond to the backup status flag:
- If your process is a UI application which can exit during backup and restore then you need do nothing – you will be terminated politely as before. It should be noted that this means that the default behaviour is for private data of apps not to be backed up. The application needs to make a positive decision to get private data backed up. This ‘opt-in’ behaviour is a deliberate choice for security reasons – apps cannot find their private data backed up without their knowledge.
- If your process is a non-UI application, or a UI application which will not terminate during backup and restore, which accesses public data then you will need to subscribe to the backup status flag and respond to it:
- .#When the backup status flag goes to ‘backup in progress’ your process must release all locks or at least make all public data files readable. This may require that the process ‘freeze’ all sessions to external processes to avoid external events that would cause files to be written to (whether requests are blocked or errors returned depends on the context). When the backup flag reverts to normal, sessions can be re-activated and files re-accessed.
- .#When the backup status flag goes to ‘restore in progress’ your process must change to a state where public files can be overwritten. This will involve releasing all public data files accessed and ensuring that external events cannot cause an attempt to re-access any files. When the restore is complete your process must re-load data files and refresh any data stored in cache.
- .#Such a process needs to check the backup flag on start-up and, if it is set, should enter the correct state. This should not happen because such a process should not be started up during a backup or restore but the process should attempt to behave robustly just in case. If the process starts up with a backup or restore in progress then it should wait until the backup or restore is complete before attempting to access any public data files.
Owners with data that resides with a proxy (e.g. the central repository)
Data owners can have data stored within another data owner’s data cage, such as with the central repository. In this scenario, data from each data cage must be backed up. The data owner holding data on behalf of another data owner is known as a proxy. From the PC’s point of view, this data belongs to the data owner, but internally the data is being requested from the proxy via the active client interface. A data owner requiring data from one of these proxies must specify the proxy in the element <proxy_data_manager /> using its secure ID. See example in Section 5.
Data stored in the central repository (CentRep) will be backed up if the proxy data manager tag is selected in the backup registration file specifying the central repository’s secure ID. Not all data may be backed up. Each value in CentRep has some metadata associated with it and one bit of the metadata is a backup flag. The value will be backed up only if the backup flag bit is set. It is the responsibility of the data owner to specify the correct settings within the repository initialization file.
CentRep backups are always base, as opposed to incremental, because the CentRep does not contain sufficient information to efficiently support incremental backups and because CentRep data is not expected to be sufficiently large to justify incremental backup.
Owners of DBMS files to be backed up
A data owner may be responsible for a number of databases that may need to be subject to back up and restore. Shared databases will be backed up if the policy number is specified in the data owners backup registration file using the <dbms_backup> tag. There is no need to specify database names as the DBMS will provide the list of the databases belonging to the data owner based on the policy identifier. See example in Section 5.
Owners of system data (installed applications) to be backed up
On platform security-enabled Symbian platform phones, installed applications are no longer backed up by default and now require the consent of the application designer. The backup and restore of an application’s binaries and its data is also done separately and requested differently. For an applications data please refer to the sections above on active and passive backup, for binaries the <system_backup/> tag should be specified in the backup registration file. See Section 5 for more details.
The <system_backup/> tag triggers the secure backup engine to query which package the application belongs to and retrieves a list of all the files referenced by the package. Only the following read-only files will be backed up as system data (any file or directory not listed below will need to be backed up separately using one of the other mechanisms described previously):
\sys\bin\*
\resource\*
\private\123456\backup_registration*.xml
Writeable files will not be backed up as system data as they will fail to be restored as system data.
An additional mechanism exists to specify backup registration files for data owners that do not have private directories - this is to be used for DLLs which are installed as part of a package. To use this method, the backup registration file must be placed in a special location under the Secure Backup Engine’s private directory:
\private\10202D56\import\packages\<package-id>\backup_registration.xml
(10202D56 is the SID of the Secure Backup Engine, and <package-id> should be replaced with the ID of the package containing the DLL)
Backup registration file format
Content of the backup registration file
A backup registration file includes the following information:
- For passive data backup operations, a list of private directories and files that should be backed up. It is possible to list a directory for backup and then list sub-directories or files for exclusion. These directories and files are defined relative to the process private area so it is not possible to refer to private files owned by another process (a value of a single backslash denotes the whole of the private directory). If any files or directories do not exist then no error will be raised – i.e. it is acceptable to list directories which do not exist yet. If a data owner’s data is such that incremental data will be inefficient then it is possible to specify that only base backups should be done (for example, if a data owner stores all of its data in one database file then any increment will always be the whole database file and it is more efficient to always do a base backup or a restore will involve transferring large amounts of redundant data).
- A list of public files and directories to be backed up as part of a partial backup. The same syntax is used as for private files but with regard to the public part of the filing system. Any system files or private files will be ignored from this section (because they are not public files). As with files listed for passive backup, directories can be listed that do not yet exist.
- For processes that require backup of system files (executables and resource files), a statement of the fact – it is not necessary to list the system files to be backed up as the list is available from package data. It should be noted that a package containing multiple data owners should have all its data owners backed up – if any of its data owners specify that system files are to be backed up then all the system files for the package will be backed up and restored as a unit.
- For passive backup and partial backup of public files, should directories be cleared before a restore operation? I.e. should extra files be deleted?
- Is active backup required? If so which process should be started or which server contacted. It is possible to invoke active backup and also request private and / or public files to be backed up. There is no guaranteed order of backup or restore (i.e. there is no guarantee of which data owner’s data will be restored first) between SIDs although it is guaranteed that active data will be requested before passive on backup and active supplied before passive on restore.
- Can this private data be backed up or restored selectively for a partial backup or restore? This is not necessarily only possible for a process that implements active backup (but a passive data owner will need to not keep files locked). This option is intended for the future where it may be possible to avoid terminating most processes during a backup or restore. At present it can be ignored as partial backup or restore will be achieved by using the normal backup or restore mode but only transferring data belonging to selected data owners.
- Does this process require a reboot after a restore operation?
- Is a shared database to be passively backed up? If so, then the security policy ID of the database to be backed up or restored must be specified.
- Does the data owner have data stored in a proxy? If so, the secure ID of the proxy must be specified in the proxy data manager tag.
- Does this process require a significant time to prepare for backup or restore?
The backup registration files will be stored in the root of the private directory of the corresponding process with a standard name (backup_registration.xml). By placing the backup registration files in the private data areas they are protected on the phone.
When a specific drive is backed up, the backup registration file is searched for on the drive being backed up. If no backup registration file is found then it is searched for in the corresponding private directory of the Z: drive. This is purely an administrative convenience to avoid processes having to copy backup registration files when it would not otherwise be necessary. If a backup registration file is found in the drive to be backed up then the Z: drive will not be searched – this allows the backup registration file on the Z: drive to be masked where necessary. One implication of this use of backup registration files from the Z: drive is that the backup registration file may refer to files (including private data files, public data files, databases, repositories and system files) that may not exist on a drive to be backed up. This is handled robustly by the backup process.
Examples of backup registration files
The following is an example of a backup registration file for a data owner that requires only passive backup of files in a sub-directory named ‘preserve’:
<?xml version="1.0" standalone="yes"?>
<backup_registration>
<passive_backup>
<include_directory name = "preserve"/>
</passive_backup>
<restore requires_reboot = "no"/>
</backup_registration>
The following is an example of a backup registration file for a data owner that requires passive backup of all its files and also wants its system files to be backed up:
<?xml version="1.0" standalone="yes"?>
<backup_registration>
<passive_backup>
<include_directory name = "\" />
</passive_backup>
<system_backup/>
<restore requires_reboot = "no"/>
</backup_registration>
The following is an example of a backup registration file for a data owner that has only central repository data:
<?xml version="1.0" standalone="yes"?>
<backup_registration>
<proxy_data_manager SID="0x10202BE9" />
</backup_registration>
The following is an example of backup registration file for a data owner that requires an active backup only:
<?xml version="1.0" encoding="UTF-16" standalone="yes" ?>
<backup_registration version="1.0">
<active_backup process_name="processname.exe"
requires_delay_to_prepare_data="yes"
active_type="activeonly" />
</backup_registration>
The following is an example of backup registration file for data owner which implements a proxy:
<?xml version="1.0" encoding="UTF-16" standalone="yes" ?>
<backup_registration version="1.0">
<active_backup process_name="processname.exe"
active_type="proxyonly" />
</backup_registration>
The following is an example of backup registration file for a data owner who wishes to back up its DBMS databases:
<?xml version="1.0" standalone="yes" ?>
<backup_registration>
<dbms_backup policy="AABBCCDD" />
</backup_registration>
Additional backup registration files
The backup registration file format allows the specification of directories for private data rather than having to specify all files individually. This means that some types of expansion (e.g., extra files or directories under a specified directory for private or public files) can be handled without changing backup registration files. However, the same technique may not handle additional system files (such as additional plug-in executables).
Therefore, additional backup registration files can be present and will be parsed. Additional backup registration files must have a name of the form backup_registration*.xml and be located in the root of the relevant private directory. Additional backup registration files can be distinguished from the principal backup registration file by the file names (the principal backup registration file has the name backup_registration.xml).
Additional backup registration files must only contain a subset of the normal backup registration file elements. They are intended to be purely additive of passive private, public and system files. They may not include an additional type of backup (i.e. they may not specify active backup or restore if it was not included in the principal backup registration file).
The effect of additional backup registration files is the same as if the passive backup, public and system file elements were included in the principal backup registration file.
All drives will be searched for additional backup registration files including the Z: drive. Additional backup registration files are always used in a backup and can not be masked.
Please note that additional registration files cannot be created or modified at runtime.
Testing backup and restore
The behaviour of any software should be tested and the behaviour of software with respect to backup and restore is no exception. Symbian tests the secure backup engine and the associated framework as part of testing the Symbian platform and developers are responsible for testing their own components.
If a process is implementing active backup and restore then this should be tested. As a minimum, a simple sequence of base and incremental backups followed by a restore to a clean device, followed by smoke tests will demonstrate that the main functions of backup and restore work. Robustness tests should involve interrupting a backup or restore operation by disconnecting the phone from the PC and checking that the data owning process handles the interruption without corruption.
The developers of a component, subsystem or other set of software are responsible for testing to ensure that their private data is backed up and restored correctly. Here are some suggested tests for inclusion in a test plan:
- Run the software under test and create some data. Back it up to a PC, reformat the phone or obtain a new device and restore the data from the PC. Then run smoke tests to ensure that the expected data is present and that no expected data is missing
- Run the software under test and create some data. Back it up to a PC and then run the software again to edit the data or create more data. Restore the data from the PC (without reformatting the phone). Then run smoke tests to ensure that that data present is that which was backed up, not the later data and that the data is consistent.
- Run the software under test and create some data. Run a backup while the software is running to test that the software makes data available and does not interfere with the backup. If possible, run the software during the backup and attempt to create or edit data. This should not interfere with the backup. Run the same tests during a restore operation to test that the software does not interfere with the restore. Pay particular attention to what happens to data entered or edited during a backup or restore operation – is it lost or retained?
More thorough tests should include verifying the active restore client’s handling of unexpected data versions, handling of out-of-sequence increments during restore and handling of incomplete or corrupt restore data but these will require specialized test software to be developed as the Symbian platform backup and restore framework tries to prevent these problems.
- After a restore, it is essential that the accuracy and completeness of the restored data is verified. This applies to passive backup data owners as much as active backup data owners. The Symbian platform backup and restore framework can only back up and restore the data that is specified or provided. If certain private files or directories are omitted then the Symbian platform backup framework will function correctly but the restored data will not be as expected.
Appendix A Backup registration File DTD
The DTD for the backup registration file is as follows:
<?xml version=”1.0” standalone=”yes”?>
<!DOCTYPE backup_registration [
<!ELEMENT backup_registration
(passive_backup?, system_backup?, public_backup?, active_backup?,
cenrep_backup*, proxy_data_manager*, dbms_backup*, restore?) >
<!ATTLIST backup_registration
version CDATA #FIXED "1.0"
>
<!-- Include file or directory name should include path relative to private
directory for private data. To include all private data use “\”.
Include file or directory name should include path relative to root of
drive for public data. This may or may not include the drive letter.
Inclusions with drive letter will be excluded from backups of other
drives. Inclusions without drive letter will be assumed to apply to all
drives.
-->
<!ELEMENT include_file EMPTY >
<!ATTLIST include_file
name CDATA #REQUIRED
>
<!-- Exclude file or directory name should be of the same form as the owning
<include_directory> and is not treated as relative to the
<include_directory>
-->
<!ELEMENT exclude EMPTY >
<!ATTLIST exclude
name CDATA #REQUIRED
>
<!ELEMENT include_directory (exclude*) >
<!ATTLIST include_directory
name CDATA #REQUIRED
>
<!ELEMENT passive_backup (include_directory|include_file)* >
<!ATTLIST passive_backup
supports_selective (yes|no) "no"
delete_before_restore (yes|no) "no"
base_backup_only (yes|no) "no"
>
<!ELEMENT public_backup (include_directory|include_file)* >
<!ATTLIST public_backup
delete_before_restore (yes|no) "no"
>
<!-- If the <system_backup> element is present then all executables
and resource files that were included in SIS files will be backed up.
The set of files does not need to be specified as it can be found from
package data.
They can only be restored after checking against signed hashes.
-->
<!ELEMENT system_backup >
<!-- <proxy_data_manager> indicates that the data owner represented by this
registration file has data that is accessed through a proxy which is
itself an active data owner.
-->
<!ELEMENT proxy_data_manager EMPTY >
<!ATTLIST proxy_data_manager
SID CDATA #REQUIRED
>
<!ELEMENT dbms_backup EMPTY >
<!ATTLIST dbms_backup
policy CDATA #REQUIRED
>
<!ELEMENT active_backup EMPTY >
<!ATTLIST active_backup
process_name CDATA #REQUIRED
requires_delay_to_prepare_data (yes|no) "no"
supports_selective (yes|no) "no"
supports_incremental (yes|no) "yes"
active_type (activeonly|activeandproxy|proxyonly) “activeonly”
>
<!ELEMENT restore EMPTY >
<!ATTLIST restore
requires_reboot (yes|no) "no"
>
]>
Appendix B Active Backup Client API
The active backup client class declarations can be found in the file epoc32\include\connect\abclient.h which requires epoc32\include\connect\sbdefs.h.
See also
© 2010 Symbian Foundation Limited. This document is licensed under the Creative Commons Attribution-Share Alike 2.0 license. See for the full terms of the license.
Note that this content was originally hosted on the Symbian Foundation developer wiki. | http://developer.nokia.com/community/wiki/PC_Connectivity_-_How_To_Write_Backup_Aware_Software_for_Symbian | CC-MAIN-2014-15 | refinedweb | 8,357 | 50.06 |
Eric Blake wrote: > Tom has (graciously) allowed me access to his Irix 5.3 system to attempt > to address this. Thanks for debugging this! > > The test ends up calling sprintf(tmp, "%Ld", -0.0L), but > > excuse the typo; I meant "%Lf", not "%Ld" > > > the system sprintf does not know how to print -0, so the result is > > 0.000000 and lacks -. Does it make more sense to adjust the existing > > gl_PRINTF_INFINITE_LONG_DOUBLE (which also tests for NaN) to add a test > > for negative zero, or to add a new macro gl_PRINTF_ZERO_LONG_DOUBLE? Based on this info, I would have recommended to add a separate test to m4/printf.m4, for clarity; however, in vasnprintf.m4 there are enough #ifdefs, therefore I would simply have defined NEED_PRINTF_INFINITE_LONG_DOUBLE. > At any rate, the Irix box also failed the infinite long double test, so it > already has problem with inf and/or NaN, and the place to add code for > -0.0 should be relatively easy to locate. In this situation, m4/printf.m4 needs no changes at all. Find here a proposed fix: Bruno --- lib/vasnprintf.c.orig 2008-09-13 19:02:12.000000000 +0200 +++ lib/vasnprintf.c 2008-09-13 19:01:42.000000000 +0200 @@ -255,11 +255,11 @@ #if NEED_PRINTF_INFINITE_LONG_DOUBLE && !NEED_PRINTF_LONG_DOUBLE && !defined IN_LIBINTL -/* Equivalent to !isfinite(x), but does not require libm. */ +/* Equivalent to !isfinite(x) || x == 0, but does not require libm. */ static int -is_infinitel (long double x) +is_infinite_or_zerol (long double x) { - return isnanl (x) || (x + x == x && x != 0.0L); + return isnanl (x) || x + x == x; } #endif @@ -2578,8 +2578,10 @@ # elif NEED_PRINTF_INFINITE_LONG_DOUBLE || (a.arg[dp->arg_index].type == TYPE_LONGDOUBLE /* Some systems produce wrong output for Inf, - -Inf, and NaN. */ - && is_infinitel (a.arg[dp->arg_index].a.a_longdouble)) + -Inf, and NaN. Some systems in this category + (IRIX 5.3) also do so for -0.0. Therefore we + treat this case here as well. */ + && is_infinite_or_zerol (a.arg[dp->arg_index].a.a_longdouble)) # endif )) { | http://lists.gnu.org/archive/html/bug-gnulib/2008-09/msg00130.html | CC-MAIN-2016-26 | refinedweb | 319 | 70.5 |
ASP.NET Core 2 reintroduced Razor. If this humble markup first exposed in 2010 allowing developers to embed C# and VB.NET into web pages failed to impress, the redesigned version just might. Imagine all the things developers adored about Web Forms, Model-View-Controller (MVC), and data-bound templating rolled up into one technology.
This article provides a brief Razor introduction that might convince skeptical .NET developers to consider it for their next web application.
MVC Backgrounder
Readers unfamiliar with ASP.NET’s implementation of the Model-View-Controller (MVC) may find this brief overview helpful before continuing with this article. MVC is an architectural pattern splitting a web application page into three components: model, view, and controller. Models capture the application domain, such as, user name information. Views display the model, again, exposing the user name as an HTML label in the upper left corner. Controllers manage the interaction between view and model.
This loose coupling of model, view, and controller facilitates their individual development. For example, the view’s design does not necessarily impact its associated model. The separation also simplifies unit testing for each of the components.
Implementing MVC-based applications is not without its challenges. Some find it unnecessarily more complex than the Web Forms-based predecessor. Nonetheless, coding an MVC view with Razor markup seems easier than a Web Forms page. In all likelihood, this ease inspired the new Razor – markup sans model and controller components.
Getting Started
An ASP.NET Core 2 Razor-based web application requires installing the .NET Core 2.0 SDK and upgrading to Microsoft.AspNetCore 2.0.0. Rather than explicitly installing AspNetCore directly, Visual Studio 2017 users may find upgrading to version 15.4+ a preferable option after installing the SDK. Upgrading Visual Studio exposes several new web project templates.
Once the prerequisites are in place, create a new ASP.NET Core 2.0 project.
data-src="" data-lazy-load>
After selecting the highlighted template option, Visual Studio creates the simple project which is entitled RazorDemo as shown in the Solution Explorer window.
data-src="" data-lazy-load>
Like most Visual Studio templated projects, building and executing RazorDemo requires minimum effort on the part of the developer. Perhaps the most fascinating aspect of this starter project resides in the Startup.cs method ConfigureServices. Razor pages rely on the MVC framework even if they don’t explicitly demand its expected components, such as, models and controllers.
Razor by convention assumes a Pages folder exists to house its web pages. These cshtml (or vbhtml for the VB.NET persuasion) files allow for two variations: markup only and code + markup.
A Tale of Two Pages
Razor supports two fundamental implementations of a web page. The first type is somewhat simple, an example in your project is Error.cshtml, which includes only markup. The second involves code and markup, for example Index.cshtml and Index.cshtml.cs.
Markup Only
Adding a static Razor page via Visual Studio is simple. It begins by right clicking on the project folder of interest and clicking Add followed by New Item and clicking Razor Page. This sequence, which might vary some between Visual Studio versions, brings up the following dialog.
data-src="" data-lazy-load>
Inspecting this newly added page highlights the simplicity of a basic markup-only file. While it may look similar to the View found in an MVC implementation, the mark up differs. The Razor keyword page stands out as the salient element. This enables page requests without a supporting model or controller while exploiting the popular Razor constructs.
Note: This discussion does not dwell on markup syntax for a good reason – it didn’t dramatically change. The most impressive aspect of the new Razor is everything other than the markup!
Developers may also add Razor pages by right clicking Add and selecting Add Razor Page… at the top of the presented item list. This option provides help for incorporating the Entity Framework.
Lastly, if a developer selects the Razor View when selecting a New Item, the added cshtml page may disappoint. It will contain a warning that the project needs MVC enabled. Count that as a gentle reminder that Razor View and Razor Page differ.
Code + Markup
The second type of Razor page contains a markup file with a Web Forms like code-behind file. PageModel, which resembles a hybrid MVC controller, provides the glue linking the two. Creating such a page is as simple as the markup only version except that you must check Generate PageModel class.
The markup file created when adding the Razor page, CodeMarkup.cshtml, closely resembles the markup only type with one critical difference. After page, another Razor keyword, model, follows declaring the markup’s supporting class RazorDemo.Pages.CodeMarkupModel which inherits from PageModel.
The Code-behind CodeMarkupModel class reveals both the simplicity and power of the new Razor. Exploiting it only requires learning a few concepts. Razor code-behind pages do not equate to the older Web Forms like sounding construct. PageModel more closely resembles an MVC controller.
PageModel Basics
Developers familiar with ASP.NET MVC projects will find fully functional Razor-based web pages easy to implement. This article explores these essentials via a sample order editing page.
Requirements
We satisfy our limited ambitions with a web page to edit an order as shown below.
data-src="" data-lazy-load>
This simple page allows highlighting a few new and many old features in Razor and MVC.
Preliminaries
Implementing the page only requires a few steps before coding:
- Add a Razor page via Visual Studio entitled OrderEdit with
- Generate PageModel class checked
- Use a layout page: checked with the _Layout.cshtml value
- Add the following using statements to the new OrderEditModel (OrderEdit.cshtml.cs)
- Microsoft.Extensions.Caching.Memory for temporarily maintaining state
- System.ComponentModel.DataAnnotations for validation support
- Add services.AddMemoryCache() to ConfigureServices enabling the in-memory cache
Time to code.
[BindProperty]
This attribute dramatically alters how user input reaches the server compared to most MVC applications. Instead of passing an object via an action for server-side processing, it leverages two-way data binding. Readers familiar with Model–View–ViewModel (MVVM), another architecture pattern combining the strengths of MVC with the supporting framework’s data binding features, will be comfortable with [BindProperty].
Note: For those still wishing to pass state the old, MVC way, don’t fret. It’s still possible, read Dino Esposito’s Improvements to Model Binding in ASP.NET Core to get started.
OrderEditModel begins with the definition of OrderInformation. This simple model-like class houses all the properties expected to be passed between client and server. Once defined, the markup page can naturally access order information via the OrderInformation typed Order property.
With all data-bound properties defined, accessing them on OrderEdit.cshtml view proves equally simple with a little help from asp-for and asp-validation-for as shown next.
Also note the minimal effort required to expose DisplayDate. All it required was applying @, another Razor keyword.
Handlers
Razor handles (no pun intended) the expected HTTP verbs via default naming conventions:
- OnGet/OnGetAsync
- OnPost/OnPostAsync
- OnDelete/OnDeleteAsync
- OnPut/OnPutAsync
- OnPatch/OnPatchAsync
It also supports named handlers via On<HTTP Verb><Custom Handler Name> syntax with or without an Async suffix. And if that’s not enough, consider rolling your own with a DefaultPageApplicationModelProvider.
Before inspecting the two handlers, the code-behind class constructor loads an instance of the Microsoft in-memory cache via built-in dependency management. _cache courteously remembers your order edits as you click about.
Thru the power of convention, Razor pages default any GET to OnGet or OnGetAsync, along with any POST OnPost or OnPostAsync. OrderEdit.cshtml neither contains nor requires explicit references to its supporting OnGet or OnPost methods.
Authorization
While authorization remains intuitive, Razor operates with its own API. Adding the following snippet to the Startup’s ConfigureServices method demonstrates one such page authorization arrangement.
Page level authorization possibilities remain. Fortunately, the API leverages many of the expected names and behaviors.
Almost Like MVC
As most likely apparent by now, Razor lives within the MVC framework. Our sample page leveraged several of its features: application startup, dependency injection, middleware management, Tag Helpers and model validation. Despite this commonality, some differences exist which may alter how developers approach Razor versus MVC controller pages.
API Support
Nothing explicitly precludes using PageModel for an API controller. Some might even argue it’s a perfect option to expose a service with user interface for checking configuration or errors. Nonetheless, doesn’t it seems potentially confusing to drag in the Microsoft.AspNetCore.Mvc.Razor namespace in a world expecting only Microsoft.AspNetCore.Mvc?
Folder Layout
The simplified code folder layout stands out as a shining star of the new Razor. First, the underlying magic avoids the many, many files and folders found in a typical MVC application as suggested below.
data-src="" data-lazy-load>
Adding a new page doesn’t require adding a file to the Controllers, Models, and Views folders for just a single web page.
Second, Razor avoids those pesky issues when employing hierarchical folder structures or an Area in MVC. For example, incorporation of the sample order management feature only requires the folders shown in the following screenshot and the usual routing tweaks.
data-src="" data-lazy-load>
Conclusion
This introduction into the Razor technology released with ASP.NET Core 2.0 barely scratched the surface. It hopefully covered enough ground to convince developers acquainted with the older version to reconsider. Razor now combines some of the best ideas from different technologies introduced into ASP.NET over the years. Anticipate seeing it as a compelling alternative to MVC based pages.
Load comments | https://www.red-gate.com/simple-talk/dotnet/net-development/razor-redux/ | CC-MAIN-2020-24 | refinedweb | 1,616 | 50.02 |
1. Introduction to Data Science in Python
By the end of this chapter, you will be able to explain what data science is and distinguish between supervised and unsupervised learning. You will also be able to explain what machine learning is and distinguish between regression, classification, and clustering problems. You will be able to create and manipulate different types of Python variable, including core variables, lists, and dictionaries. You will build a
for loop, print results using f-strings, and define functions. You will also import Python packages and load data in different formats using
pandas. You will also get your first taste of training a model using scikit-learn.
This very first chapter will introduce you to the field of data science and walk you through an overview of Python's core concepts and their application in the world of data science.
Introduction
Welcome to the fascinating world of data science! We are sure you must be pretty excited to start your journey and learn interesting and exciting techniques and algorithms. This is exactly what this book is intended for.
But before diving into it, let's define what data science is: it is a combination of multiple disciplines, including business, statistics, and programming, that intends to extract meaningful insights from data by running controlled experiments similar to scientific research.
The objective of any data science project is to derive valuable knowledge for the business from data in order to make better decisions. It is the responsibility of data scientists to define the goals to be achieved for a project. This requires business knowledge and expertise. In this book, you will be exposed to some examples of data science tasks from real-world datasets.
Statistics is a mathematical field used for analyzing and finding patterns from data. A lot of the newest and most advanced techniques still rely on core statistical approaches. This book will present to you the basic techniques required to understand the concepts we will be covering.
With an exponential increase in data generation, more computational power is required for processing it efficiently. This is the reason why programming is a required skill for data scientists. You may wonder why we chose Python for this Workshop. That's because Python is one of the most popular programming languages for data science. It is extremely easy to learn how to code in Python thanks to its simple and easily readable syntax. It also has an incredible number of packages available to anyone for free, such as pandas, scikit-learn, TensorFlow, and PyTorch. Its community is expanding at an incredible rate, adding more and more new functionalities and improving its performance and reliability. It's no wonder companies such as Facebook, Airbnb, and Google are using it as one of their main stacks. No prior knowledge of Python is required for this book. If you do have some experience with Python or other programming languages, then this will be an advantage, but all concepts will be fully explained, so don't worry if you are new to programming.
Application of Data Science
As mentioned in the introduction, data science is a multidisciplinary approach to analyzing and identifying complex patterns and extracting valuable insights from data. Running a data science project usually involves multiple steps, including the following:
- Defining the business problem to be solved
- Collecting or extracting existing data
- Analyzing, visualizing, and preparing data
- Training a model to spot patterns in data and make predictions
- Assessing a model's performance and making improvements
- Communicating and presenting findings and gained insights
- Deploying and maintaining a model
As its name implies, data science projects require data, but it is actually more important to have defined a clear business problem to solve first. If it's not framed correctly, a project may lead to incorrect results as you may have used the wrong information, not prepared the data properly, or led a model to learn the wrong patterns. So, it is absolutely critical to properly define the scope and objective of a data science project with your stakeholders.
There are a lot of data science applications in real-world situations or in business environments. For example, healthcare providers may train a model for predicting a medical outcome or its severity based on medical measurements, or a high school may want to predict which students are at risk of dropping out within a year's time based on their historical grades and past behaviors. Corporations may be interested to know the likelihood of a customer buying a certain product based on his or her past purchases. They may also need to better understand which customers are more likely to stop using existing services and churn. These are examples where data science can be used to achieve a clearly defined goal, such as increasing the number of patients detected with a heart condition at an early stage or reducing the number of customers canceling their subscriptions after six months. That sounds exciting, right? Soon enough, you will be working on such interesting projects.
What Is Machine Learning?
When we mention data science, we usually think about machine learning, and some people may not understand the difference between them. Machine learning is the field of building algorithms that can learn patterns by themselves without being programmed explicitly. So machine learning is a family of techniques that can be used at the modeling stage of a data science project.
Machine learning is composed of three different types of learning:
- Supervised learning
- Unsupervised learning
- Reinforcement learning
Supervised Learning
Supervised learning refers to a type of task where an algorithm is trained to learn patterns based on prior knowledge. That means this kind of learning requires the labeling of the outcome (also called the response variable, dependent variable, or target variable) to be predicted beforehand. For instance, if you want to train a model that will predict whether a customer will cancel their subscription, you will need a dataset with a column (or variable) that already contains the churn outcome (cancel or not cancel) for past or existing customers. This outcome has to be labeled by someone prior to the training of a model. If this dataset contains 5,000 observations, then all of them need to have the outcome being populated. The objective of the model is to learn the relationship between this outcome column and the other features (also called independent variables or predictor variables). Following is an example of such a dataset:
Figure 1.1: Example of customer churn dataset
The
Cancel column is the response variable. This is the column you are interested in, and you want the model to predict accurately the outcome for new input data (in this case, new customers). All the other columns are the predictor variables.
The model, after being trained, may find the following pattern: a customer is more likely to cancel their subscription after 12 months and if their average monthly spent is over
$50. So, if a new customer has gone through 15 months of subscription and is spending $85 per month, the model will predict this customer will cancel their contract in the future.
When the response variable contains a limited number of possible values (or classes), it is a classification problem (you will learn more about this in Chapter 3, Binary Classification, and Chapter 4, Multiclass Classification with RandomForest). The model will learn how to predict the right class given the values of the independent variables. The churn example we just mentioned is a classification problem as the response variable can only take two different values:
yes or
no.
On the other hand, if the response variable can have a value from an infinite number of possibilities, it is called a regression problem.
An example of a regression problem is where you are trying to predict the exact number of mobile phones produced every day for some manufacturing plants. This value can potentially range from 0 to an infinite number (or a number big enough to have a large range of potential values), as shown in Figure 1.2.
Figure 1.2: Example of a mobile phone production dataset
In the preceding figure, you can see that the values for
Daily output can take any value from
15000 to more than
50000. This is a regression problem, which we will look at in Chapter 2, Regression.
Unsupervised Learning
Unsupervised learning is a type of algorithm that doesn't require any response variables at all. In this case, the model will learn patterns from the data by itself. You may ask what kind of pattern it can find if there is no target specified beforehand.
This type of algorithm usually can detect similarities between variables or records, so it will try to group those that are very close to each other. This kind of algorithm can be used for clustering (grouping records) or dimensionality reduction (reducing the number of variables). Clustering is very popular for performing customer segmentation, where the algorithm will look to group customers with similar behaviors together from the data. Chapter 5, Performing Your First Cluster Analysis, will walk you through an example of clustering analysis.
Reinforcement Learning
Reinforcement learning is another type of algorithm that learns how to act in a specific environment based on the feedback it receives. You may have seen some videos where algorithms are trained to play Atari games by themselves. Reinforcement learning techniques are being used to teach the agent how to act in the game based on the rewards or penalties it receives from the game.
For instance, in the game Pong, the agent will learn to not let the ball drop after multiple rounds of training in which it receives high penalties every time the ball drops.
Note
Reinforcement learning algorithms are out of scope and will not be covered in this book.
Overview of Python
As mentioned earlier, Python is one of the most popular programming languages for data science. But before diving into Python's data science applications, let's have a quick introduction to some core Python concepts.
Types of Variable
In Python, you can handle and manipulate different types of variables. Each has its own specificities and benefits. We will not go through every single one of them but rather focus on the main ones that you will have to use in this book. For each of the following code examples, you can run the code in Google Colab to view the given output.
Numeric Variables
The most basic variable type is numeric. This can contain integer or decimal (or float) numbers, and some mathematical operations can be performed on top of them.
Let's use an integer variable called
var1 that will take the value
8 and another one called
var2 with the value
160.88, and add them together with the
+ operator, as shown here:
var1 = 8 var2 = 160.88 var1 + var2
You should get the following output:
Figure 1.3: Output of the addition of two variables
In Python, you can perform other mathematical operations on numerical variables, such as multiplication (with the
* operator) and division (with
/).
Text Variables
Another interesting type of variable is
string, which contains textual information. You can create a variable with some specific text using the single or double quote, as shown in the following example:
var3 = 'Hello, ' var4 = 'World'
In order to display the content of a variable, you can call the
print() function:
print(var3) print(var4)
You should get the following output:
Figure 1.4: Printing the two text variables
Python also provides an interface called f-strings for printing text with the value of defined variables. It is very handy when you want to print results with additional text to make it more readable and interpret results. It is also quite common to use f-strings to print logs. You will need to add
f before the quotes (or double quotes) to specify that the text will be an f-string. Then you can add an existing variable inside the quotes and display the text with the value of this variable. You need to wrap the variable with curly brackets,
{}. For instance, if we want to print
Text: before the values of
var3 and
var4, we will write the following code:
print(f"Text: {var3} {var4}!")
You should get the following output:
Figure 1.5: Printing with f-strings
You can also perform some text-related transformations with string variables, such as capitalizing or replacing characters. For instance, you can concatenate the two variables together with the
+ operator:
var3 + var4
You should get the following output:
Figure 1.6: Concatenation of the two text variables
Python List
Another very useful type of variable is the list. It is a collection of items that can be changed (you can add, update, or remove items). To declare a list, you will need to use square brackets,
[], like this:
var5 = ['I', 'love', 'data', 'science'] print(var5)
You should get the following output:
Figure 1.7: List containing only string items
A list can have different item types, so you can mix numerical and text variables in it:
var6 = ['Packt', 15019, 2020, 'Data Science'] print(var6)
You should get the following output:
Figure 1.8: List containing numeric and string items
An item in a list can be accessed by its index (its position in the list). To access the first (index 0) and third elements (index 2) of a list, you do the following:
print(var6[0]) print(var6[2])
Note
In Python, all indexes start at
0.
You should get the following output:
Figure 1.9: The first and third items in the var6 list
Python provides an API to access a range of items using the
: operator. You just need to specify the starting index on the left side of the operator and the ending index on the right side. The ending index is always excluded from the range. So, if you want to get the first three items (index 0 to 2), you should do as follows:
print(var6[0:3])
You should get the following output:
Figure 1.10: The first three items of var6
You can also iterate through every item of a list using a
for loop. If you want to print every item of the
var6 list, you should do this:
for item in var6: print(item)
You should get the following output:
Figure 1.11: Output of the for loop
You can add an item at the end of the list using the
.append() method:
var6.append('Python') print(var6)
You should get the following output:
Figure 1.12: Output of var6 after inserting the 'Python' item
To delete an item from the list, you use the
.remove() method:
var6.remove(15019) print(var6)
You should get the following output:
Figure 1.13: Output of var6 after removing the '15019' item
Python Dictionary
Another very popular Python variable used by data scientists is the dictionary type. For example, it can be used to load JSON data into Python so that it can then be converted into a DataFrame (you will learn more about the JSON format and DataFrames in the following sections). A dictionary contains multiple elements, like a list, but each element is organized as a key-value pair. A dictionary is not indexed by numbers but by keys. So, to access a specific value, you will have to call the item by its corresponding key. To define a dictionary in Python, you will use curly brackets,
{}, and specify the keys and values separated by
:, as shown here:
var7 = {'Topic': 'Data Science', 'Language': 'Python'} print(var7)
You should get the following output:
Figure 1.14: Output of var7
To access a specific value, you need to provide the corresponding key name. For instance, if you want to get the value
Python, you do this:
var7['Language']
You should get the following output:
Figure 1.15: Value for the 'Language' key
Note
Each key-value pair in a dictionary needs to be unique.
Python provides a method to access all the key names from a dictionary,
.keys(), which is used as shown in the following code snippet:
var7.keys()
You should get the following output:
Figure 1.16: List of key names
There is also a method called
.values(), which is used to access all the values of a dictionary:
var7.values()
You should get the following output:
Figure 1.17: List of values
You can iterate through all items from a dictionary using a
for loop and the
.items() method, as shown in the following code snippet:
for key, value in var7.items(): print(key) print(value)
You should get the following output:
Figure 1.18: Output after iterating through the items of a dictionary
You can add a new element in a dictionary by providing the key name like this:
var7['Publisher'] = 'Packt' print(var7)
You should get the following output:
Figure 1.19: Output of a dictionary after adding an item
You can delete an item from a dictionary with the
del command:
del var7['Publisher'] print(var7)
You should get the following output:
Figure 1.20: Output of a dictionary after removing an item
In Exercise 1.01, we will be looking to use these concepts that we've just looked at.
Note
If you are interested in exploring Python in more depth, head over to our website () to get yourself the Python Workshop.
Exercise 1.01: Creating a Dictionary That Will Contain Machine Learning Algorithms
In this exercise, we will create a dictionary using Python that will contain a collection of different machine learning algorithms that will be covered in this book.
The following steps will help you complete the exercise:
Note
Every exercise and activity in this book is to be executed on Google Colab.
- Open on a new Colab notebook.
- Create a list called
algorithmthat will contain the following elements:
Linear Regression,
Logistic Regression,
RandomForest, and
a3c:
algorithm = ['Linear Regression', 'Logistic Regression', 'RandomForest', 'a3c']
- Now, create a list called
learningthat will contain the following elements:
Supervised,
Supervised,
Supervised, and
Reinforcement:
learning = ['Supervised', 'Supervised', 'Supervised', 'Reinforcement']
- Create a list called
algorithm_typethat will contain the following elements:
Regression,
Classification,
Regressionor
Classification, and
Game AI:
algorithm_type = ['Regression', 'Classification', 'Regression or Classification', 'Game AI']
- Add an item called
k-meansinto the
algorithmlist using the
.append()method:
algorithm.append('k-means')
- Display the content of
algorithmusing the
print()function:
print(algorithm)
You should get the following output:
Figure 1.21: Output of 'algorithm'
From the preceding output, we can see that we added the
k-meansitem to the list.
- Now, add the
Unsuperviseditem into the
learninglist using the
.append()method:
learning.append('Unsupervised')
- Display the content of
learningusing the
print()function:
print(learning)
You should get the following output:
Figure 1.22: Output of 'learning'
From the preceding output, we can see that we added the
Unsuperviseditem into the list.
- Add the
Clusteringitem into the
algorithm_typelist using the
.append()method:
algorithm_type.append('Clustering')
- Display the content of
algorithm_typeusing the
print()function:
print(algorithm_type)
You should get the following output:
Figure 1.23: Output of 'algorithm_type'
From the preceding output, we can see that we added the
Clusteringitem into the list.
- Create an empty dictionary called
machine_learningusing curly brackets,
{}:
machine_learning = {}
- Create a new item in
machine_learningwith the key as
algorithmand the value as all the items from the
algorithmlist:
machine_learning['algorithm'] = algorithm
- Display the content of
machine_learningusing the
print()function.
print(machine_learning)
You should get the following output:
Figure 1.24: Output of 'machine_learning'
From the preceding output, we notice that we have created a dictionary from the
algorithmlist.
- Create a new item in
machine_learningwith the key as
learningand the value as all the items from the
learninglist:
machine_learning['learning'] = learning
- Now, create a new item in
machine_learningwith the key as
algorithm_typeand the value as all the items from the algorithm_type list:
machine_learning['algorithm_type'] = algorithm_type
- Display the content of
machine_learningusing the
print()function.
print(machine_learning)
You should get the following output:
Figure 1.25: Output of 'machine_learning'
- Remove the
a3citem from the
algorithmkey using the
.remove()method:
machine_learning['algorithm'].remove('a3c')
- Display the content of the
algorithmitem from the
machine_learningdictionary using the
print()function:
print(machine_learning['algorithm'])
You should get the following output:
Figure 1.26: Output of 'algorithm' from 'machine_learning'
- Remove the
Reinforcementitem from the
learningkey using the
.remove()method:
machine_learning['learning'].remove('Reinforcement')
- Remove the
Game AIitem from the
algorithm_typekey using the
.remove()method:
machine_learning['algorithm_type'].remove('Game AI')
- Display the content of
machine_learningusing the
print()function:
print(machine_learning)
You should get the following output:
Figure 1.27: Output of 'machine_learning'
You have successfully created a dictionary containing the machine learning algorithms that you will come across in this book. You learned how to create and manipulate Python lists and dictionaries.
In the next section, you will learn more about the two main Python packages used for data science:
pandas
scikit-learn
Python for Data Science
Python offers an incredible number of packages for data science. A package is a collection of prebuilt functions and classes shared publicly by its author(s). These packages extend the core functionalities of Python. The Python Package Index () lists all the packages available in Python.
In this section, we will present to you two of the most popular ones:
pandas and
scikit-learn.
The pandas Package
The pandas package provides an incredible amount of APIs for manipulating data structures. The two main data structures defined in the
pandas package are
DataFrame and
Series.
DataFrame and Series
A
DataFrame is a tabular data structure that is represented as a two-dimensional table. It is composed of rows, columns, indexes, and cells. It is very similar to a sheet in Excel or a table in a database:
Figure 1.28: Components of a DataFrame
In Figure 1.28, there are three different columns:
algorithm,
learning, and
type. Each of these columns (also called variables) contains a specific type of information. For instance, the
algorithm variable lists the names of different machine learning algorithms.
A row stores the information related to a record (also called an observation). For instance, row number
2 (index number
2) refers to the
RandomForest record and all its attributes are stored in the different columns.
Finally, a cell is the value of a given row and column. For example,
Clustering is the value of the cell of the row index
2 and the
type column. You can see it as the intersection of a specified row and column.
So, a DataFrame is a structured representation of some data organized by rows and columns. A row represents an observation and each column contains the value of its attributes. This is the most common data structure used in data science.
In pandas, a DataFrame is represented by the
DataFrame class. A
pandas DataFrame is composed of
pandas Series, which are 1-dimensional arrays. A
pandas Series is basically a single column in a DataFrame.
Data is usually classified into two groups: structured and unstructured. Think of structured data as database tables or Excel spreadsheets where each column and row has a predefined structure. For example, in a table or spreadsheet that lists all the employees of a company, every record will follow the same pattern, such as the first column containing the date of birth, the second and third ones being for first and last names, and so on.
On the other hand, unstructured data is not organized with predefined and static patterns. Text and images are good examples of unstructured data. If you read a book and look at each sentence, it will not be possible for you to say that the second word of a sentence is always a verb or a person's name; it can be anything depending on how the author wanted to convey the information they wanted to share. Each sentence has its own structure and will be different from the last. Similarly, for a group of images, you can't say that pixels 20 to 30 will always represent the eye of a person or the wheel of a car: it will be different for each image.
Data can come from different data sources: there could be flat files, data storage, or Application Programming Interface (API) feeds, for example. In this book, we will work with flat files such as CSVs, Excel spreadsheets, or JSON. All these types of files are storing information with their own format and structure.
We'll have a look at the CSV file first.
CSV Files
CSV files use the comma character—
,—to separate columns and newlines for a new row. The previous example of a DataFrame would look like this in a CSV file:
algorithm,learning,type Linear Regression,Supervised,Regression Logistic Regression,Supervised,Classification RandomForest,Supervised,Regression or Classification k-means,Unsupervised,Clustering
In Python, you need to first import the packages you require before being able to use them. To do so, you will have to use the
import command. You can create an alias of each imported package using the
as keyword. It is quite common to import the
pandas package with the alias
pd:
import pandas as pd
pandas provides a
.read_csv() method to easily load a CSV file directly into a DataFrame. You just need to provide the path or the URL to the CSV file:
pd.read_csv('')
You should get the following output:
Figure 1.29: DataFrame after loading a CSV file
Note
In this book, we will be loading datasets stored in the Packt GitHub repository:.
GitHub wraps stored data into its own specific format. To load the original version of a dataset, you will need to load the raw version of it by clicking on the Raw button and copying the URL provided on your browser.
Have a look at Figure 1.30:
Figure 1.30: Getting the URL of a raw dataset on GitHub
Excel Spreadsheets
Excel is a Microsoft tool and is very popular in the industry. It has its own internal structure for recording additional information, such as the data type of each cell or even Excel formulas. There is a specific method in pandas to load Excel spreadsheets called
.read_excel():
pd.read_excel('')
You should get the following output:
Figure 1.31: Dataframe after loading an Excel spreadsheet
JSON
JSON is a very popular file format, mainly used for transferring data from web APIs. Its structure is very similar to that of a Python dictionary with key-value pairs. The example DataFrame we used before would look like this in JSON format:
{ "algorithm":{ "0":"Linear Regression", "1":"Logistic Regression", "2":"RandomForest", "3":"k-means" }, "learning":{ "0":"Supervised", "1":"Supervised", "2":"Supervised", "3":"Unsupervised" }, "type":{ "0":"Regression", "1":"Classification", "2":"Regression or Classification", "3":"Clustering" } }
As you may have guessed, there is a
pandas method for reading JSON data as well, and it is called
.read_json():
pd.read_json('')
You should get the following output:
Figure 1.32: Dataframe after loading JSON data
pandas provides more methods to load other types of files. The full list can be found in the following documentation:.
pandas is not limited to only loading data into DataFrames; it also provides a lot of other APIs for creating, analyzing, or transforming DataFrames. You will be introduced to some of its most useful methods in the following chapters.
Exercise 1.02: Loading Data of Different Formats into a pandas DataFrame
In this exercise, we will practice loading different data formats, such as CSV, TSV, and XLSX, into pandas DataFrames. The dataset we will use is the Top 10 Postcodes for the First Home Owner Grants dataset (this is a grant provided by the Australian government to help first-time real estate buyers). It lists the 10 postcodes (also known as zip codes) with the highest number of First Home Owner grants.
In this dataset, you will find the number of First Home Owner grant applications for each Australian postcode and the corresponding suburb.
Note
This dataset can be found on our GitHub repository at.
Also, it is publicly available here:.
The following steps will help you complete the exercise:
- Open a new Colab notebook.
- Import the pandas package, as shown in the following code snippet:
import pandas as pd
- Create a new variable called
csv_urlcontaining the URL to the raw CSV file:
csv_url = ''
- Load the CSV file into a DataFrame using the pandas
.read_csv()method. The first row of this CSV file contains the name of the file, as you can see in the following screenshot. You will need to exclude it by using the
skiprows=1parameter. Save the result in a variable called
csv_dfand print it:
csv_df = pd.read_csv(csv_url, skiprows=1) csv_df
You should get the following output:
Figure 1.33: The DataFrame after loading the CSV file
- Create a new variable called
tsv_urlcontaining the URL to the raw TSV file:
tsv_url = ''
Note
A TSV file is similar to a CSV file but instead of using the comma character (
,) as a separator, it uses the tab character (
\t).
- Load the TSV file into a DataFrame using the pandas .
read_csv()method and specify the
skiprows=1and
sep='\t'parameters. Save the result in a variable called
tsv_dfand print it:
tsv_df = pd.read_csv(tsv_url, skiprows=1, sep='\t') tsv_df
You should get the following output:
Figure 1.34: The DataFrame after loading the TSV file
- Create a new variable called
xlsx_urlcontaining the URL to the raw Excel spreadsheet:
xlsx_url = ''
- Load the Excel spreadsheet into a DataFrame using the pandas
.read_excel()method. Save the result in a variable called
xlsx_dfand print it:
xlsx_df = pd.read_excel(xlsx_url) xlsx_df
You should get the following output:
Figure 1.35: Display of the DataFrame after loading the Excel spreadsheet
By default,
.read_excel()loads the first sheet of an Excel spreadsheet. In this example, the data is actually stored in the second sheet.
- Load the Excel spreadsheet into a Dataframe using the pandas
.read_excel()method and specify the
skiprows=1and
sheetname=1parameters. Save the result in a variable called
xlsx_df1and print it:
xlsx_df1 = pd.read_excel(xlsx_url, skiprows=1, sheet_name=1) xlsx_df1
You should get the following output:
Figure 1.36: The DataFrame after loading the second sheet of the Excel spreadsheet
In this exercise, we learned how to load the Top 10 Postcodes for First Home Buyer Grants dataset from different file formats.
In the next section, we will be introduced to scikit-learn.
Scikit-Learn
Scikit-learn (also referred to as
sklearn) is another extremely popular package used by data scientists. The main purpose of
sklearn is to provide APIs for processing data and training machine learning algorithms. But before moving ahead, we need to know what a model is.
What Is a Model?
A machine learning model learns patterns from data and creates a mathematical function to generate predictions. A supervised learning algorithm will try to find the relationship between a response variable and the given features.
Have a look at the following example.
A mathematical function can be represented as a function, ƒ(), that is applied to some input variables, X (which is composed of multiple features), and will calculate an output (or prediction), ŷ:
Figure 1.37: Function f(X)
The function, ƒ(), can be quite complex and have different numbers of parameters. If we take a linear regression (this will be presented in more detail in Chapter 2, Regression) as an example, the model parameters can be represented as W=( w1, w2, ... , wn). So, the function we saw earlier will become as follows:
Figure 1.38: Function for linear regression
A machine learning algorithm will receive some examples of input X with the relevant output, y, and its goal will be to find the values of ( w1, w2, ... , wn) that will minimize the difference between its prediction, ŷ and the true output, y.
The previous formulas can be a bit intimidating, but this is actually quite simple. Let's say we have a dataset composed of only one target variable y and one feature X, such as the following one:
Figure 1.39: Example of a dataset with one target variable and one feature
If we fit a linear regression on this dataset, the algorithm will try to find a solution for the following equation:
Figure 1.40: Function f(x) for linear regression fitting on a dataset
So, it just needs to find the values of the
w
0 and
w1 parameters that will approximate the data as closely as possible. In this case, the algorithm may come up with
w
o
= 0 and
w
1
= 10. So, the function the model learns will be as follows:
Figure 1.41: Function f(x) using estimated values
We can visualize this on the same graph as for the data:
Figure 1.42: Fitted linear model on the example dataset
We can see that the fitted model (the orange line) is approximating the original data quite closely. So, if we predict the outcome for a new data point, it will be very close to the true value. For example, if we take a point that is close to 5 (let's say its values are
x = 5.1 and
y = 48), the model will predict the following:
Figure 1.43: Model prediction
This value is actually very close to the ground truth, 48 (red circle). So, our model prediction is quite accurate.
This is it. It is quite simple, right? In general, a dataset will have more than one feature, but the logic will be the same: the trained model will try to find the best parameters for each variable to get predictions as close as possible to the true values.
We just saw an example of linear models, but there are actually other types of machine learning algorithms, such as tree-based or neural networks, that can find more complex patterns from data.
Model Hyperparameters
On top of the model parameters that are learned automatically by the algorithm (now you understand why we call it machine learning), there is also another type of parameter called the hyperparameter. Hyperparameters cannot be learned by the model. They are set by data scientists in order to define some specific conditions for the algorithm learning process. These hyperparameters are different for each family of algorithms and they can, for instance, help fast-track the learning process or limit the risk of overfitting. In this book, you will learn how to tune some of these machine learning hyperparameters.. You will see a simple random forest example in this chapter, but all of these algorithms will be explained in detail in later chapters of the book.
sklearn groups algorithms by family. For instance,
RandomForest and
GradientBoosting are part of the
ensemble module. In order to make use of an algorithm, you will need to import it first like this:
from sklearn.ensemble import RandomForestClassifier
Another reason why
sklearn is so popular is that all the algorithms follow the exact same API structure. So, once you have learned how to train one algorithm, it is extremely easy to train another one with very minimal code changes. With
sklearn, there are four main steps to train a machine learning model:
- Instantiate a model with specified hyperparameters: this will configure the machine learning model you want to train.
- Train the model with training data: during this step, the model will learn the best parameters to get predictions as close as possible to the actual values of the target.
- Predict the outcome from input data: using the learned parameter, the model will predict the outcome for new data.
- Assess the performance of the model predictions: for checking whether the model learned the right patterns to get accurate predictions.
Note
In a real project, there might be more steps depending on the situation, but for simplicity, we will stick with these four for now. You will learn the remaining ones in the following chapters.
As mentioned before, each algorithm will have its own specific hyperparameters that can be tuned. To instantiate a model, you just need to create a new variable from the class you imported previously and specify the values of the hyperparameters. If you leave the hyperparameters blank, the model will use the default values specified by
sklearn.
It is recommended to at least set the
random_state hyperparameter in order to get reproducible results every time that you have to run the same code:
rf_model = RandomForestClassifier(random_state=1)
The second step is to train the model with some data. In this example, we will use a simple dataset that classifies 178 instances of Italian wines into 3 categories based on 13 features. This dataset is part of the few examples that
sklearn provides within its API. We need to load the data first:
from sklearn.datasets import load_wine features, target = load_wine(return_X_y=True)
Then using the
.fit() method to train the model, you will provide the features and the target variable as input:
rf_model.fit(features, target)
You should get the following output:
Figure 1.44: Logs of the trained Random Forest model
In the preceding output, we can see a Random Forest model with the default hyperparameters. You will be introduced to some of them in Chapter 4, Multiclass Classification with RandomForest.
Once trained, we can use the
.predict() method to predict the target for one or more observations. Here we will use the same data as for the training step:
preds = rf_model.predict(features) preds
You should get the following output:
Figure 1.45: Predictions of the trained Random Forest model
From the preceding output, you can see that the 178 different wines in the dataset have been classified into one of the three different wine categories. The first lot of wines have been classified as being in category 0, the second lot are category 1, and the last lot are category 2. At this point, we do not know what classes 0, 1, or 2 represent (in the context of the "type" of wine in each category), but finding this out would form part of the larger data science project.
Finally, we want to assess the model's performance by comparing its predictions to the actual values of the target variable. There are a lot of different metrics that can be used for assessing model performance, and you will learn more about them later in this book. For now, though, we will just use a metric called accuracy. This metric calculates the ratio of correct predictions to the total number of observations:
from sklearn.metrics import accuracy_score accuracy_score(target, preds)
You should get the following output
Figure 1.46: Accuracy of the trained Random Forest model
In this example, the Random Forest model learned to predict correctly all the observations from this dataset; it achieves an accuracy score of
1 (that is, 100% of the predictions matched the actual true values).
It's as simple as that! This may be too good to be true. In the following chapters, you will learn how to check whether the trained models are able to accurately predict unseen or future data points or if they have only learned the specific patterns of this input data (also called overfitting).
Exercise 1.03: Predicting Breast Cancer from a Dataset Using sklearn
In this exercise, we will build a machine learning classifier using
RandomForest from
sklearn to predict whether the breast cancer of a patient is malignant (harmful) or benign (not harmful).
The dataset we will use is the Breast Cancer Wisconsin (Diagnostic) dataset, which is available directly from the
sklearn package at.
The following steps will help you complete the exercise:
- Open a new Colab notebook.
- Import the
load_breast_cancerfunction from
sklearn.datasets:
from sklearn.datasets import load_breast_cancer
- Load the dataset from the
load_breast_cancerfunction with the
return_X_y=Trueparameter to return the features and response variable only:
features, target = load_breast_cancer(return_X_y=True)
- Print the variable features:
print(features)
You should get the following output:
Figure 1.47: Output of the variable features
The preceding output shows the values of the features. (You can learn more about the features from the link given previously.)
- Print the
targetvariable:
print(target)
You should get the following output:
Figure 1.48: Output of the variable target
The preceding output shows the values of the target variable. There are two classes shown for each instance in the dataset. These classes are
0and
1, representing whether the cancer is malignant or benign.
- Import the
RandomForestClassifierclass from
sklearn.ensemble:
from sklearn.ensemble import RandomForestClassifier
- Create a new variable called
seed, which will take the value
888(chosen arbitrarily):
seed = 888
- Instantiate
RandomForestClassifierwith the
random_state=seedparameter and save it into a variable called
rf_model:
rf_model = RandomForestClassifier(random_state=seed)
- Train the model with the
.fit()method with
featuresand
targetas parameters:
rf_model.fit(features, target)
You should get the following output:
Figure 1.49: Logs of RandomForestClassifier
- Make predictions with the trained model using the
.predict()method and
featuresas a parameter and save the results into a variable called
preds:
preds = rf_model.predict(features)
- Print the
predsvariable:
print(preds)
You should get the following output:
Figure 1.50: Predictions of the Random Forest model
The preceding output shows the predictions for the training set. You can compare this with the actual target variable values shown in Figure 1.48.
- Import the
accuracy_scoremethod from
sklearn.metrics:
from sklearn.metrics import accuracy_score
- Calculate
accuracy_score()with
targetand
predsas parameters:
accuracy_score(target, preds)
You should get the following output:
Figure 1.51: Accuracy of the model
You just trained a Random Forest model using
sklearn APIs and achieved an accuracy score of
1 in classifying breast cancer observations.
Activity 1.01: Train a Spam Detector Algorithm
You are working for an email service provider and have been tasked with training an algorithm that recognizes whether an email is spam or not from a given dataset and checking its performance.
In this dataset, the authors have already created 57 different features based on some statistics for relevant keywords in order to classify whether an email is spam or not.
Note
The dataset was originally shared by Mark Hopkins, Erik Reeber, George Forman, and Jaap Suermondt:.
You can download it from the Packt GitHub at.
The following steps will help you to complete this activity:
- Import the required libraries.
- Load the dataset using
.pd.read_csv().
- Extract the response variable using .
pop()from
pandas. This method will extract the column provided as a parameter from the DataFrame. You can then assign it a variable name, for example,
target = df.pop('class').
- Instantiate
RandomForestClassifier.
- Train a Random Forest model to predict the outcome with .
fit().
- Predict the outcomes from the input data using
.predict().
- Calculate the accuracy score using
accuracy_score.
The output will be similar to the following:
Figure 1.52: Accuracy score for spam detector
Note
The solution to this activity can be found at the following address:.
Summary
This chapter provided you with an overview of what data science is in general. We also learned the different types of machine learning algorithms, including supervised and unsupervised, as well as regression and classification. We had a quick introduction to Python and how to manipulate the main data structures (lists and dictionaries) that will be used in this book.
Then we walked you through what a DataFrame is and how to create one by loading data from different file formats using the famous pandas package. Finally, we learned how to use the sklearn package to train a machine learning model and make predictions with it.
This was just a quick glimpse into the fascinating world of data science. In this book, you will learn much more and discover new techniques for handling data science projects from end to end.
The next chapter will show you how to perform a regression task on a real-world dataset. | https://www.packtpub.com/product/the-data-science-workshop/9781838981266 | CC-MAIN-2020-40 | refinedweb | 7,287 | 52.7 |
,
a customer reported a problem in the XamSvg component.
It happens to be a problem with the assembly name chosen by the customer for an android app, containing the Android word. The customer renamed both the namespace and the assembly name using the Android application property pane.
But after saving changes in this pane, if you reopen it, you can verify that the old previous value of "Assembly Name" is still there.
Microsoft Visual Studio Enterprise 2017
Version 15.2 (26430.15) Release
VisualStudio.15.Release/15.2.0+26430.15
Microsoft .NET Framework
Version 4.7.02046
Installed Version: Enterprise.
*** This bug has been marked as a duplicate of bug 57653 *** | https://bugzilla.xamarin.com/58/58205/bug.html | CC-MAIN-2021-39 | refinedweb | 112 | 60.11 |
aeyrium_sensor 1.0.7
A Flutter sensor plugin which provide easy access to the Pitch and Roll on Android and iOS devices.
Flutter Aeyrium Sensor Plugin #
A Flutter sensor plugin which provide easy access to the Pitch and Roll on Android and iOS devices. It was made using TYPE_ROTATION_VECTOR sensor on Android and DeviceMotion on iOS.
Import #
To use this plugin, add
aeyrium_sensor as a dependency in your pubspec.yaml file. For example:
dependencies: aeyrium_sensor: ^1.0.7
Usage #
import 'package:aeyrium_sensor/aeyrium_sensor.dart'; AeyriumSensor.sensorEvents.listen((SensorEvent event) { //do something with the event , values expressed in radians print("Pitch ${event.pitch} and Roll ${event.roll}") });
Real Demo #
We developed this plugin to use it on our Attitude indicator screen.
Issues #
Please file any issues, bugs or feature request as an issue on our GitHub page.
Author #
This Aeyrium Sensor plugin for Flutter is developed by Aeyrium Inc | https://pub.dev/packages/aeyrium_sensor | CC-MAIN-2020-45 | refinedweb | 148 | 50.63 |
Coding principles, designs, and styles
Overarching Principles
- Care about quality. Care about code quality, design quality, and user experience. Strive for excellence.
- Lets build something that we can be truly proud of. A product that gives us a great reputation.
- Readability and maintainability are of primary importance. Don’t be clever, instead be clear. Don’t be sloppy.
- Use source-level comments generously to document the design. Comment each class, method, and “logical steps” within methods. What you are striving to document is the “Why?” and “How?” questions.
- Test early, test often.
- Thou shall not make hard to use classes/modules. Pull complexity into a class, rather than pushing it onto the user of the class. Make interfaces brain-dead simple to understand and use.
Bread and Butter
- Strive to make code naturally readable via class, method, and variable names. This is in addition to good commenting.
- Use a consistent code style within the app. Use the dominant style within a file.
- Write production quality code. Don’t assume you’ll have time sometime later to clean it up.
- Don’t check in code that has warnings. Resolve them.
- Make changes in small incremental steps. When a step is stable/complete, check it in your local git clone. Push the local checkins to the repo when they are production quality — strive for daily pushes. The goal here is to keep everyone in sync, but without breaking things.
- Add “TODO:” comments to document work that has been temporarily skipped.
- Don’t duplicate code. If you ever find yourself copying a chunk of code, pasting it and then making a few minor changes. Stop, refactor, and parameterise the differences.
- Methods should be small. Use this as a general principle, don’t abuse it. It’s fine for a method to be large, if it should be.
- Never put domain-specific logic within a general purpose class. E.g. you shouldn’t have a general dialog class do something like, “if (fromActivity instanceOf BooActivity) {}”.
- Strive to use the “Locality Principle” — group related code (classes, methods, blocks within methods, and variables) together. This also applies to delegate/call-back interfaces. It is better to use anonymous classes (declared at the point of use) rather than declaring the interface in the class definition — don’t do this: public class FooActivity extends BaseActivity implements VerticalPager.OnScrollListener.
This or That, But Let’s Do It This Way
- Use 4 spaces rather than tabs.
- Use whitespace and comments to make “logical steps” stand out. In the same vain, put scope brackets “{“, “}” on their own lines. Vertical whitespace is not your enemy.
- use camelCase for variable and method names. “Upper camelCase” for Class names. Lowercase for package names.
- Start member variables with an “m” — mMemberVariable.
- Start static variables with an “s” — sStaticVariable.
- Use scope brackets even for single line ifs, for-loops, while-loops, etc. Its just too easy to mess up the scoping of these statements. The brackets also make the blocks stand out better. | https://medium.com/@ravidsrk/coding-principles-designs-and-styles-2098204987db | CC-MAIN-2019-30 | refinedweb | 497 | 70.29 |
This is the manual for users of XML-RPC for C/C++.
The manual documents all current and past releases of XML-RPC for C/C++ and even planned future releases. Each part of the manual tells you to what releases it applies. Since the main difference between releases is that newer ones have more features, this mainly means that the description of a feature tells you in what release it was added to the package.
Compared to the more common system of distributing manuals keyed to particular releases, this makes the manual harder to use for some users (to wit, a user who has no intention of using any but one particular release), but it allows for a higher quality manual for past releases, with the same publication effort. It also allows additional uses: writing portable code and discovering when you could benefit by moving to a newer release.
For more information about the document, see About This Document.
XML-RPC for C/C++ is a software package of programming libraries to help a C or C++ program use XML-RPC. In particular, a C/C++ programmer can easily write a program to be an XML-RPC client or server.
XML-RPC for C/C++ is also known as Xmlrpc-c.
XML-RPC is a standard network protocol that computers can use to talk to each other in a remote procedure call fashion. Remote procedure call essentially means that a program on one computer runs a program on another computer. But a simpler way of looking at this kind of network protocol is just that you have clients and servers. A client makes individual isolated requests of a server. A server sits around waiting for a request to arrive from some client, does what the request asks, and sends a response. It then goes back to waiting for the next request.
Here are some examples of remote procedure call (RPC) style communications:
Here are some kinds of communication that are not RPC:
The original RPC protocol is the ONC RPC protocol -- the one that NFS (the network fileystem protocol) uses. It's often called "Sun RPC" because Sun invented and promulgated it. The ONC RPC protocol is layered over UDP or sometimes TCP and uses a machine-friendly bits and bytes format, just like the TCP/IP layers under it.
XML-RPC differs from ONC RPC in that it encodes the information in the requests and responses in XML. That means they are human friendly -- XML is human-readable text, so a human can readily see what's going on from a network trace and quickly write code to create and decipher XML-RPC streams. Of course, the tradeoff is that XML-RPC uses way more network and computation resources than ONC RPC. Because XML-RPC is meant to be used for relatively small and infrequent transactions, this is thought not to matter.
In XML-RPC, the aforementioned XML is transported via HTTP (the protocol whose principal purpose is to implement web serving -- web browsing is a form of RPC, after all). HTTP is normally carried over TCP, which is carried over IP.
There are lots of servers in the world that use the XML-RPC protocol and lots of programs and programming libraries from which people can build XML-RPC-based servers and clients.
There are also other HTTP-based RPC protocols. SOAP and CORBA are the most famous. REST-RPC is a more recent entry.
For more information on XML-RPC, see The XML-RPC web site and The XML-RPC Howto. The latter includes information (with examples) on implementing XML-RPC clients and servers in languages other than C and C++, which is all that is covered in this document.
The function libraries in XML-RPC For C/C++ (Xmlrpc-c) let you write a program that makes XML-RPC calls (a client) or executes XML-RPC calls (a server program) at any of various levels of understanding of the XML-RPC protocol.
Here are some examples of client and server code.
This is a list of the function libraries Xmlrpc-c provides, with links to the manual for each.
There are two sets of libraries -- C and C++. You can of course use the C libraries in a C++ program, but you cannot in general mix the two -- you use either the C Xmlrpc-c facilities or the C++ Xmlrpc-c facilities. The C++ libraries depend heavily on the C libraries, but apart from having to install and link to the C libraries, you won't see that from the outside.
The C++ libraries were all new in Xmlrpc-c 1.03 (June 2005).
There is an older C++ facility, which is just a thin wrapper around the C libraries. We do not document it in this manual or recommend it, but it remains part of Xmlrpc-c for backward compatibility. This library consists in the header file xmlrpc-c/oldcppwrapper.hpp (fka XmlRpcCpp.h) and the library libxmlrpc_cpp.
For information common to all the libraries, see General Library Information - C
For information common to all the libraries, see General Library Information - C++
Xmlrpc-c comes with a few utility programs that you can use to diagnose problems or learn about XML-RPC or Xmlrpc-c. These programs double as examples of how to use the Xmlrpc-c function libraries.
Because the utility programs are not essential to the package, the default install tools don't install them at all. The builder does build them, though, and if you build Xmlrpc-c from source, you will find them all in the tools/ directory.
You'll also find more complete documentation there.
xmlrpc is a general purpose XML-RPC client program. It performs one XML-RPC call, which you describe in its command line arguments.
Example:
$ xmlrpc sample.add i/3 i/5This makes a call to the XML-RPC server at the indicated URL, for the method named "sample.add", with two arguments: the integer 3 and the integer 5.
xmlrpc prints to Standard Output the result of the call, which it gets back from the server.
You can abbreviate the URL; xmlrpc assumes "http://" and "/RPC2":
$ xmlrpc localhost:8080 sample.add i/3 i/5 Result: Integer: 8
The port number defaults to 80, so you can abbreviate even more:
$ xmlrpc localhost sample.add i/3 i/5
String arguments look like this:
$ xmlrpc method_that_takes_string s/hello
If you don't include a type specifier such as "i/" or "s/", xmlrpc assumes "s/". So you can use this shortcut, equivalent to the above:
$ xmlrpc method_that_takes_string hello
Each argument to xmlrpc describes on XML-RPC parameter. So in a typical command shell, the following would make an XML-RPC call with two paramters: "hello" and "see you later":
$ xmlrpc mymethod s/hello "s/see you later"
Compound values for parameters look the following, except that these aren't implemented yet. Only "i/" and "s/" are implemented right now.
Note that this is an example of a Bourne shell command, so some of the characters (most notably the quotation marks) are part of the shell language, not the xmlrpc syntax.
$ xmlrpc \ meerkat.getItems \ "struct/{search:linux,descriptions:i/76,time_period:12hour}" Result: Array: Struct: title: String: DatabaseJournal: OpenEdge-Based Finance ... link: String:... description: String: "Finance application with embedded ... Struct: title: ... link: ... description: ...
$ xmlrpc localhost:8080 array_processing_method \ "array/(i/3,i/49,s/hello,array/(i/-10,i/-9))"
xmlrpc is implemented using the Xmlrpc-c client library, but its function is not in any way tied to Xmlrpc-c. It makes a standard XML-RPC call and does not know or care whether the server is implemented with Xmlrpc-c or not.
For extra diagnostic information, use the XMLRPC_TRACE_XML environment variable so you can see the XML that goes back and forth to perform the call. (This is not specifically xmlrpc function -- it's tracing function that's automatically there because xmlrpc uses libxmlrpc_client).
xmlrpc from Xmlrpc-c before Release 1.16 doesn't work on some platforms — it crashes due to invalid assumptions it makes about the way C variadic functions are implemented.
This section describes some alternatives to using XML-RPC For C/C++.
There are plenty of facilities to help you create XML-RPC clients and servers in a language other than C or C++. Search on Freshmeat.
It is worth mentioning that with some of these other-language facilities, the client or server is way slower than with XML-RPC for C/C++, due to the nature of the language. For example, I have used the Perl RPC::XML modules from CPAN and found a client program that takes 50 milliseconds to run when written with XML-RPC For C And C++ takes 2000 milliseconds to run when done with RPC::XML::Client.
In the case of Perl, there is a middle ground. The RPC::Xmlrpc_c modules from CPAN are based on Perl extensions that use the libraries of XML-RPC For C And C++. One reason RPC::XML is so slow is that it is built on top of a stack about 6 layers high, each one implemented in interpreted Perl. With RPC::Xmlrpc_c, all those layers except the top are implemented as executable machine code, efficiently compiled from C, so you have the same ease of Perl coding, without the slowness.
RPC::Xmlrpc_c is much younger than RPC::XML, so doesn't have many features, and in fact does not include any server facilities. But you could add missing features yourself (and, ideally, submit them for inclusion in the RPC::Xmlrpc_c package on CPAN, so others can use them).
RPC::Xmlrpc_c was new in December 2006 and needs XML-RPC For C And C++ Release 1.08 or better.
In other interpreted languages, the same hybrid may be possible -- replacing slow interpreted code with executable XML-RPC libraries.
You can make a nice XML-RPC server based on an Apache HTTP server (which may or may not simultaneously be a regular web server) using an Apache module.
There once was an Apache module based on Xmlrpc-c, so you could use the same method code as you do for other Xmlrpc-c-based implementations. It was called mod_xmlrpc and is described by a Freshmeat entry, but as of April 2009, the download link is dead.
Another module, also called mod_xmlrpc, is distributed via a Sourceforge project, but hasn't been updated since 2001, is undocumented, and looks pretty weak.
An even simpler, though less efficient and more limited way to make an XML-RPC server out of an Apache server is to do it via a CGI script. That script can be written in a variety of languages, but if you write it in C, you can use Xmlrpc-c's libxmlrpc_server_cgi library.
SOAP and CORBA are common alternatives to XML-RPC. Lots of expensive commercial software helps you use those. There is more to know and more you can do with them.
REST-RPC was invented in 2006 and was meant to be superior to XML-RPC for at least some things. It is easier to use in many ways than XML-RPC. Like XML-RPC, it uses HTTP, and like XML-RPC an RPC's result is XML. But unlike XML-RPC, a call is not XML. It is encoded entirely in the query part of a URL. (Example: http:/test.rest-rpc.org/?_function=GetCart&cart=1563). In the result, there are no inherent data types; server and client agree on those separately. The Xins project has more information.
Here, to show you what Xmlrpc-c is, we present example code (almost an entire C program) for a simple XML-RPC client that exploits the Xmlrpc-c libraries, and a corresponding simple XML-RPC server.
You can find complete working versions of these, and lots of other examples in the examples/ directory in the Xmlrpc-c source tree.
In these examples, the service to be provided is adding of two numbers. You wouldn't do this with RPC in real life, of course, because a program can add two numbers without the help of a remote server. This is just to demonstrate the concept..
#include <xmlrpc.h> #include <xmlrpc_client.h> #include "config.h" /* information about this build environment */ #define NAME "XML-RPC C Test Client" #define VERSION "1.0" int main(int const argc, const char ** const argv) { xmlrpc_env env; xmlrpc_value * resultP; int sum; char * const url = ""; char * const methodName = "sample.add"; /* Initialize our error-handling environment. */ xmlrpc_env_init(&env); /* Start up our XML-RPC client library. */ xmlrpc_client_init2(&env, XMLRPC_CLIENT_NO_FLAGS, NAME, VERSION, NULL, 0); die_if_fault_occurred(&env); /* Make the remote procedure call */ resultP = xmlrpc_client_call(&env, url, methodName, "); /* Shutdown our XML-RPC client library. */ xmlrpc_client_cleanup(); return 0; }
Now, here is code that implements an XML-RPC server that provides the number-adding service from the previous section.
#include <xmlrpc.h> #include <xmlrpc_server.h> #include <xmlrpc_server_abyss.h> static xmlrpc_value * sample_add(xmlrpc_env * const envP, xmlrpc_value * const paramArrayP, void * const serverContext) { xmlrpc_int32 x, y, z; /* Parse our argument array. */ xmlrpc_parse_value(envP, paramArrayP, "(ii)", &x, &y); if (envP->fault_occurred) return NULL; /* Add our two numbers. */ z = x + y; /* Return our result. */ return xmlrpc_build_value(envP, "i", z); } int main (int const argc, const char ** const argv) { xmlrpc_server_abyss_parms serverparm; xmlrpc_registry * registryP; xmlrpc_env env; if (argc-1 != 1) { fprintf(stderr, "You must specify 1 argument: The Abyss " "configuration file name. You specified %d.\n", argc-1); exit(1); } xmlrpc_env_init(&env); registryP = xmlrpc_registry_new(&env); xmlrpc_registry_add_method( &env, registryP, NULL, "sample.add", &sample_add, NULL); serverparm.config_file_name = argv[1]; serverparm.registryP = registryP; printf("Starting XML-RPC server...\n"); xmlrpc_server_abyss(&env, &serverparm, XMLRPC_APSIZE(registryP)); return 0; }
There's a lot going on under the covers of this example server. What the xmlrpc_server_abyss() statement does is run a whole HTTP server. The function doesn't normally return. The HTTP server runs the abyss web server (i.e. HTTP server) program. abyss is like the more serious web server program apache, but on a much smaller scale. An XML-RPC call is just an HTTP POST request, so while abyss was not designed specifically for XML-RPC, it provides much of the function an XML-RPC server needs.
The only way this Abyss web server differs from one you would run to do traditional web serving is that it contains a special handler to call Xmlrpc-c functions to handle an XML-RPC POST request. The server calls that handler for any URI that starts with "/RPC2", which is what XML-RPC URIs conventionally have.
While abyss is distributed independently of Xmlrpc-c, Xmlrpc-c contains an old copy of it, somewhat modified. So you don't need to install abyss separately.).
There are lots of other ways to use Xmlrpc-c libraries to build XML-RPC clients and servers. The more code you're willing to write, and the more involved in the guts of the protocol you want to get, the more control you can have.
/* A simple CGI-based XML-RPC server written in C. */ #include <xmlrpc.h> #include <xmlrpc_server_cgi.h> static xmlrpc_value * sample_add(xmlrpc_env * const env, xmlrpc_value * const param_array, void * const user_data) { xmlrpc_int32 x, y, z; /* Parse our argument array. */ xmlrpc_decompose_value(env, param_array, "(ii)", &x, &y); if (env->fault_occurred) return NULL; /* Add our two numbers. */ z = x + y; /* Return our result. */ return xmlrpc_int_new(env, z); } int main(int const argc, const char ** const argv) { /* Process our request. */ xmlrpc_cgi_init(XMLRPC_CGI_NO_FLAGS); xmlrpc_cgi_add_method_w_doc("sample.add", &sample_add, NULL, "i:ii", "Add two integers."); xmlrpc_cgi_process_call(); xmlrpc_cgi_cleanup(); return 0; }.
The example server above would be a suitable server for this client.
#include <string> #include <iostream> #include <xmlrpc-c/base.hpp> #include <xmlrpc-c/client_simple.hpp> using namespace std; int main(int argc, char **argv) { if (argc-1 > 0) { if (argv) {} cerr << "This program has no arguments" << endl; exit(1); } string const serverUrl(""); string const methodName("sample.add"); xmlrpc_c::clientSimple myClient; xmlrpc_c::value result; myClient.call(serverUrl, methodName, "ii", &result, 5, 7); int const sum((xmlrpc_c::value_int(result))); // Assume the method returned an integer; throws error if not cout << "Result of RPC (sum of 5 and 7): " << sum << endl; return 0; }
To keep it brief, we don't catch any thrown errors, though various parts of this program can throw them.
Here is C++ code that implements the same kind of XML-RPC server shown in C above.
#include <cassert> #include <xmlrpc-c/base.hpp> #include <xmlrpc-c/registry.hpp> #include <xmlrpc-c/server_abyss.hpp> using namespace std; class sampleAddMethod : public xmlrpc_c::method { public: sampleAddMethod() {} argc, const char ** const argv) { xmlrpc_c::registry myRegistry; xmlrpc_c::methodPtr const sampleAddMethodP(new sampleAddMethod); myRegistry.addMethod("sample.add", sampleAddMethodP); xmlrpc_c::serverAbyss myAbyssServer( myRegistry, 8080, // TCP port on which to listen "/tmp/xmlrpc_log" // Log file ); myAbyssServer.run(); // xmlrpc_c::serverAbyss.run() never returns assert(false); return 0; }
This document is part of the XML-RPC For C/C++ project. It is the main user documentation for the project.
The master copy of this document lives at. The HTML copy there is the original source -- it is hand edited.
This is a living document. It gets updated continuously, both to document changes in Xmlrpc-c and to improve the documentation. It documents all current and past, and, where possible, future releases of Xmlrpc-c. There is no benefit to keeping an old copy of the document to use with an old copy of the code.
Bryan Henderson wrote and published the first draft of this document in November 2004, as an entirely original work. Bryan placed it in the public domain.
Bryan enthusiastically maintains the document. If you have a problem with it, from typos to missing topics, please email Bryan at bryanh@giraffe-data.com. | http://xmlrpc-c.sourceforge.net/doc/ | crawl-002 | refinedweb | 2,941 | 55.54 |
Programming the F18
As we saw in the last post, the GA144 chip is an array of 144 tiny computers or "nodes". We tend not to call them "cores" because they are really more independent than that. Programming these interconnected nodes is something like working with agents or CSP. Each is an instance of the F18 architecture and can be thought of as a Forth inner interpreter in hardware. Pretty neat! Probably you're used to stack machines in the form of VMs (e.g. the JVM and CLR). It's indeed a very simple and beautiful model. The GreenArrays chip brings this beauty to life in silicon!
In this post we'll learn the basics of the F18 architecture and the instruction set. We'll write a few simple programs in raw machine code just to get a feel for it. In later posts we'll move on to using colorForth to program it.
Architecture
You can see pretty much all of the guts of the computer; a handful of registers, a couple of stacks and some memory. To the left is the portion of RAM from which we're executing. The right two columns show all the registers and the two stacks. It is a truly simple machine. I'm going to give just an overview here. If you want to learn the nitty gritty details I would suggest reading the well written GreenArrays docs and maybe taking the free 'F18A Architecture and Instruction Set' portion of the arrayForth Institute course.
Instruction Fetch. Very interesting processor this is!
General/Address Registers
The A register is a general purpose register. It may be used to store data or addresses. Those addresses may be into RAM or to/from a port. The B register is write-only and is used only for addressing.
Having separate address registers may be a very strange thing to someone familiar with Forth. Normally, addresses go on the stack and the fetch (@) and store (!) operations use them from there. On the F18, fetch and store are always through P, A or B. Don't forget that this machine is not just a VM with nice pretty abstractions. The F18 is implemented in silicon, and physical address lines through the top of the stack along with ALU being driven by the same registers is difficult and/or inefficient (apparently - I'm not a chip designer). Just don't be confused by this. This is an example, I think, of Chuck Moore's philosophy of not making the simplest possible software or the simplest possible hardware, but instead the simplest combination of the two. This is a trade-off made to favor hardware simplicity; breaking software composition a bit.
Stacks
You must read Chuck Moore's short essay on push down stacks. Each F18 node has a pair of stacks. This dual-stack approach is clearly the Forth architecture realized in hardware; a wonderful thing. Each stack is eight elements indexed circularly. Nothing moves when pushing and popping these stacks. A 3-bit pointer is incremented/decremented. The circularity comes from simple overflow of this 3-bit pointer. Being circular leads to some interesting techniques such as cycling endlessly through values and fearlessly leaving things on the stack to be stomped on later, saving cycles "cleaning up." Above each stack are registers (R, T and S) optimizing access to the top elements used directly by instructions.
One is a return stack; storing addresses for returning from nested calls. Having such a lightweight calling convention is what allows for extremely aggressive factoring in Forth. Some say that C is a high level assembly language, but you cannot escape the complected calling convention there. In Forth a call costs only a push/pop of a return address and having lots of small routines is encouraged without worrying about inlining. The return stack may also be used to contain local values and hosts the induction value for (potentially nested) counted loop. The R register is the top of the return stack; "spilling" values to/from the eight stack elements below; effectively making this a nine-element stack. One regular register backed by eight circularly indexed ones.
The other stack is the data stack for evaluation and argument passing. Having zero-operand instructions that assume their operands are waiting near the top of the stack is what allows for very tightly packed instructions (four per cell). Also, passing arguments through the stack at call sites rather than in registers leads to simple composition of routines. That is, a sequence of calls each taking arguments and leaving return values on the stack with no explicit parameter passing between them. I've waxed rhapsodic in the past about how much I like point-free programming. This is one of the reasons I love Forth and the stack is what enables it efficiently. To give binary ALU operations easy access, the top two values are in the "top" (T) and "second" (S) registers. Like with R, these "spill" to/from the eight elements below, making a ten-element data stack.
Instruction Set
These are the 32 instructions of this simple machine. I will briefly describe them here and will get into more detail on some (e.g. the multiply-step instruction) in future posts.
In the simulator there are a couple of extra (unofficial) instructions for debugging and performance measurement:
The ALU operations mostly do just what you'd expect; taking one or two arguments from the stack and replacing with the result. Multiply-step is a complicated one which I'll describe in a future post. It essentially is one step in a multiply/shift operation; needing to be executed in a micronext loop to multiply values. Very primitive. You may want to generally think of the instruction set as microcode. I should point out that or is an exclusive-or and that - is a "not" operation rather than a full twos-compliment negation. We'll get into how to make good use of these instructions as we go. There are a lot of techniques to cover and it's pretty fun! The instruction set does take some getting used to.
There are the usual stack manipulation instructions drop, dup and over. Glaringly missing is swap. This is another place where complexity of the hardware drove the decision. We'll see how to accomplish swapping with the primitives provided and how over is often all you need.
The data and return stacks are "connected" in a sense. The push and pop instructions shuffle values between the tops of each. Be careful not to confuse pop (top of return) with drop (top of data). I get confused because IL has a pop instruction that that really is a drop.
There are instruction for fetching and storing through P (@p and !p), through A (@, @+, ! and !+) and through B (@b and !b). Fetching through P (@p) is commonly used to fetch literal values inline from the instruction stream to the top of the stack. It is so common to index through A that the instruction mneumonics are simply @ and ! (without 'a'). Fetching and storing through P auto-increments (except when pointing at a port), but A may be used with or without auto-incrementation (notice the variants with/without '+'). Values may be stored into A (a!) or B (b!). Values may be retrieved from A (a) but remember that B is write-only.
Counted loops may be formed with next and unext. Each use R as the induction variable; counting down to zero. The difference between the two loop instructions is that next expects an arbitrary address operand, while unext is a loop within I; back to the first slot. This is one of the very interesting instructions; allowing looping within a single fetched instruction cell. Of course these loops are tiny (three instructions max) but the utility is amazing!
Conditional control transfer is done with if and -if. These branch depending on the value on top of the stack. Unlike traditional Forth "if" however, they leave the predicate value on the stack. This is convenient much of the time. Occasionally, you need to add a drop to discard.
Unconditional control transfer may be done with (call), (jump) and ex. In particular, ex is useful for jumping to computed addresses and for doing co-routines. We'll explore this powerful feature in a future post. The ; (return) instruction transfers out of a called or executed routine; popping an address from the return stack.
Structure and TCO
It is extremely common to break programs into many, many small routines. Aggressive factoring is a hallmark of Forth. The (call) and (jump) instructions are used to execute these routines. In fact, a high level routine may commonly be nothing but a sequence of calls followed by a return (;) - subroutine threading. Actually, the last call may be optimized to a (jump) allowing the callee to return directly to the original caller - tail call optimization is that simple!
Encoding
Since these instructions expect their operands on the stack, for the most part, they pack very tightly - four to an instruction cell. This tight packing would not be possible on a register machine! Several of the instructions do have address operands. They are (jump), (call), next, if and -if. Each of these use the remaining slots of the instruction cell as an address. The address simply replaces the lower bits in P so that they form "pages" of memory within which you can transfer. That is, a slot 3 (jump) may not reach everywhere in RAM. Don't worry though. We'll get away from dealing with low-level issues like these once we start working in colorForth in future posts.
Example Program 1
This happens to be. Pretty cool stuff!.
Example Program 2.
Example Program 3 'a').).
Next, we'll explore some of the techniques for making great use of this super-minimal instruction set and will get into authoring programs in colorForth. It would be tedious to continue hand writing them in machine code. It is nice to work with mnemonics and with an instruction set that feels very Forth-like without a lot of monkeying with registers. Still, some aspects could be more "automated" (assembly-time macros) and we should really never have to think about the target addresses for jumps, calls, next loops, etc. Forth may predate Dijkstra's famous rant, but it has always been a structured language in which you should never directly see a "goto" (jump, call, ...).
Things will become much nicer when we move to authoring in colorForth.
Nice. But the data width is 18 bits (F18) so you won't be running 'over ffffffff iterations'
Yes, of course the actual F18 is 18 bits wide. The sim I'm using here however is 32-bit (github.com/…/Color)
Nice to see someone paying close attention:)
32 bits could contain a much bigger array of opcodes allowing for larger uNext loops.
The array of computer nodes offer a different way of thinking about and factoring problem. The factoring exists at many levels. For instance, imagine packets traveling through a system executing the header on each node to effect routing and on the destination node the payload is run. Programs need not sit in local memory. They can be passed in and executed on the fly and never exist in actual memory. Each node can pass packet programs through to other nodes or run them. I've been considering how one might set up a system to do this. An initial seed packet could start off on a single node and be propagated to the neighbours leaving a breadcrumb trail behind it. Each node would end up with a unique identifier and routing info. This identifier would be used for routing. If the identifier matched on a node, then the payload of the packet would get executed on that node. Otherwise the identifier would be used to route the packet up or to the left eventually getting to the target node to be executed. Return packets would travel right or down. I"m not sure what the primitives would be yet but this architecture lends itself to some interesting creative thinking.
True. There could be unext loops with twice the instructions! 6+ slots per 32-bit word.
I guess the purpose of the sim here is to learn the GA144 hardware without some of the restrictions and weirdness. But still, in some ways, stay faithful to the real hardware. I have no other good explanation for wasting bits with 5-bit instructions packed in 8-bit slots. Well, I guess there is the possibility of extending the instruction set (e.g. the 'break' and 'mark' instructions already added).
RE: Multi-node message passing and such. Yes! One of the beautiful things is executing instructions streaming in without residing in memory at all. I've only used as a 'loader' so far and I've only demo'd programming a single node. It's easy enough to wire together sim instances and I'll be doing that later!
Your idea of a "routing protocol" of sorts is excellent. You might check out etherForth for inspiration along those lines 🙂
etherforth is for kernel and distributing Chuck's computer system and is a move in the right direction – certain elements could be hijacked.
I'm thinking along the lines of embedded systems with I/O, algorithms with intermediate results (FFT), and other bit processing machines. In a conventional single computer memory is all inaccessible because there is only one address and data port. Everything must go through that port. If we use one for data and one for instructions then we double our bandwidth. Then if we cache items in registers we again increase our bandwidth. But the program still just sits in memory. One could put large amounts of ram on each node and run big programs there but then it would not be a Chuck chip. The key to using the GA144 chip is to have travelling programs. The ports have potential to replace two off chip memories with 4 off chip memories. A port looks to the F18 like a connection to a conventional memory. And it can be treated in a similar way. And there are 4 of them for most nodes. One port could be feeding instructions while a second port could be pushing a data stream. If you look at a computer in an abstract way, this is what they are doing. In the GA chip, instead of connecting a computer to memory, it is a computer connected to 4 other computers. Our thinking to this point has been restricted to cpu+ram. We need to think outside of this and this chip gives us the fabric for building new computing structures. Once this takes hold then we will factor out new computing elements and build solutions in new ways. Not unlike transputers but without the historical baggage.
Awesome explanation! Thanks for posting this. I was a little reluctant to try and learn how the green arrays stuff works because it's so different from everything else. But you have made it much more understandable.
Ashley,
In the Example Program 2, according to the opcodes and descriptionm, shouldn't it read
@p ! unext .
instead of
@p ! . . ?
Thanks for the nice post!
About my last comment: from the description, "@p ! . ." seems correct, but the opcodes seem wrong (04 instead of 1c for the first nop).
Wow @iru, sharp eye! Just fixed it. Thanks!
Trying to run your code on a Mac with Xamarin Studios.
It is giving me this error in application output when set to release:
User Assembly '/Users/path/Color/Editor/bin/Release/Editor.exe' is missing
Hi!
There is a flaw in RAM line 0003 in program 3
@p + dup !b
!b can not be last.
Hey Tony, nice eye! On the *actual* F18 indeed you can't have this instruction in the last slot. In this simulator, however, we're allowing every instruction in every slot. This is just to learn the instruction set without some of the "weirdness" of the actual chip.
I'm using the actual chip and trying to understand the compiler encoding. For instance, address 00 contains x01dfa for ( @b @p and . ). But the Op codes are 0a 08 15 1c. What encoding algorithm is being used? | https://blogs.msdn.microsoft.com/ashleyf/2013/10/13/programming-the-f18/ | CC-MAIN-2019-43 | refinedweb | 2,732 | 66.03 |
That something we'll be logging into is a database.
The idea is to take the supplied information (username & password) and verify that the given password matches the given username in the database.
Objectives:
Finish the login dialog so when the user attempts to login, the information is verified against information taken from the database. If the information matches then the user has successfully logged in. Otherwise, the user has either supplied a wrong username and/or password.
Prerequisites:
Again, a fair amount of knowledge is expected to begin this tutorial. Some new concepts you'll see are:
- Java Database Connections (JDBC)
- MySQL
- MySQL Connector/J
- Statements
- ResultSets
- SHA-1 Hashing Function
- XAMPP
- PhpMyAdmin
Setting up the Database:
I created and set the database name to logins.
In the logins database I've create 1 table named users.
The users table has 3 columns:
- UserID (Primary Key) (Auto-increment) (Integer)
- Username (Text) (Length = 20)
- Password (Binary) (Length = 20)
I have entered a username and hashed password to the database.
Username: username
Password: password
Hashed Password: 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
Screenshot of database:
This is the data we'll be using to compare with the end-user's login data.
Setting up the Mysql Connector/J Driver
This driver enables the client to be able to speak with the MySQL database
First download the driver from the following website:
MySQL :: Download Connector/J
Once downloaded, unzip the file until you gain access to the file named:
mysql-connector-java-5.1.18-bin.jar
I created a folder named libraries and place this file inside of it.
You'll need to be sure to include this library in your classpath.
In eclipse, you can Right Click the Project and go to BuildPath then Configure BuildPath
Under the Libraries tab, click the button titled Add External JARs...
Next navigate to the location where you saved mysql-connector-java-5.1.18-bin.jar and choose open.
Here's a screenshot of what the buildpath looks like after including the driver:
Step 1 - Decide Which Classes Are Relevant For Your Objective
- java.sql.Connection - Used to create the connection between the client and the database
- java.sql.Statement - Used to get results from queries
- java.sql.ResultSet - Stores the data retrieved from a query in table fashion
- java.security.MessageDigest - Used to hash the supplied password using the SHA-1 algorithm
The idea is straight forward.
When the loginButton is clicked, the usernameField's text is stored into a String called username.
The password is retrieved from the passwordField and stored into a byte[] array using the UTF-8 charset.
A boolean named success is used to determine if the login attempt was successful or not.
On success, a message is shown telling the end-user that the login was successful and the dialog closes.
Otherwise, an unsuccessful message is shown and the dialog remains open.
buttons[0].addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { String username = usernameField.getText().trim(); byte[] password = null; try { password = new String(passwordField.getPassword()).trim().getBytes("UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } success = [COLOR=#ff0000]submit(username, password);[/COLOR] if(success) { JOptionPane.showMessageDialog(null, "Successful login"); close(); } else { JOptionPane.showMessageDialog(null, "Incorrect username or password"); } } });
Step 3 - Creating the submit(String username, byte[] password) Method
In this method, the username and password lengths are checked and if they are less than 1, the method returns false.
In any other case, the method passes these parameters to the hashAndVerify(...) method which hashes the password and verifies it against the correct database information.
protected boolean submit(String username, byte[] password) { if(username.length() < 1 || password.length < 1) return false; return hashAndVerify(username, password); }
Step 4 - Creating the hashAndVerify(String username, byte[] password) Method
The idea is to obtain a hash value for the given password using the SHA-1 algorithm and compare it to the hashed password gathered from the database.
If the data matches, then the login attempt is successful.
The first line in this method looks like:
byte[] hashedPassword = hash(password);
The hashed password is now stored in the previous byte[] array. (The hash(...) method will be shown later)
The entire body looks like so:
private boolean hashAndVerify(String username, byte[] password) { byte[] hashedPassword = hash(password); String query = "SELECT Password FROM users WHERE Username = ?"; PreparedStatement stmt = DatabaseConnection.getStatement(query); ResultSet rs = null; try { stmt.setString(1, username); rs = stmt.executeQuery(); while (rs.next()) { byte[] arr = rs.getBytes("Password"); if (java.util.Arrays.equals(hashedPassword, arr)) { return true; } } } catch (SQLException e1) { e1.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); DatabaseConnection.closeConnection(); } catch (SQLException e) { e.printStackTrace(); } } return false; }
Using the DatabaseConnection's (defined later) static method getStatement(), we're able to get a ResultSet from the following query:
String query = "SELECT Password FROM users WHERE Username='" + username + "'";The password from the database is temporarily stored into a byte[] array named arr.
If the hashed password and the password retrieved from the database match then method returns true.
If not, then the method returns false.
Step 5 - Constructing the hash(byte[] password) Method
First, the MessageDigest sha1 object is initialized with the SHA-1 algorithm.
The sha1 object then obtains a hashed value for the password. The returned value is the hashed password in a byte[] array.
private byte[] hash(byte[] password) { MessageDigest sha1 = null; try { sha1 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } if (sha1 == null) return null; sha1.update(password); return sha1.digest(); }
Here is the DatabaseConnection.java class used to maintain the Connection to the database:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class DatabaseConnection { private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/logins"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; private static Connection conn; private DatabaseConnection() { } public static PreparedStatement getStatement(String query) { PreparedStatement stmt = null; try { stmt = getConnection().prepareStatement(query); } catch (SQLException e) { e.printStackTrace(); } return stmt; } private static Connection getConnection() { try { if(conn == null || conn.isClosed() ) conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD); } catch (SQLException e) { e.printStackTrace(); } return conn; } public static void closeConnection() { if(conn == null ) return; try { if( conn.isClosed() ) return; conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
>>Link To Source Code for Parts 1 & 2<<
Edited by lethalwire, 01 January 2012 - 11:26 AM.
Modified Statements into PreparedStatements | http://forum.codecall.net/topic/67583-java-login-dialog-part-2/ | CC-MAIN-2018-30 | refinedweb | 1,057 | 50.43 |
Introduction
In this post, I will write about Redux Middleware by viewing it in 2 different angles, one from the Object Oriented way and the other from the functional way as how it is implemented in Redux source code.
Basics of Redux
The core function of Redux is:
dispatch(action)
When the client calls
dispatch(action), it internally calls the
reducer function which is a pure function (a function which does not have any side effects) whose signature is
(currentstate, action) => nextstate. The client can call
getState to get the current state value any time.
Middleware
As stated earlier,
dispatch(action) is the core function of Redux which does the next state calculation using the reducer function. What if an application wants to log the
getState() function before and after the call to
dispatch(action) (or) would like to know how long it took for
dispatch(action) to finish completion (or) would like to make an IO operation before calling the actual
dispatch(action)? How do we solve this problem? I was reminded of a famous quote,
“History doesn’t repeat itself but it often rhymes”
I have seen this similar problem in a couple of instances from the Object Oriented world.
- Java Filters: A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.
- Java IO: InputStream is an abstract class. Most concrete implementations like BufferedInputStream, GzipInputStream, ObjectInputStream, etc. have a constructor that takes an instance of the same abstract class. That’s the recognition key of the decorator pattern (this also applies to constructors taking an instance of the same interface).
Both the above examples are typically solved by a popular Gang of Four Design Pattern: Decorator Design Pattern. The basic idea of Decorator Design pattern is to augment (or) decorate the behavior of the underlying base component without the need to change/extend the base component.
So the original problem of how to augment/decorate
dispatch(action) perfectly fits the bill of GoF Decorator Design Pattern. GoF Decorator design pattern provides the solution in Object Oriented way, but the general abstract motivation of using Decorator Design pattern perfectly maps to how we will solve the problem of implementing
Middlewares in Redux whether in Object Oriented Way (or) Functional way.
Square Calculator
To understand middleware, we will try to view it through the lens of a very simple example:Square calculator. If the input is x the output is x*x, which basically forms the pure reducer function. Redux stores the last computed square value as its state. Additionally we would like to do 3 middleware operations:
- Validate the input to make sure it is a number by calling a service (extremely hypothetical example), but in essence would like to sprinkle some impurity through an IO operation.
- Calculate the time taken to perform the original
dispatch(action)
- Log the
getState()before and after the original
dispatch(action)
[If you look closely, not only 1 is impure because of an IO operation, even 2 and 3 are also impure since accessing the system clock to get the time and writing to the console are also impure operations.]
Implementation of Square Calculator – Object Oriented Way
As stated earlier, it is implemented using Decorator design pattern:Source Code in Java Using OO way
The UML diagram for the crux of the implementation can be shown as below:
Store globalStore; globalStore = new Thunk(new TimerStore(new LoggingStore(baseStore)));
As shown above, we are adhering to an important principle, “Code to an interface rather than an implementation” and the client ties to the interface called
Store and the implementation is a fully constructed chain of decorators wrapping the base Store and the client is not aware of any of the implementation details.
Implementation of Square Calculator – Functional Way
If we look at Redux source code, the implementation of middleware uses a lot of functional constructs. I have created a slimmed down version of it to implement the logic for Square Calculator. Source Code in Javascript Using Functional way
I would like to touch upon some of the important functional programming constructs that are being employed to construct the wiring for middleware.
If you look at the above source code you will see the following important properties being employed:
- In Functional Programming, functions are first class citizens. Meaning, functions can be stored in variables and can be passed around like numbers, strings etc.
- Use of Higher Order Functions – Functions can take functions as parameters and return functions as return values. A function that does either of those is called a higher order function. It turns out that if you want to define computations by defining what stuff is instead of defining steps that change some state and maybe looping them, higher order functions are indispensable. They’re a really powerful way of solving problems and thinking about programs.
- Currying – Basically if you take a simple function like adding 2 numbers, its signature for being a curried function would be
var add = a => b => a + b. The caller of this function would have to do, add(1) (2) to get 3. A good analogy would be, “If I can give you a carrot for an apple and a banana, and you already gave me an apple, you just have to give me a banana and I’ll give you a carrot.” Translating to the add example, if we had called the function
addwith just
1and stored the result like
var addOne = add(1). Now if the client wants to add any number to one, they can simply just do
addOne(2), so If I can give you a
3for
1and
2and you already gave me
1you just have to give me
2and I will give you
3
- Use of
mapfunction in the
List– Usage of Functor
- Use of
foldsthrough
reducefunction – extremely powerful abstract API.
- Use of functional composition –.
All the above 6 properties are used in just 30 lines of code 🙂
function compose(...funcs) { funcs = funcs.filter(func => typeof func === 'function') if (funcs.length === 0) { return arg => arg } if (funcs.length === 1) { return funcs[0] } return funcs.reduce((a, b) => (...args) => a(b(...args))) } function applyMiddleware(...middlewares) { return (createStore) => (reducer, preloadedState, enhancer) => { var store = createStore(reducer, preloadedState, enhancer) var dispatch = store.dispatch var chain = [] var middlewareAPI = { getState: store.getState, dispatch: (action) => dispatch(action) } chain = middlewares.map(middleware => middleware(middlewareAPI)) dispatch = compose(...chain)(store.dispatch) return { ...store, dispatch } } }
Conclusion
As you can see, Redux Middleware is a very simple but powerful concept where the core idea of decorating the base behavior of
dispatch(action)function with wrappers is seen in many other instances in the Object Oriented world as well.
Great explanation of the core ideas and pattern behind redux middleware. Thanks 🙂
LikeLiked by 1 person
Thanks Vasa.
Simple Explanation of a complex logic.
great read!
Very nicely written Maya. Lots of concepts packaged into one article. | https://vmayakumar.wordpress.com/2016/12/27/redux-middleware/ | CC-MAIN-2018-17 | refinedweb | 1,160 | 50.16 |
Back to index
#include <nsGraphicState.h>
Definition at line 96 of file nsGraphicState.h.
Definition at line 50 of file nsGraphicState.cpp.
Definition at line 57 of file nsGraphicState.cpp.
{ nsGraphicState* gs = mFreeList; while (gs != nsnull) { nsGraphicState* next = gs->mNext; delete gs; gs = next; } }
Definition at line 69 of file nsGraphicState.cpp.
{ nsGraphicState* gs = mFreeList; if (gs != nsnull) { mFreeList = gs->mNext; return gs; } return new nsGraphicState; }
Definition at line 81 of file nsGraphicState.cpp.
{ // clear the graphics state? this will cause its transformation matrix and regions // to be released. I'm dubious about that. in fact, shouldn't the matrix always be // a member object of the graphics state? why have a separate allocation at all? aGS->Clear(); aGS->mNext = mFreeList; mFreeList = aGS; }
Definition at line 107 of file nsGraphicState.h. | https://sourcecodebrowser.com/lightning-sunbird/0.9plus-pnobinonly/classns_graphic_state_pool.html | CC-MAIN-2016-44 | refinedweb | 131 | 54.49 |
Floating point literals are of type double by defaultsuggest change
Care must be taken when initializing variables of type
float to literal values or comparing them with literal values, because regular floating point literals like
0.1 are of type
double. This may lead to surprises:
#include <stdio.h> int main() { float n; n = 0.1; if (n > 0.1) printf("Wierd\n"); return 0; } // Prints "Wierd" when n is float
Here,
n gets initialized and rounded to single precision, resulting in value 0.10000000149011612. Then,
n is converted back to double precision to be compared with
0.1 literal (which equals to 0.10000000000000001), resulting in a mismatch.
Besides rounding errors, mixing
float variables with
double literals will result in poor performance on platforms which don’t have hardware support for double precision.
Found a mistake? Have a question or improvement idea? Let me know.
Table Of Contents | https://essential-c.programming-books.io/floating-point-literals-are-of-type-double-by-default-83242ddadca44df18a2a68a9494796d3 | CC-MAIN-2021-25 | refinedweb | 149 | 69.89 |
Available items
The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:
sgqlc- Simple GraphQL Client ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. image:: :target:
.. image:: :target:
This package offers an easy to use
GraphQL_ client. It's composed of the following modules:
:mod:
sgqlc.types: declare GraphQL in Python, base to generate and interpret queries. Submodule :mod:
sgqlc.types.datetimewill provide bindings for :mod:
datetimeand ISO 8601, while :mod:
sgqlc.types.relaywill expose
Node,
PageInfoand
Connection.
:mod:
sgqlc.operation: use declared types to generate and interpret queries.
:mod:
sgqlc.endpoint: provide access to GraphQL endpoints, notably :mod:
sgqlc.endpoint.httpprovides :class:
HTTPEndpointusing :mod:
urllib.request.urlopen().
Straight from:
A query language for your API was created by Facebook based on their problems and solutions using
REST_ to develop applications to consume their APIs. It was publicly announced at
React.js Conf 2015_ and started to gain traction since then. Right now there are big names transitioning from REST to GraphQL:
Yelp_
Shopify_ and
GitHub, that did an excellent
postto explain why they changed.
A short list of advantages over REST:
Built-in schema, with documentation, strong typing and introspection. There is no need to use
Swagger_ or any other external tools to play with it. Actually GraphQL provides a standard in-browser IDE for exploring GraphQL endpoints:;
Only the fields that you want. The queries must explicitly select which fields are required, and that's all you're getting. If more fields are added to the type, they won't break the API, since the new fields won't be returned to old clients, as they didn't ask for such fields. This makes much easier to keep APIs stable and avoids versioning. Standard REST usually delivers all available fields in the results, and when new fields are to be included, a new API version is added (reflected in the URL path, or in an HTTP header);
All data in one request. Instead of navigating hypermedia-driven RESTful services, like discovering new
"_links": {"href"...and executing a new HTTP request, with GraphQL you specify nested queries and let the whole navigation be done by the server. This reduces latency a lot;
The resulting JSON object matches the given query exactly; if you requested
{ parent { child { info } } }, you're going to receive the JSON object
{"parent": {"child": {"info": value }}}.
From GitHub's
Migrating from REST to GraphQL_ one can see these in real life::
$ curl -v [ { "login": "...", "id": 1234, "avatarurl": "...", "gravatarid": "", "url": "...", "htmlurl": "...", "followersurl": "", "followingurl": "{/otheruser}", "gistsurl": "{/gistid}", "starredurl": "{/owner}{/repo}", "subscriptionsurl": "", "organizationsurl": "", "reposurl": "", "eventsurl": "{/privacy}", "receivedeventsurl": "", "type": "User", "site_admin": true }, ... ]
brings the whole set of member information, however you just want name and avatar URL::
query { organization(login:"github") { # select the organization members(first: 100) { # then select the organization's members edges { # edges + node: convention for paginated queries node { name avatarUrl } } } } }
Likewise, instead of 4 HTTP requests::
curl -v curl -v curl -v curl -v
A single GraphQL query brings all the needed information, and just the needed information::
query { repository(owner: "profusion", name: "sgqlc") { pullRequest(number: 9) { commits(first: 10) { # commits of profusion/sgqlc PR #9 edges { node { commit { oid, message } } } } comments(first: 10) { # comments of profusion/sgqlc PR #9 edges { node { body author { login } } } } reviews(first: 10) { # reviews of profusion/sgqlc/ PR #9 edges { node { state } } } } } }
sgqlc
As seen above, writing GraphQL queries is very easy, and it is equally easy to interpret the results. So what was the rationale to create sgqlc?
GraphQL has its domain-specific language (DSL), and mixing two languages is always painful, as seen with SQL + Python, HTML + Python... Being able to write just Python in Python is much better. Not to say that GraphQL naming convention is closer to Java/JavaScript, using
aNameFormatinstead of Python's
a_name_format.
Navigating dict-of-stuff is a bit painful:
d["repository"]["pullRequest"]["commits"]["edges"]["node"], since these are valid Python identifiers, we better write:
repository.pull_request.commits.edges.node.
Handling new
scalartypes. GraphQL allows one to define new scalar types, such as
Date,
Timeand
DateTime. Often these are serialized as ISO 8601 strings and the user must parse them in their application. We offer
sgqlc.types.datetimeto automatically generate :class:
datetime.date, :class:
datetime.timeand :class:
datetime.datetime.
Make it easy to write dynamic queries, including nested. As seen, GraphQL can be used to fetch lots of information in one go; however if what you need (arguments and fields) changes based on some variable, such as user input or cached data, then you need to concatenate strings to compose the final query. This can be error prone and servers may block you due to invalid queries. Some tools "solve" this by parsing the query locally before sending it to server. However usually the indentation is screwed and reviewing it is painful. We change that approach: use :class:
sgqlc.operation.Operationand it will always generate valid queries, which can be printed out and properly indented. Bonus point is that it can be used to later interpret the JSON results into native Python objects.
Usability improvements whenever needed. For instance
Relay_ published their
Cursor Connections Specification_ and its widely used. To load more data, you need to extend the previous data with newly fetched information, updating not only the nodes and edges, but also page information. This is done automatically by :class:
sgqlc.types.relay.Connection.
Future plans include generating the Python classes from the GraphQL schema, which can be automatically fetched from an endpoint using the introspection query.
Automatic::
pip install sgqlc
From source using
pip::
pip install .
To reach a GraphQL endpoint using synchronous
HTTPEndpointwith a hand-written query (see more at
examples/basic/01_http_endpoint.py):
.. code-block:: python
from sgqlc.endpoint.http import HTTPEndpoint
url = '' headers = {'Authorization': 'bearer TOKEN'}
query = 'query { ... }' variables = {'varName': 'value'}
endpoint = HTTPEndpoint(url, headers) data = endpoint(query, variables)
However, writing GraphQL queries and later interpreting the results may be cumbersome. That's solved by our
sgqlc.types, which is usually paired with
sgqlc.operationto generate queries and then interpret results (see more at
examples/basic/02_schema_types.py). The example below matches a subset of
GitHub API v4_. In GraphQL syntax it would be::
query { repository(owner: "profusion", name: "sgqlc") { issues(first: 100) { nodes { number title } pageInfo { hasNextPage endCursor } } } }
The output JSON object is:
.. code-block:: json
{ "data": { "repository": { "issues": { "nodes": [ {"number": 1, "title": "..."}, {"number": 2, "title": "..."} ] }, "pageInfo": { "hasNextPage": false, "endCursor": "..." } } } }
.. code-block:: python
from sgqlc.endpoint.http import HTTPEndpoint from sgqlc.types import Type, Field, listof from sgqlc.types.relay import Connection, connectionargs from sgqlc.operation import Operation
# Declare types matching GitHub GraphQL schema: class Issue(Type): number = int title = str
class IssueConnection(Connection): # Connection provides pageinfo! nodes = listof(Issue)
class Repository(Type): issues = Field(IssueConnection, args=connection_args())
class Query(Type): # GraphQL's root repository = Field(Repository, args={'owner': str, 'name': str})
# Generate an operation on Query, selecting fields: op = Operation(Query) #)
Since we don't want to clobber GraphQL fields, we cannot provide nicely named methods. Therefore we use overloaded methods such as
__iadd__,
__add__,
__bytes__(compressed GraphQL representation) and
__str__(indented GraphQL representation).
To select fields by name, use
__fields__(*names, **names_and_args). This helps with repetitive situations and can be used to "include all fields", or "include all except...":
.. code-block:: python
# just 'a' and 'b' typeselection.fields('a', 'b') typeselection.fields(a=True, b=True) # equivalent
# a(arg1: value1), b(arg2: value2): typeselection.fields_( a={'arg1': value1}, b={'arg2': value2})
# selects all possible fields typeselection.fields_()
# all but 'a' and 'b' typeselection.fields(exclude=('a', 'b')) typeselection.fields(a=False, b=False)
Manually converting an existing GraphQL schema to
sgqlc.typessubclasses is boring and error prone. To aid such task we offer a code generator that outputs a Python module straight from JSON of an introspection call:
.. code-block:: console
[email protected]$ python3 -m sgqlc.introspection \ --exclude-deprecated \ --exclude-description \ -H "Authorization: bearer ${GHTOKEN}" \ \ githubschema.json [email protected]$ sgqlc-codegen githubschema.json githubschema.py
This generates
github_schemathat provides the :class:
sgqlc.types.Schemainstance of the same name
github_schema. Then it's a matter of using that in your Python code, as in the example below from
examples/github/github-agile-dashboard.py:
.. code-block:: python
from sgqlc.operation import Operation from githubschema import githubschema as schema
op = Operation(schema.Query) # note 'schema.'
# -- code below follows as the original usage example:
#)
Gustavo Sverzut Barbieri_
sgqlcis licensed under the
ISC_.
You need to use
pipenv_.
::
pipenv install --dev pipenv shell
Install the git hooks:
::
./utils/git/install-git-hooks.sh
Run the tests (one of the below):
::
./utils/git/pre-commit # flake8 and nose
./setup.py nosetests # only nose (unit/doc tests) flake8 --config setup.cfg . # style checks
Keep 100% coverage. You can look at the coverage report at
cover/index.html. To do that, prefer
doctest_ so it serves as both documentation and test. However we use
nose_ to write explicit tests that would be hard to express using
doctest.
Build and review the generated Sphinx documentation, and validate if your changes look right:
::
./setup.py build_sphinx open doc/build/html/index.html
To integrate changes from another branch, please rebase instead of creating merge commits (
read more_).
The following repositories provides public schemas generated using
sgqlc-codegen:
Mogost/sgqlc-schemas_ GitHub, Monday.com | https://xscode.com/profusion/sgqlc | CC-MAIN-2020-45 | refinedweb | 1,546 | 50.33 |
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode.
Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript).
class Solution {
public:
bool isPerfectSquare(int num) {
if(num <= 0)return false;
int sq = sqrt(num);
return (sq*sq == num);
}
};
Obviously, with sqrt, the question looks trivial.
You should not use it.
sqrt
"Note: Do not use any built-in library function such as sqrt."
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/49374/simple-c-using-math | CC-MAIN-2017-39 | refinedweb | 104 | 74.59 |
22 March 2012 18:47 [Source: ICIS news]
(updates with Canadian and Mexican chemical railcar traffic data)
?xml:namespace>
Canadian chemical railcar loadings for the week totalled 10,900, down from 12,688 in the same week in 2011, the Association of American Railroads (AAR) said.
The previous week, ended 10 March, saw a year-on-year decline of 12.9%.
The weekly chemical railcar loadings data are seen as important real-time measures of chemical industry activity and demand.
From 1 January to 17 March, Canadian chemical railcar loadings were down by 12.4% year on year to 111,725.
The AAR said weekly chemical railcar traffic in
Meanwhile, overall US weekly railcar loadings for the 19 high-volume freight commodity groups tracked by the AAR fell by 5.3% year on year to 278,420 | http://www.icis.com/Articles/2012/03/22/9544196/canada-chem-railcar-traffic-falls-for-11th-week-in-a.html | CC-MAIN-2014-15 | refinedweb | 137 | 55.74 |
Running your own email server can be quite rewarding. You are in charge of your data. It also allows you more flexibility with your delivery options. However, there are a few challenges. You run the risk of opening your server up to vulnerabilities, as well as making your server a potential relay for spammers to use.
With that out of the way, let's get on to running our own mail server.
There are three required pieces of software to install that aren't included in the FreeBSD base system:
OpenSMTPd is a mail transfer agent (MTA) and mail delivery agent (MDA). This means that it can communicate with other mail servers over the
SMTP protocol, and it also handles delivering mail to the individual users' mailboxes. We'll be setting up OpenSMTPd so that it can communicate to external servers (filtered through spamd) and deliver mail to local users, as well as delivering local mail from user to user.
Dovecot is an MDA which reads local mailboxes and serves them up over IMAP or POP3 to the users. It will use the local users' mailboxes to serve this content.
Spamd is a mail filtering service. We can forward mail through spamd, and it will filter mail based on a variety of deny lists, allow lists, and a greylist.
The general idea for this mail server requires a few different paths:
Outside world -> Firewall -> spamd -> OpenSMTPD -> User mail boxes Outside world -> Firewall (spamd-allow list) -> OpenSMTPD -> User mailboxes Outside world -> Firewall (IMAP/POP3) -> Dovecot Outside world -> Firewall (SMTPD submission)
For this tutorial, we will be using the FreeBSD version of OpenBSD's PF for our firewall. You can also use
ipfw, where the configuration is very similar.
Note: Vultr, by default, blocks port 25, which is used by SMTP servers everywhere. If you want to run a fully functional email server, you will have to get that port opened up.
First, we need to install the required programs.
Assuming you are running as a user with sudo access set up, we can run the following commands. They will vary depending on whether you are using ports or packages.
Unless you need specific functionality built into these utilities, it is recommended to install via packages. It is easier, takes less server time and resources, and provides an intuitive, user friendly interface.
sudo pkg install opensmtpd dovecot spamd
The following
make commands will give you lots of compile options, the defaults will work fine. Do not change these unless you know exactly what you're doing.
sudo portsnap fetch update # or run portsnap fetch extract if using ports for the first time cd /usr/ports/mail/opensmtpd make install # Installs openSMTPd make clean cd /usr/ports/mail/dovecot make install # Installs dovecot make clean cd /usr/ports/mail/spamd make install # Installs spamd make clean
We will need to add the following lines to
/etc/rc.conf:
pf_enable="YES" pf_rules="/usr/local/etc/pf.conf" pflog_enable="YES" pflog_logfile="/var/log/pflog" obspamd_enable="YES" obspamd_flags="-v" obspamlogd_enable="YES" dovecot_enable="YES"
To configure PF, we can create our
/usr/local/etc/pf.conf:
## Set public interface ## ext_if="vtnet0" ## set and drop IP ranges on the public interface ## martians = "{ 127.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, \ 10.0.0.0/8, 169.254.0.0/16, 192.0.2.0/24, \ 0.0.0.0/8, 240.0.0.0/4 }" table <spamd> persist table <spamd-allow> persist # Allowed webmail services table <webmail> persist file "/usr/local/etc/pf.webmail.ip.conf" ## Skip loop back interface - Skip all PF processing on interface ## set skip on lo ## Sets the interface for which PF should gather statistics such as bytes in/out and packets passed/blocked ## set loginterface $ext_if # Deal with attacks based on incorrect handling of packet fragments scrub in all # Pass spamd allow list pass quick log on $ext_if inet proto tcp from <spamd-allow> to $ext_if port smtp \ -> 127.0.0.1 port 25 # Pass webmail servers rdr pass quick log on $ext_if inet proto tcp from <gmail> to $ext_if port smtp \ -> 127.0.0.1 port 25 # pass submission messages. pass quick log on $ext_if inet proto tcp from any to $ext_if port submission modulate state # Pass unknown mail to spamd rdr pass log on $ext_if inet proto tcp from {!<spamd-allow> <spamd>} to $ext_if port smtp \ -> 127.0.0.1 port 8025 ## Blocking spoofed packets antispoof quick for $ext_if ## Set default policy ## block return in log all block out all # Drop all Non-Routable Addresses block drop in quick on $ext_if from $martians to any block drop out quick on $ext_if from any to $martians pass in inet proto tcp to $ext_if port ssh # Allow Ping-Pong stuff. Be a good sysadmin pass inet proto icmp icmp-type echoreq # Open up imap/pop3 support pass quick on $ext_if proto tcp from any to any port {imap, imaps, pop3, pop3s} modulate state # Allow outgoing traffic pass out on $ext_if proto tcp from any to any modulate state pass out on $ext_if proto udp from any to any keep state
This is a working PF configuration. It is relatively simple, but there are a few quirks to be explained as well.
Firstly, we define our
$ext_if variable for our
vtnet0 device to use later on. We also define invalid IP addresses that should be dropped on the external interface.
We also define two tables,
spamd and
spamd-allow - these two tables are created by spamd in it's default configuration. As well, we define a table named
webmail which we will use to allow some major webmail providers through.
To view a table, you can use the command
pfctl -t tablename -T show to list the elements in a table.
We set a few PF rules: skip processing on the local interface, enable statistics on the external interface and scrub incoming packets.
Next is one of the more important parts, where we manage sending our traffic through to spamd or OpenSMTPd.
First up is a redirect rule (note the syntax here, FreeBSD 11 uses the older style PF syntax (pre-OpenBSD 4.6) so the syntax may seem odd. If we receive anything on smtp from a host listed in the
spamd table or not listed in the
spamd-allow table, we redirect the connection through to the spamd daemon, which deals with these connections. The next three rules are passthrough rules so that we can actually receive mail. We pass through messages from the IPs listed in the
spamd-allow and the
webmail tables straight through to OpenSMTPd. Also, we accept messages on the submission port (
587).
Then there's a few housekeeping rules to set our default policy, and accept SSH and ICMP messages.
We then pass IMAP and POP3 on our external interface in order to access Dovecot.
Lastly we allow all outgoing traffic. If you wanted to add extra security, you could limit the ports you pass, but for a single-use server it's not a problem to pass everything.
Start PF:
sudo service pf start
Now that we have our firewall setup, we can move on to our mail server configuration.
OpenSMTPd has a very simple, and easy-to-read configuration syntax. An entire working configuration can fit into 14 lines, as you can see below:
#This is the smtpd server system-wide configuration file. # See smtpd.conf(5) for more information. ext_if=vtnet0 # If you edit the file, you have to run "smtpctl update table aliases" table aliases file:/etc/mail/aliases table domains file:/etc/mail/domains # Keys pki mail.example.com key "/usr/local/etc/letsencrypt/live/mail.example.com/privkey.pem" pki mail.example.com certificate "/usr/local/etc/letsencrypt/live/mail.example.com/fullchain.pem" # If you want to listen on multiple subdomains (e.g. mail.davidlenfesty) you have to add more lines # of keys, and more lines of listeners # Listen for local SMTP connections listen on localhost hostname mail.example.com # listen for filtered spamd connections listen on lo0 port 10026 # Listen for submissions listen on $ext_if port 587 tls-require auth pki mail.example.com tag SUBMITTED # Accept mail from external sources. accept from any for domain <domains> alias <aliases> deliver to maildir "~/mail" accept for local alias <aliases> deliver to maildir "~/mail" accept from local for any relay tls accept tagged SUBMITTED for any relay tls
Firstly, we again define our external interface, as well as a few tables, aliases and domains. Then we move on to the SSL key and certificate for any domains we want to handle mail under.
In the next section, we define the interfaces and ports we want to listen on. Firstly, we listen on localhost for our
mail.example.com domain, for any local connections. Then we listen for our spamd-filtered messages and submitted messages on the external interface. Lastly, we listen for submissions, these happen on port
587 and we are requiring them to authenticate, for security reasons.
Lastly are our
accept settings. We accept any message for any of our domains defined in our
domains table for aliases in our
aliases table, to deliver to their home directory in the
maildir format. Then we accept all local connections for local mailboxes and relay out our messages, so we can send email. Lastly, we accept our submitted messages to relay. If we didn't require authentication for our submissions port, this would be a big security hazard. This would let anyone use our server as a spam relay.
FreeBSD ships with a default alias file
/etc/mail/aliases in the following format:
vuser1: user1 vuser2: user1 vuser3: user1 vuser4: user2
This defines the different mail boxes, and where we want to forward messages sent to these defined mailboxes. We can either define our users as local system users or external mailboxes to forward to. The default FreeBSD file is quite descriptive so you can refer to that for reference.
FreeBSD does not supply a default domains file, but this is incredibly simple:
# Domains example.com mail.example.com smtp.example.com
This is just a plain text file with each domain you want to listen to on a new line. You can make a comment using the
# symbol. This file exists simply so that you can use fewer lines of configuration.
There are two ways to be able to secure your communications with your mail server, self-signed and signed certificates. It is certainly possible to self-sign your certificates, however services like Let's Encrypt provide free and incredibly easy to use signing.
First we have to install the certbot program.
sudo pkg install py-certbot
Alternatively, it can be installed with ports:
cd /usr/ports/security/py-certbot make install make clean
Then, to get your certificate, you need to make sure you have opened up port
80 on your external interface. Add the following lines somewhere in your filtering rules in
/usr/local/etc/pf.conf:
pass quick on $ext_if from any to any port http
Then run
pfctl -f /usr/local/etc/pf.conf to reload the ruleset.
Then you can run the command for any domains you want to get a certificate for:
certbot certonly --standalone -d mail.example.com
It is recommended to set up a crontab entry to run
certbot renew once every 6 months to ensure your certificates don't expire.
Then for every relevant domain, you can modify the lines to point to the correct key file:
pki mail.example.com key "/usr/local/etc/letsencrypt/live/mail.example.com/privkey.pem" pki mail.example.com certificate "/usr/local/etc/letsencrypt/live/mail.example.com/fullchain.pem"
Edit the securities:
sudo chmod 700 /usr/local/etc/letsencrypt/archive/mail.example.com/*
Note: You will have to do this for each original keyfile or else OpenSMTPd won't open them.
Now we can start the service:
sudo service smtpd start
Here we are using OpenBSD's spamd daemon to reduce the amount of spam we get from the internet. Essentially, this filters out messages from IPs that are known as bad from various spam sources, as well as (by default) "greylisting" incoming connections. Spamd also tries to waste spammer's time by "stuttering" denied and greylisted connections, which means it spreads out its response over several seconds which forces the client to stay open for longer than usual.
Greylisting a connection is done when any new IP address connects that isn't on any deny list or allow list. Once the new address connects, spamd drops the message with an inocuous error message, then it adds it to a temporary list. Because spammers get paid for delivered messages, they will not retry on an error, whereas a legitimate service will retry relatively soon.
You will have to run the following to mount
fdescfs:
mount -t fdescfs null /dev/fd
Then you will have to add this line to
/etc/fstab:
fdescfs /dev/fd fdescfs rw 0 0
The default config file (found in
/usr/local/etc/spamd/spamd.conf.sample) will work fine. You can edit it to add new sources or change the sources you use:
sudo cp /usr/local/etc/spamd/spamd.conf.sample /usr/local/etc/spamd/spamd.conf
We can start the service with the following:
sudo service obspamd start
At this point spamd is set up.
One problem with the greylisting approach is that large mail services will often send mail out through one of many different spools, and you aren't guaranteed to get the same server sending the message every time. One solution to this is to allow the IP ranges used by various webmail services. This is what the webmail table is used for in the PF configuration. This strategy can backfire if you include an IP address a spammer uses, but as long as you are careful with what ranges you put in the table you will be fine.
To add an email range to the webmail table, you can run the following command:
pfctl -t webmail -T add 192.0.2.0/24
If you want users to access their mail without logging in via SSH, you'll need an MDA that supports IMAP and/or POP3. A very popular program is Dovecot, with a fairly simple configuration and powerful features.
We can copy over the default configuration:
cd /usr/local/etc/dovecot cp -R example-config/* ./
The configuration is made up of quite a few different files. To see the differences between your configuration and the dovecot defaults, run the command below:
sudo doveconf -n
The following is a simple, working configuration:
# 2.3.2.1 (0719df592): /usr/local/etc/dovecot/dovecot.conf # OS: FreeBSD 11.2-RELEASE amd64 # Hostname: mail.example.com hostname = mail.example.com mail_location = maildir:~/mail namespace inbox { inbox = yes location = mailbox Archive { auto = create special_use = \Archive } mailbox Archives { auto = create special_use = \Archive } mailbox Drafts { auto = subscribe special_use = \Drafts } mailbox Junk { auto = create autoexpunge = 60 days special_use = \Junk } mailbox Sent { auto = subscribe special_use = \Sent } mailbox "Sent Mail" { auto = no special_use = \Sent } mailbox "Sent Messages" { auto = no special_use = \Sent } mailbox Spam { auto = no special_use = \Junk } mailbox Trash { auto = no autoexpunge = 90 days special_use = \Trash } prefix = separator = / } passdb { args = imap driver = pam } ssl = required ssl_cert = </usr/local/etc/letsencrypt/live/mail.example.com/fullchain.pem ssl_dh = </usr/local/etc/dovecot/dh.pem ssl_key = </usr/local/etc/letsencrypt/live/mail.example.com/privkey.pem userdb { driver = passwd }
Most config files will be in
conf.d
The important ones are
10-auth.conf,
10-mail.conf, and
10-ssl.conf.
You can configure the different mailboxes you use in
15-mailboxes.conf. What you see above is a good configuration for many systems, but your mileage may vary. It's recommended you play around with this with as many different clients as you can.
Most default settings will be correct. If you want to use the system users to authenticate, you will have to edit
10-auth.conf.
Uncomment the following line:
!include auth-system.conf.ext
We have to generate Diffie-Hellman parameters:
sudo nohup openssl dhparam -out /usr/local/etc/dovecot/dh.pem
Note: This will take a long time to run. Much longer than you might expect.
We can now start Dovecot:
sudo service dovecot start
At this point, we have a functional, secure and relatively spam-free mail server.
Some more things to look into from here are using SpamAssassin to heuristically get rid of spam, as well as finding more spamd deny lists put out by sources you trust. | https://www.vultr.com/docs/building-your-own-mail-server-with-freebsd-11/ | CC-MAIN-2021-39 | refinedweb | 2,769 | 62.27 |
In this article, we'll learn how to stream data to clients with signalr using aspnet core and Angular 5. We will go through the channel reader /writer which helps in reading/writing into a channel. The channels are playing vital role in streaming data using signalR
Introduction
In this article, we'll learn how to stream data to clients with SignalR using ASP.NET Core and Angular 5. We will go through the channel reader /writer which helps in reading/writing into a channel. The channels play a vital role in streaming data using SignalR. Streaming data is the type of consumer /producer pattern. Let's say the producer is writing data to a channel and the consumer is reading data from the channel. You can choose how to write and read the data from channels so it is memory efficient and high performance. Let us say you are producing data on the channel but somehow a consumer is no longer available to consume the data. In such a case, the memory will increase so you can restrict the channel context to be bound to some limit. Will discuss each of the channels in details below.
The channels were introduced in DOTNET Core 2.1 in "System.Threading.Channels" namespace under the CoreFX () project. The channels are better than data flow and pipeline stream. They are more elegant performers in consumer producer queue patterns and with simple and powerful APIs.
This article is a part of the series on SignalR using ASPNET Core.
This article demonstrates the following.
Prerequisite You must have the following software,
The source code is available at GitHub.
Channels
The System.Threading.Tasks.Channels library provides a set of synchronization data structures for passing the data between producers and consumers. Whereas the existing System.Threading.Tasks.Dataflow library is focused on pipelining and connecting together dataflow "blocks" which encapsulates both storage and processing. System.Threading.Tasks.Channels is focused purely on the storage aspect with data structures used to provide the hand-offs between the participants explicitly coded to use the storage. The library is designed to be used with async/await in C#.
Core channels
At the end of this article , you will be able to achieve the below demo.
In the previous article , we have learned how to create Angular SPA template and we have also seen the start up configuration and npm package installation. The purpose of this article is to work with streaming data in SignalR.
SignalR Startup Configuration
You need to configure the SignalR service in "Configure Service" section and Map the hub in configure section. It automatically adds the SignalR reference for you.
Add SignalR service in Configure service method
Configure Method
After configuring SignalR in Startup we need to install SignalR Javascript library using NPM Package Manager. Run the below command in Command Prompt.
Command
You have to run the above commands in Package manager console (Tools --> Nuget Package Manager --> Package Manager Console)
Now, we are going to create a separate hub for data streaming so I'm going to create a stock ticker hub. The Hub is taking care of communication between client and server.
Creating Stock Hub
We are going to create stock hub class which inherits hub class. The hub has clients API to talk with clients so you can easily invoke. I've created a separate class for stock ticker which is take care about the list of stock and streaming data.
Stock Ticker Hub
Stock Ticker Class Which is taking care about loading stocks and writing data to stream
Creating Stock Angular Service
Now, I'm going to create stock signalR service for the Angular client to subscribe the stream and call any method. This service has three components.
Stock.signalR.service.ts
After creating the service, we have to register with the provider to access in components. Either register for a global provider in app module or for specific one at self. Stock Component The Component takes care of rendring the stream data.
stock.component.ts Class
stock.component.html
Finally, we are finished with the streaming demo with SignalR using ASPNET Core and Angular 5.
Summary
In this article, we have seen the working demo of Streaming data with SignalR using ASP.NET Core and Angular 5. We have learned the following -
References
View All | https://www.c-sharpcorner.com/article/getting-started-with-signalr-using-aspnet-co-streaming-data-using-angular-5/ | CC-MAIN-2019-26 | refinedweb | 724 | 56.86 |
Header guards are used in C and C++ header files to avoid them being included more than once during the compilation of a compilation unit. There are generally two techniques: using an include guard and using a pragma once directive. guardonce provides a set of Python tools that can be used to diagnose the state of header guards, convert between the two types of guards and to fix guards in your codebase.
- Installing guardonce using pip is easy:
$ sudo pip3 install guardonce
- To convert include guards to pragma onces for all header files in the current directory:
$ guard2once *.h
- To convert pragma onces to include guards for all header files in the current directory:
$ once2guard *.h
- The tools support a pattern language that can be used to specify include guard name of a specific pattern. The pattern is built like a Unix pipeline. For example, to convert pragma once to include guard names with a default prefix (say
FOOBAR_) followed by filename in snake form and uppercase:
$ once2guard -p "name | snake | upper | prepend FOOBAR_" *.h
For a filename
linkedList.h the above command would generate an include guard name
FOOBAR_LINKED_LIST_H.
- For include guards it is convenient to have the guard name to appear in comments near the endif. To do that:
$ once2guard -s "#endif // %" *.h
- It is a good convenience to have a newline before the endif. To do that:
$ once2guard -l *.h
- There is no straightforward option to fix or modify the include guards to a certain pattern. Instead I found that I could achieve this by first converting the file to pragma once and then converting back to include guards. This can be done like this:
$ guard2once *.h ; once2guard *.h
Tried with: guardonce 2.4.0 and Ubuntu 18.04
Advertisements | https://codeyarns.com/2019/01/28/how-to-fix-header-guards-using-guardonce/ | CC-MAIN-2019-30 | refinedweb | 293 | 72.97 |
As you have noticed from my previous posts, Atlanta Code Camp took place yesterday, August 24th. I spoke on Entity Framework, and wanted to post my slides and a sample project. Here is the session description.
Entity Framework Code First End to End
This session will cover the use Entity Framework in .NET based applications. Discussion will include model creation and organization as well as schema evolution via migrations. The role of data annotations in Entity Framework model creation and validation will be highlighted. Key issues in achieving performance will be part of the talk, including ability to embed stored procedures when necessary. Creation of a maintainable data access layer via use of repositories will be illustrated. An ASP.NET MVC application will be built throughout the talk to illustrate the concepts.
Here are the links:
Thank you!
Thanks a lot.
Will there be a video available?
It was not recorded this time, but I do have recording of the similar talk available on youtube
Great talk.
I noticed you mentioned batch updates briely in your talk. In my app the user will work on multiple objects (adding deleting and updating) before saving. It looks like in your code you need to have the context around during that time until you savechanges. Any thoughts on that? It seems to be a general challenge with EF 5 though that might be addressed post EF 6.
Thanks, Martin.
Yes, if you want to group updates into a single transaction, you have to do those updates with the same instance of DbContext. If you use generic repository that can update any type of record, you can use the same repository for all the updates though. Is this an issue for you?
Also, you could use different contexts within TransactionScope, but you will need to have MSDTC running, which is not ideal. I hope this helps, unless I am missing something.
Keeping a shared context around seems to be bad practice (threading and concurrency issues). Also when working in a disconnected environment there’s no direct access to the context..
When disposing the context the EF proxys seem to loose data related to its state and its graph relationships. Some workarounds seem to be out their like Graphdiff, but they seem rather complicated (and need modification for the selfreferencing model that i use).
I was not talking about shared context, but an instance specific to your unit of work that you use to update all the data in this unit. You do not need to keep it around passed the final SaveChanges either. Maybe if you provide and example, it would be more clear.
At the moment my DBContext is my unit of work (behind an IContext interface). I’m keeping the context around until savechanges.
Something like this:
interface IContext: IDisposable
{
int SaveChanges();
TItem AddItem();
void DeleteItem(TItem item);
IEnumerable GetAllItems();
}
In a seperate project
public class Context: DBContext, IContext
{
// Implementation
}
Calling Code:
var ctx = IoC.Get(); // create a Context here
// Add, Delete or Modify Items tracked by ctx
// until user presses save project
ctx.SaveChanges();
I’d like to start with a fresh context, but just calling
ctx.Dispose(); won’t do it. Need a way to re-attach or perhaps i can just hang on to the context (but that seem to go against best practices)
Well, you will not be able to do this in a web app, right? You would dispose of the context, then re-attach updated entities on post-back. Why would you not do the same for desktop app?
I want to do the same for the desktop app. The problems occurs for me when disposing the context. The proxies stay around but all the states are set to unchanged and graph relationships are lost ().
so if i do the following in the code above
ctx.SaveChanges();
ctx.Dispose();
ctx = IoC.Get(); // resolve new DBContext
ReAttachGrapToContext();
All the proxies will have a state of unchanged (not a problem in this case since i just saved), but the graph relationships in the proxies are lost as well.
Looking at your code, a new context is created when you create a WriteRepository and disposed when you dispose the repository. It does however not seem to take the state changes of the proxies into account.
If you insert a Contact for example (EntityState.Added) and then dispose the repository (EntityState back to unchanged!). Then try to save the contact with a new repository it will not save
But at that point contact is unchanged. If you change it again and call Update method of new repository, it will persist the changes then, wouldn’t it?
yes true, but what if you don’t change it again. The save operation won’t persist your changes.
I must be missing something. If nothing is changed, what should be persisted?
1 New up a write repository
2 Update an item (state = EntityState.Modified)
3 Dispose repository((state = EntityState.Unchanged triggered by disposing of DbContext)
4 New up a write repository
5 SaveChanges (nothing gets saved eventhough the proxy still has the changes)
Hence you are forced to savechanges before the dispose or manually set the state back to EntityState.Modified and then SaveChanges
I think you are describing the normal web app flow. On post back new up repo, attach items, marked as modified, save, dispose repo. I think the issue you are experiencing is that you want the repo to hang around for you, but I am not sure why. Usually I just get the data and dispose repo. When I am ready to save, I do all the work right away, as I describe above in this answer.
“On post back new up repo, attach items, marked as modified, save, dispose repo”
How do you determine to mark as modified after attaching and not added or unchanged? what if you deleted items?
In our apps we check for changes in the web site and save when items change. We do not currently track each item, but we could. I think you are speaking to the fact that you are using EF objects as business objects, and you can, but you have to make them smarter so that they know what state they are in. If you have business objects on top of EF classes, you can put those smarts in business objects. Hence, the reason I advocate using EF as DAL only. My 2 cents.
I think you hit the nail with the hammer. I’ve been sceptical of using a seperate model for the business objects. It seems that EF code first is so close to be used for the business layer, but when it comes down to it it’s missing a few things. Hopefully they will be adressed post EF6 or perhaps you can help me in the right direction. Could it be as simple as introducing a property in the business object to keep track of the state?
I might still go the route of using a second model for the business layer.
You’re talk convinced me that it’s not too complicated. I’m also thinking of using CSLA objects for the business layer and your approach would fit nicely. Then using the state tracking build into CSLA objects, EF state tracking should be a non issue.
Thanks for your input.
You could add custom properties to the models and mark them not to persist to DB. You can do it in custom base class if you want. It will probably work, but you might run into issues still.
Thank you SIr, great explanation
I’ve one question, what if I’ve a DateTime property in one of my tables, how to set it to .UtcNow() from c# code (configuration class)
for now I’m using a contractor to initialize it :
public class Video
{
public Video()
{
Date = DateTime.UtcNow;
}
public int VideoId { get; set; }
public string VideoTitle { get; set; }
public string VideoUrl { get; set; }
public DateTime Date { get; set; }
public string Description { get; set; }
}
And you do not want to do that in Constructor?
I’m not sure if it’s best way, I just want to know what you think about it and there is a better solution
@Med,
Oh, I see. No, I never had a need to do this because I would consider this business logic, so it would reside in a business object, not an EF DTO. If you are using EF POCOs directly in the UI, then this is correct location for your code I think, assuming you are populating this for new Videos.
Hope this helps.
Thank you Sir for your help,
I was trying to do the same as you did in the video, but I can’t understand what inside of business project (mapping…)
Can you please give some links or tutorials to better understand this architecture
And thank you again for helping people
I do not think I have anything beyond the video on you tube for the talk. The idea is that you create a set of objects you expose to UI, and just map those objects to EF classes for persistence.
Hello Sergey!
Thanks for that video and sample. I am new to EF so i found your code very handy. But I am having some issues with relationships. For example, when I want to save a Signature object with a FK to Document object (and Document Object has a FK to Company object).
Basically when I want to save a set of Signatures, EF triggers validation for Document and Company. Even thou I am passing an id to DocumentID in Signature object.
What am i doing wrong?
Jose
Hi Sergey,
First, Thank you so much. For beginners like us, you are a blessing in disguise
Thanks, I learned a lot from this 🙂 | http://www.dotnetspeak.com/community/entity-framework-talk-at-atlanta-code-camp-2013/ | CC-MAIN-2021-04 | refinedweb | 1,640 | 72.56 |
On 05/05/2015 11:57 PM, Peter Crosthwaite wrote: > So I have made a start on this. The ARM, MB and CRIS in this patch > series is rather easy. Its X86 im having trouble with but your example > here looks like most of the work ... > >> Indeed, the flags setup becomes less obscure when, instead of >> >> #ifdef TARGET_I386 >> if (wsize == 2) { >> flags = 1; >> } else if (wsize == 4) { >> flags = 0; >> } else { > > So here the monitor is actually using the argument memory-dump size to > dictate the flags. Is this flawed and should we delete this wsize > if-else and rely on the CPU-state driven logic for correct disas info > selection? This wsize reliance seems unique to x86. I think we would > have to give this up in a QOMified approach. Hmm. I don't think that I've ever noticed the monitor disassembly could do that. If I were going to do that kind of debugging I certainly wouldn't use the monitor -- I'd use gdb. ;-) If someone thinks we ought to keep that feature, speak now... >> /* as default we use the current CS size */ >> flags = 0; >> if (env) { >> #ifdef TARGET_X86_64 >> if ((env->efer & MSR_EFER_LMA) && >> (env->segs[R_CS].flags & DESC_L_MASK)) > > This uses env->efer and segs to drive the flags... > >> flags = 2; >> else >> #endif >> if (!(env->segs[R_CS].flags & DESC_B_MASK)) >> flags = 1; >> } >> } >> >> in one place and >> >> #if defined(TARGET_I386) >> if (flags == 2) { >> s.info.mach = bfd_mach_x86_64; >> } else if (flags == 1) { >> s.info.mach = bfd_mach_i386_i8086; >> } else { >> s.info.mach = bfd_mach_i386_i386; >> } >> print_insn = print_insn_i386; >> >> in another, we merge the two so that we get >> >> s.info.mach = bfd_mach_i386_i8086; >> if (env->hflags & (1U << HF_CS32_SHIFT)) { > > But your new implementation uses hflags. Are they the same state? I > couldnt find easy correltation between MSR_EFER_LMA and HF_CSXX_SHIFT > (although I do see that map to hflags HF_LMA?). > > Is your code a functional change? It's not intended to be. Since I couldn't find where wsize was initialized, I pulled the tests used by target-i386/translator.c, for dc->code32 and dc->code64, since I knew where to find them right away. ;-) Without going back to the manuals, I don't know the difference between CS64 and LMA; from the code it appears only the behaviour of sysret, which seems surprising. > I went for adding print_insn to disassembly_info and passing just that > to the hook. Patches soon! I might leave X86 out for the first spin. Sounds good. r~ | http://lists.gnu.org/archive/html/qemu-devel/2015-05/msg00838.html | CC-MAIN-2018-05 | refinedweb | 403 | 74.59 |
Metasploit/UsingMixins
Utilizing MSF Mixins For Exploit/Auxiliary Modules Development[edit]
Mixins are a handy mechanism in Ruby language to include functionality into a module. Although Ruby is a single-inheritance language, mixins provide a way to have multiple-inheritance of some sort. Metasploit makes good use of mixins. Understanding and efficiently using mixins is a vital part in the course of module development for MSF. This chapter aims to describe various mixins available, their purpose and functionality.
Please note that mixins are normally not tied to a specific module category (Exploit, Auxiliary etc), though they appear under the one which most closely suits them. This means that you can use Exploit module mixins in Auxiliary modules and vice versa.
Contents
- 1 Utilizing MSF Mixins For Exploit/Auxiliary Modules Development
The Auxiliary::Report Mixin[edit]
This mixin is used to save host, service and vulnerability info to a database. It provides two methods report_host and report_service that are used to indicate the status of a host (Up or Down etc) and a service. To use this module you need to include it into your classes by using: include Auxiliary::Report
After including the mixin, you can use its method to save info in the DB.
Please note if you haven't loaded a backend database, calling these methods won't do anything and will not raise an error.
Auxiliary::Report.report_host()[edit]
This method takes in a hash argument. To save the status of a host that is up, you can call this method as:
report_host(:host => datastore['RHOST'])
To specify that a host is not online (dead), pass the second parameter to the method that should be of type HostState.
report_host(:host => '127.0.0.1', Msf::HostState::Dead)
Auxiliary::Report.report_service()[edit]
Similar to the report_host method, this method also takes a hash argument containing various key-value pairs. The hash can contain values for the following keys:
- addr (The hostname or address)
- port (The numerical port number)
- proto (Protocol can be 'tcp' or 'udp' )
- name (Service name, like 'http', 'https', etc)
- state (service state of type Msf::ServiceState)
The code snippet below reports TCP port 80 to be open for localhost. Notice that the default value for state is Msf::ServiceState::Up so we don't need to specify the state parameter.
report_service(:host => 'localhost', :port => 80, :name => 'HTTP' )
The Auxiliary::Scanner Mixin[edit]
The Scanner mixin allows modules to have the ability to perform operations on more than one host. The easiest and most common way to implement a scanner is to include the scanner mixin with a line like:
include Auxiliary::Scanner
and then implement the run_host(ip) method in your module
def run_host(ip) print_status("Processing IP #{ip}") end
Each host/IP is automatically passed to this function and you just have to implment your logic as if you were working on a single host.
Including the scanner mixin removes the RHOST option from the module options and adds a RHOSTS option to the module. This option allows you to specify network address ranges (like: 192.168.10.0/24, 11.23.45.6-11.23.45.56, etc). This allows module users to specify the hosts to scan.
run_host()[edit]
called with a single IP, with THREADS concurrent threads. The best way to mass-test a range of addresses for a host-specific issue.
run_batch()[edit]
called with a group of IPs with the size defined by the run_batch_size() method, with THREADS concurrent threads. This means it will process multiple batches at the same time, so don't use this for single-host testing (its useful for a few edge cases basically).
run_range()[edit]
called *once* for the entire range of hosts. This is useful if you are going to be passing this range to another tool or doing some network-wide test. For example, calling the nmap program.
USING MULTIPLE THREADS FOR SCANNING[edit]
The scanner module now has an additional feature of using multiple threads to have multiple hosts scanned in parallel. Including the scanner mixin now adds an additional THREADS option to your module with a default value of 1. Module users and/or developers can change this value to anything greater than 1 to have multiple-threaded scanning. | http://en.wikibooks.org/wiki/Metasploit/UsingMixins | CC-MAIN-2014-52 | refinedweb | 709 | 50.87 |
Controllers
In LoopBack 4, controllers handle the request-response lifecycle for your API.
Each function on a controller can be addressed individually to handle an
incoming request (like a POST request to
/todos), to perform business logic,
and to return a response.
Controller is a class that implements operations defined by application’s API.
It implements an application’s business logic and acts as a bridge between the
HTTP/REST API and domain/database models.
In this respect, controllers are the regions in which most of your business logic will live!
For more information about Controllers, see Controllers.
Create your controller
You can create a REST controller using the CLI as follows:
lb4 controller ? Controller class name: todo ? What kind of controller would you like to generate? REST Controller with CRUD functions ? What is the name of the model to use with this CRUD repository? Todo ? What is the name of your CRUD repository? TodoRepository ? What is the type of your ID? number ? What is the base HTTP path name of the CRUD operations? /todos create src/controllers/todo.controller.ts update src/controllers/index.ts Controller todo was created in src/controllers/
Let’s review the
TodoController located in
src/controllers/todo.controller.ts. The
@repository decorator will retrieve
and inject an instance of the
TodoRepository whenever an inbound request is
being handled. The lifecycle of controller objects is per-request, which means
that a new controller instance is created for each request. As a result, we want
to inject our
TodoRepository since the creation of these instances is more
complex and expensive than making new controller instances.
Note: You can customize the lifecycle of all bindings in LoopBack 4! Controllers can easily be made to use singleton lifecycles to minimize startup costs. For more information, see the Dependency injection section of our docs.
In this example, there are two new decorators to provide LoopBack with metadata about the route, verb and.
Some additional things to note about this example:
- Routes like
@get('/todos/{id}')can be paired with the
@param.pathdecorators to inject those values at request time into the handler function.
- LoopBack’s
@paramdecorator also contains a namespace full of other “subdecorators” like
@param.path,
@param.query, and
@param.headerthat allow specification of metadata for those parts of a REST request.
- LoopBack’s
@param.pathand
@param.queryalso provide subdecorators for specifying the type of certain value primitives, such as
@param.path.number('id').
Now that we’ve wired up the controller, our last step is to tie it all into the Application!
Navigation
Previous step: Add a repository
Final step: Putting it all together | https://loopback.io/doc/en/lb4/todo-tutorial-controller.html | CC-MAIN-2019-22 | refinedweb | 437 | 50.23 |
First thing first, you need to install wandb with
pip install wandb
Create a free account then run
wandb login
in your terminal. Follow the link to get an API token that you will need to paste, then you're all set!
Optionally logs weights and or gradients depending on
log (can be "gradients", "parameters", "all" or None), sample predictions if
log_preds=True that will come from
valid_dl or a random sample pf the validation set (determined by
seed).
n_preds are logged in this case.
If used in combination with
SaveModelCallback, the best model is saved as well (can be deactivated with
log_model=False).
Datasets can also be tracked:
- if
log_datasetis
True, tracked folder is retrieved from
learn.dls.path
log_datasetcan explicitly be set to the folder to track
- the name of the dataset can explicitly be given through
dataset_name, otherwise it is set to the folder name
- Note: the subfolder "models" is always ignored
For custom scenarios, you can also manually use functions
log_dataset and
log_model to respectively log your own datasets and models.
Example of use:
Once your have defined your
Learner, before you call to
fit or
fit_one_cycle, you need to initialize wandb:
import wandb wandb.init()
To use Weights & Biases without an account, you can call
wandb.init(anonymous='allow').
Then you add the callback to your
learner or call to
fit methods, potentially with
SaveModelCallback if you want to save the best model:
from fastai.callback.wandb import * # To log only during one training phase learn.fit(..., cbs=WandbCallback()) # To log continuously for all training phases learn = learner(..., cbs=WandbCallback())
Datasets and models can be tracked through the callback or directly through
log_model and
log_dataset functions.
For more details, refer to W&B documentation. | https://docs.fast.ai/callback.wandb.html | CC-MAIN-2020-50 | refinedweb | 289 | 51.58 |
08 March 2013 09:57 [Source: ICIS news]
SINGAPORE (ICIS)--China’s Fushun Petrochemical has increased the operating rates at its 30,000 tonne/year methyl ethyl ketone (MEK) facility in Liaoning province to 90% from 60-70% in February, a company source said on Friday.
The company has yet to set a restart date for its second 25,000 tonne/year plant at the same site, the source said. The facility was shut since May 2012 because of a shortage of feedstock C4 supply.
Chinese MEK domestic prices have come under pressure from increased production after the Lunar New Year holiday (9-15 February) and a slow recovery in downstream demand.
“MEK domestic consumption did not improve as expected after the holiday. The export market is also slow because of ample supply,” a Chinese producer said.
?xml:namespace>
Prices in east China were at yuan (CNY) 8,450-8,500/tonne ($1,359-1,367) ex-tank on 8 March, down by CNY150-200/tonne from prices a week ago, according to Chemease, a service of ICIS.
($ | http://www.icis.com/Articles/2013/03/08/9647921/chinas-fushun-petrochemical-ramps-up-liaoning-mek-production.html | CC-MAIN-2014-41 | refinedweb | 178 | 57 |
import org.w3c.dom.events.Event ;16 17 /**18 * This interface represents a progress event object that notifies the 19 * application about progress as a document is parsed. It extends the 20 * <code>Event</code> interface defined in [<a HREF=''>DOM Level 3 Events</a>]21 * . 22 * <p> The units used for the attributes <code>position</code> and 23 * <code>totalSize</code> are not specified and can be implementation and 24 * input dependent. 25 * <p>See also the <a HREF=''>Document Object Model (DOM) Level 3 Load26 and Save Specification</a>.27 */28 public interface LSProgressEvent extends Event {29 /**30 * The input source that is being parsed.31 */32 public LSInput getInput();33 34 /**35 * The current position in the input source, including all external 36 * entities and other resources that have been read.37 */38 public int getPosition();39 40 /**41 * The total size of the document including all external resources, this 42 * number might change as a document is being parsed if references to 43 * more external resources are seen. A value of <code>0</code> is 44 * returned if the total size cannot be determined or estimated.45 */46 public int getTotalSize();47 48 }49
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | http://kickjava.com/src/org/w3c/dom/ls/LSProgressEvent.java.htm | CC-MAIN-2017-04 | refinedweb | 213 | 52.39 |
Scaffolding for the Global Function Search optimizer from Dlib
Project description
gfsopt
pip3 install --user gfsopt
Convenient scaffolding for the excellent Global Function Search hyperparameter optimizer from the Dlib library. (See: 'A Global Optimization Algorithm Worth Using')
Provides the following features:
- Parallel optimization: Run multiple hyperparameter searches in parallel
- Save and restore progress: Save/restore settings and optimization progress to/from file.
- Average over multiple runs: Run a stochastic objective function using the same parameters multiple times and report the average to Dlib's Global Function Search. Useful in highly stochastic domains to avoid biasing the search towards lucky runs.
Example usage
A basic example where we maximize
obj_func with respect to
y over 10 runs,
with as many parallel processes as there are logical cores, and save progress to file.
from gfsopt import GFSOptimizer def obj_func(x, y, pid): """"Function to be maximized (pid is iteration number)"""" a = (1.5 - x + x * y)**2 b = (2.25 - x + x * y * y)**2 c = (2.625 - x + x * y * y * y)**2 return -(a + b + c) # For this example we pretend that we want to keep 'x' fixed at 0.5 # while optimizing 'y' in the range -4.5 to 4.5
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/gfsopt/ | CC-MAIN-2020-16 | refinedweb | 223 | 55.13 |
Day for the given Date in Java
Day for the given Date in Java How can i get the day for the user input data ?
Hello Friend,
You can use the following code:
import...");
String day=f.format(date);
System.out.println
OOPs What is OOps? Object oriented programming organizes a program around its data,i.e.,objects and a set of well defined interfaces... access to code
Get first day of week
Get first day of week
In this section, we will learn how to get the first day
of ..._package>java FirstDayOfWeek
Day of week: 7
Sunday
OOPs concepts in Java
Object-Oriented Programming (OOPs) concepts in Java helps in creating programs that are based on real world.
OOPs is very flexible and compatible and hence... application that are developed on the OOPs concepts at first analyze the program
OOPs Concept
the OOPs concepts along with
fundamentals used to develop the java...
OOPs Concept
.... This is a technique
used to create
programs around the real world entities. In OOPs
Find Day of Month
Find Day of Month
This example explores how to find
the day of a month and the day of a week This example sets the year as 2007
and the day as 181. The example
error message - Java Beginners
information.... and run java programs.
i am sending simple java code,
public class Hello...error message sir,
while i m trying to execute my first program
Easiest way to learn Java
There are various ways to learn Java language but the easiest way to learn..., video
tutorials and lectures that help beginners learn in Java. This tutorials..., Java classes, etc are covered. To make it easy for novices to
learn
oops concepts - Java Interview Questions
oops concepts what stands for "S" in OOPs ? object oriented programing..... Hi friend,
Object Oriented Programming or OOP....
Thanks
Code error
Code error package trail;
import...)
read.close();
}
}
}
While using this it shows error as:
run...(ClassLoader.java:247)
... 17 more
Java Result: 1
BUILD SUCCESSFUL (total time: 9
Find the Day of the Week
Find the Day of the Week
This example finds the specified date of an year and
a day... time zone, locale
and current time.
The fields used:
DAY_OF_WEEK
learn
learn how to input value in java
Java Code Color Function Error
Java Code Color Function Error Java Code Color Function Error
learn
learn i need info about where i type the java's applet and awt programs,and how to compile and run them.please give me answer
error in java code - Java Beginners
error in java code Hi
Can u say how to communication between systems in a network. Hi friend,
A method for controlling an operation.../java/network/index.shtml
Thanks
Java compilation error - Java Beginners
://
b) Close... at compilation error Hello,
i am getting an error while
Java code error - Java Beginners
Java code error Hi,
I am using a MooreQuery to look for neighbors in a grid:
MooreQuery query = new MooreQuery(grid, this,(int) (2*myHomeRangeRadius), (int) (2*myHomeRangeRadius));
if(query != null){
for (Object
Implementation of Day Class
to be returned is Monday.
Here is the code:
public class Day {
final static int...Implementation of Day Class
Here we are going to design and implement the class Day. The class Day should store the days of the week. Then test the following
Learn Java in 24 hours
it hard
to code in Java language.
RoseIndia brings you a quick Java guide... find it easy to understand the example.
To learn Java in 24 hours, you must clear... to execute a particular task.
Oops Concept
Java is an Object Oriented
Where can I learn Java Programming
Learn Java in a Day
Master Java
in a Week
More links for Java... and
time to learn Java in a right way. This article is discussing the most asked
question which is "Where can I learn Java Programming?". We
Getting Previous, Current and Next Day Date
Getting Previous, Current and Next Day Date
In this section, you will learn how to get previous,
current and next date in java. The java util package provides
java runtime error: JDBC code - Java Beginners
java runtime error: JDBC code Hi i want to insert data into mysql... and also set in the class path. the code is compilled and giving runtime error.... Hi friend,
Plz give full details with source code to solve
to learn java
to learn java I am b.com graduate. Can l able to learn java platform without knowing any basics software language.
Learn Java from the following link:
Java Tutorials
Here you will get several java tutorials
Error Handling in Java Script
will Learn how to handle error in
java script.
JavaScript is scripting language used...
Error Handling in Java Script
...
will return error. the try block contains run able code and catch block
contains
Learn java
Learn java Hi,
I am absolute beginner in Java programming Language. Can anyone tell me how I can learn:
a) Basics of Java
b) Advance Java
c) Java frameworks
and anything which is important.
Thanks
Learn Java - Learn Java Quickly
Learn Java - Learn Java Quickly
.... This is a software process that converts the compiled Java byte code to
machine code. Byte code is an intermediary language between Java source and the
host system
Hey Guys really need to learn - Java Beginners
u will use scanf(%d%d%d, & month, day, year). How can i do this in java...Hey Guys really need to learn Im a java beginner and i want to know... the following code to input three integers from the command prompt.
import
OOPs and Its Concepts in Java
OOPs and Its Concepts in Java
....
Java is a object oriented programming and to understand the
functionality of OOP in Java, we first need to understand several fundamentals
related
How to learn Java easily?
If you are wondering how to learn Java easily, well its simple, learn...
Java learning.
The students opting to learn Java are of two types, either... a simple language and
easy way to understand and learn the language. Java on its
error in code - Java Server Faces Questions
error in code hi friends i have a problem in execution of JSF it is displaying the error like "Cannot find FacesContext" i am not understanding plz check the error and give me the answer
i am sending the code of web.xml
java Compilation error:jsp code - JSP-Servlet
java Compilation error:jsp code I am getting an Generated Servlet error:
String literal is not properly closed by a double-quote.
here is my code:
<%
{
Dbclass2 d= new Dbclass2
How to learn programming free?
,
Here are the tutorials:
Beginners Java Tutorial
Learn Java in a day
Master Java...How to learn programming free? Is there any tutorial for learning Java absolutely free?
Thanks
Hi,
There are many tutorials on Java
Error in MySQL Procedure Using JAVA Code
Error in MySQL Procedure Using JAVA Code The following Java code (using Connector/J to create a stored procedure on MySQL 5.0) does not execute successfully. Identify the cause and available solutions.
statement.execute
basic java - Java Beginners
basic java oops concept in java ? Hi Friend,
Please visit the following links:
Thanks
Java Error - Java Beginners
Java Error E:\SUSHANT\Core Java\FileHandling\Error>javac...
ch= reader.read();
^
1 error
import java.io.... "+e);
}
}
} Hi Friend,
Try the following code
JDBC Training, Learn JDBC yourself
programming language of java then fist
learn our following two tutorials:
Learn Java in a Day and
Master...
JDBC Connection Pooling
Accessing Database
using Java and JDBC
Learn how
Java Compilation error. Hibernate code problem. Struts first example - Hibernate
Java Compilation error. Hibernate code problem. Struts first example Java Compilation error. Hibernate code problem. Struts first example
JSF code Error - Java Server Faces Questions
JSF code Error Hii Friends,
When Iam working on JSF..,What jars are have to add in Applicaton?
Thanks and Regards By
Sreedhar
java error - Java Beginners
Friend,
Save java file with 'SortFileData.java' and try the following code...java error Thanks for providing me the answer for the question,but there are some errors while running the code are
1.class SortFileData is public
Determining the Day-of-Week for a Particular Date
Determining the Day-of-Week for a Particular Date
This section simply show the current day in word i.e.
the Day of Week for a particular date. Here,
you can learn about the way
java error - Java Beginners
java error Dear roseindiamembers,
I have checked the registration form for new user to login roseindiamembers forum with different data.It's... this email be validated .I opened the source code also you have done ur validations
error
of framework used and also the JDK version.
This type error also comes when java file is complied in old version of java and used on latest version.
Thanks
java - Java Beginners
Java error handling How to write a code to handle the errors in Java? hi all,visit these site mentioned below will work
java code
java code hello sir,
i want to devlop one simple app in java,c,c++ which is made without using database and awt system is multiplex cinema ticket... booking.
2)find a highest gained movie for the day.
3)find screens which Programming
in it, Learn Java programming online with tutorials and simple examples that explains every single code. The online learning of Java begins with simple example... of the programmer wants to learn this language quickly.
The basic of Java tutorials
java code
java code int g()
{
System.out.println("Inside method g");
int h()
{
System.out.println("Inside method h");
}
}
Find the error in the following program segment and explain how to correct the error?
Firstly, int type
java compilation error - Applet
java compilation error hi friends
the following is the awt front design program error, give me the replay
E:\ramesh>javac...,
Plz give full details with source code and visit to :
http
How we learn java
How we learn java what is class in java?
what is object in java?
what is interface in java and use?
what is inheritence and its type
Learn Servlet Life Cycle
Learn Servlet Life Cycle
Servlet is a Java programming language class... of the servlet. The servlet will only be available for service if it is servlet code is loaded successfully without any error otherwise it will be not available
runtime error - Java Beginners
runtime error I created a sample java source ,compiled it succesfully using command prompt but when i tried to run i got the folowing error... with source code :
Thanks
Features of Java
of occurance of any error and a lot more.
JAVA IS ARCHITECTURALLY NEUTRAL... architecture. This byte code makes java an architecture neutral language because this code can be interpreted by any system which has java virtual machine (JVM
Features of Java
Java is a class based Object Oriented Programming (OOPs) language, which... , programs are easy to write and easy to learn
Java provides the bug free system...:
Java is an Object Oriented Programming (OOPs) language and provides simple
OOP
OOP
OOPs stands... to test the module in the procedurally developed
code because the coded modules were...
and scenerios. OOPs enables to program the real world objects and easily play
java compilation error - Java Beginners
java compilation error i am going to type program and the error is shaded one this one is giving error please sole this one sir
import java.io....:"+ch);
}
}
Hi friend,
Having some error in your code check | http://roseindia.net/tutorialhelp/comment/66436 | CC-MAIN-2014-42 | refinedweb | 1,930 | 55.54 |
On Dec 30, 2008, at 8:33 PM, Antony Blakey wrote:
>
> On 30/12/2008, at 1:40 AM, Robert Dionne wrote:
>
>> With respect to a meta structure, I was going to make this comment
>> yesterday as I think Geir was arguing for this:
>>
>> It seems to me that occam's razor argues for the simplicity of a
>> single JSON doc, rather that a "metadoc" envelope that contains
>> another JSON doc embedded in it. It's not clear to me that
>> creating this separation of concerns buys anything at all. The use
>> of an underscore to designate distinguished fields at the top
>> level is a fairly easy convention to get your arms around.
>
> That's not actually the issue. The issue is about having a single
> name, and not inventing a namespace technique for json docs. The
> choices are:
I understand the issue. I noted the use of _id versus id myself and
wasn't that put off by it, just seemed a quirk of the implementation.
I realize you've likely written a lot of code a this point and have
run into reuse issues. It's not unusual to have different names for
the same thing if the context is different.
>
> 1. The current scheme of prepending _ to atom names when the atom
> is used inside a document. Con is the breakage of name identity,
> which has technical consequences as well as cognitive ones. Does
> the rule only apply at the top level of a document? What about
> future injected metadata that has internal structure?
>
> 2. Use '_' for all atoms, inside and outside documents. Con is the
> noise of extra underscores everywhere.
>
> 3. Don't use underscores inside documents - for id and rev at
> least, this wouldn't seem to be a big issue, but isn't future-proof
> if you want to handle other injected fields.
>
> 4. Use '_' for atoms that have to be injected, and make the name BE
> the '_' form. Con is that you have to decide in advance if an atom
> is going to ever be injected.
>
> 5. Use a '_meta' wrapper for the metadata. I don't see any
> technical cons, and IMO is by far the cleanest model. Name identity
> is preserved, it's arbitrarily extensible without scalability
> concerns, and is structural rather than lexical.
It is clearly cleaner and has it's advantages, however I have to
agree with an earlier poster; "Putting them in a _meta group might
encourage aggregation and manipulation of the bookkeeping metadata
separately from the document, which to me sounds like a recipe for
trouble."
This would be a more complex design than the current use of the
underscore at the top level of documents and would definitely
encourage a quite different implementation. I don't know the
internals enough yet to comment on this. The code there to date is
remarkably terse for what it does but this may just reflect the use
of Erlang.
Cheers,
Bob
>
> IMO option 5 is the best and cleanest solution.
>
>
>
> | http://mail-archives.apache.org/mod_mbox/incubator-couchdb-user/200812.mbox/%3C34FCDB16-6D06-4401-BCD8-0B053E2E935E@gmail.com%3E | CC-MAIN-2017-26 | refinedweb | 505 | 69.41 |
This tutorial will attempt to describe how to write a simple device driver for Windows NT. There are various resources and tutorials on the internet for writing device drivers, however, they are somewhat scarce as compared to writing a �hello world� GUI program for Windows. This makes the search for information on starting to write device drivers a bit harder. You may think that if there�s already one tutorial, why do you need more? The answer is that more information is always better especially when you are first beginning to understand a concept. It is always good to see information from different perspectives. People write differently and describe certain pieces of information in a different light depending on how familiar they are with a certain aspect or how they think it should be explained. This being the case, I would recommend anyone who wants to write device drivers not to stop here or somewhere else. Always find a variety of samples and code snippets and research the differences. Sometimes there are bugs and things omitted. Sometimes there are things that are being done that aren�t necessary, and sometimes there�s information incorrect or just incomplete.
This tutorial will describe how to create a simple device driver, dynamically load and unload it, and finally talk to it from user mode.
I need to define a starting ground before we begin to explain how to write a device driver. The starting point for this article will be the compiler. The compiler and linker generate a binary in a format that the Operating System understands. In Windows, this format is �PE� for �Portable Executable� format. In this format, there is an idea called a subsystem. A subsystem, along with other options specified in the PE header information, describes how to load an executable which also includes the entry point into the binary.
Many people use the VC++ IDE to simply create a project with some default pre-set options for the compiler�s (and linker) command line. This is why a lot of people may not be familiar with this concept even though they are most likely already using it if they have ever written Windows applications. Have you ever written a console application? Have you ever written a GUI application for Windows? These are different subsystems in Windows. Both of these will generate a PE binary with the appropriate subsystem information. This is also why a console application uses �
main� where a WINDOWS application uses �
WinMain�. When you choose these projects, VC++ simply creates a project with /SUBSYSTEM:CONSOLE or /SUBSYSTEM:WINDOWS. If you accidentally choose the wrong project, you can simply change this in the linker options menu rather than needing to create a new project.
There�s a point to all of this? A driver is simply linked using a different subsystem called �NATIVE�. MSDN Subsystem compiler options.
After the compiler is setup with the appropriate options, it�s probably good to start thinking about the entry point to a driver. The first section lied a little bit about the subsystem. �NATIVE� can also be used to run user-mode applications which define an entry point called �
NtProcessStartup�. This is the �default� type of executable that is made when specifying �NATIVE� in the same way �
WinMain� and �
main� are found when the linker is creating an application. You can override the default entry point with your own, simply by using the �-entry:<functionname>� linker option. If we know we want this to be a driver, we simply need to write an entry point whose parameter list and return type matches that of a driver. The system will then load the driver when we install it and tell the system that it is a driver.
The name we use can be anything. We can call it
BufferFly() if we want. The most common practice used by driver developers and Microsoft is using the name �
DriverEntry� as its initial entry point. This means we add �-entry:DriverEntry� to the linker�s command line options. If you are using the DDK, this is done for you when you specify �DRIVER� as the type of executable to build. The DDK contains an environment that has pre-set options in the common make file directory which makes it simpler to create an application as it specifies the default options. The actual driver developer can then override these settings in the make file or simply use them as a connivance. This is essentially how �
DriverEntry� became the somewhat �official� name for driver entry points.
Remember, DLLs actually are also compiled specifying �WINDOWS� as the subsystem, but they also have an additional switch called /DLL. There is a switch which can also be used for drivers: /DRIVER:WDM (which also sets NATIVE behind the scenes) as well as a /DRIVER:UP which means this driver cannot be loaded on a multi-processor system.
The linker builds the final binary, and based on what the options are in the PE header and how the binary is attempting to be loaded (run as an EXE through the loader, loaded by
LoadLibrary, or attempting to be loaded as a driver) will define how the loading system behaves. The loading system attempts to perform some level of verification, that the image being loaded is indeed supposed to be loaded in this manner, for example. There is even, in some cases, startup code added to the binary that executes before your entry point is reached (
WinMainCRTStartup calling
WinMain, for example, to initialize the CRT). Your job is to simply write the application based on how you want it to be loaded and then set the correct options in the linker so it knows how to properly create the binary. There are various resources on the details of the PE format which you should be able to find if you are interested in further investigation into this area.
The options we will set for the linker will end up being the following:
/SUBSYSTEM:NATIVE /DRIVER:WDM �entry:DriverEntry
There are some things we need to go over before we simply sit down and write the �
DriverEntry�. I know that a lot of people simply want to jump right into writing the driver and seeing it work. This is generally the case in most programming scenarios as you usually just take the code, change it around, compile it, and test it out. If you remember back to when you were first learning Windows development, it was probably the same way. Your application probably didn�t work right away, probably crashed, or just disappeared. This was a lot of fun and you probably learned a lot, but you know that with a driver, the adventure is a little different. Not knowing what to do can end up in blue screening the system, and if your driver is loaded on boot and executes that code, you now have a problem. Hopefully, you can boot in safe mode or restore to a previous hardware configuration. That being the case, we have a few things to go over before you write the driver in order to help educate you on what you are doing before you actually do it.
The first rule of thumb is do not just take a driver and compile it with some of your changes. If you do not understand how the driver is working or how to program correctly in the environment, you are likely to cause problems. Drivers can corrupt the integrity of the whole system, they can have bugs that don�t always occur but in some rare circumstances. Application programs can have the same type of bugs in behavior but not in root cause. As an example, there are times when you cannot access memory that is pagable. If you know how Virtual Memory works, you know that the Operating System will remove pages from memory to pull in pages that are needed, and this is how more applications can run than would have been physically possible given the memory limitations of the machine. There are places, however, when pages cannot be read into memory from disk. At these times, those �drivers� who work with memory can only access memory that cannot be paged out.
Where am I going with this? Well, if you allow a driver which runs under these constraints to access memory that is �pagable�, it may not crash as the Operating System usually tries to keep all pages in memory as long as possible. If you close an application that was running, it may still be in memory, for example! This is why a bug like this may go undetected (unless you try doing things like driver verifier) and eventually may trap. When it does, if you do not understand the basic concepts like this, you would be lost as to what the problem is and how to fix it.
There are a lot of concepts behind everything that will be described in this document. On IRQL alone, there is a twenty page document you can find on MSDN. There�s an equally large document on IRP. I will not attempt to duplicate this information nor point out every single little detail. What I will attempt to do is give a basic summary and point you in the direction of where to find more information. It�s important to at least know that these concepts exist and understand some basic idea behind them, before writing the driver.
The IRQL is known as the �Interrupt ReQuest Level�. The processor will be executing code in a thread at a particular IRQL. The IRQL of the processor essentially helps determine how that thread is allowed to be interrupted. The thread can only be interrupted by code which needs to run at a higher IRQL on the same processor. Interrupts requiring the same IRQL or lower are masked off so only interrupts requiring a higher IRQL are available for processing. In a multi-processor system, each processor operates independently at its own IRQL.
There are four IRQL levels which you generally will be dealing with, which are �Passive�, �APC�, �Dispatch� and �DIRQL�. Kernel APIs documented in MSDN generally have a note which specifies the IRQL level at which you need to be running in order to use the API. The higher the IRQL you go, the less APIs that are available for use. The documentation on MSDN defines what IRQL the processor will be running at when the particular entry point of the driver is called. �
DriverEntry�, for example, will be called at
PASSIVE_LEVEL.
This is the lowest IRQL. No interrupts are masked off and this is the level in which a thread executing in user mode is running. Pagable memory is accessible.
APC_LEVEL
In a processor running at this level, only APC level interrupts are masked. This is the level in which Asynchronous Procedure Calls occur. Pagable memory is still accessible. When an APC occurs, the processor is raised to APC level. This, in turn, also disables other APCs from occurring. A driver can manually raise its IRQL to APC (or any other level) in order to perform some synchronization with APCs, for example, since APCs can�t be invoked if you are already at APC level. There are some APIs which can�t be called at APC level due to the fact that APCs are disabled, which, in turn, may disable some I/O Completion APCs.
DISPATCH_LEVEL
The processor running at this level has DPC level interrupts and lower masked off. Pagable memory cannot be accessed, so all memory being accessed must be non-paged. If you are running at Dispatch Level, the APIs that you can use greatly decrease since you can only deal with non-paged memory.
Generally, higher level drivers do not deal with IRQLs at this level, but all interrupts at this level or less are masked off and do not occur. This is actually a range of IRQLs, and this is a method to determine which devices have priority over other devices.
In this driver, we will basically only be working at
PASSIVE_LEVEL, so we won�t have to worry about the gotchas. However, it is necessary for you to be aware of what IRQL is, if you intend to continue writing device drivers.
For more information on IRQLs and thread scheduling, refer to the following documentation, and another good source of information is here.
The �IRP� is called the �I/O Request Packet�, and it is passed down from driver to driver in the driver stack. This is a data structure that allows drivers to communicate with each other and to request work to be done by the driver. The I/O manager or another driver may create an IRP and pass it down to your driver. The IRP includes information about the operation that is being requested.
A description of the IRP data structure can be found here.
The description and usage of an IRP can go from simple to complex very easily, so we will only be describing, in general, what an IRP will mean to you. There is an article on MSDN which describes in a lot more detail (about twenty pages) of what exactly an IRP is and how to handle them. That article can be found here.
The IRP will also contain a list of �sub-requests� also known as the �IRP Stack Location�. Each driver in the device stack will generally have its own �sub request� of how to interpret the IRP. This data structure is the �IO_STACK_LOCATION� and is described on MSDN.
To create an analogy of the IRP and
IO_STACK_LOCATION, perhaps you have three people who do different jobs such as carpentry, plumbing and welding. If they were going to build a house, they could have a common overall design and perhaps a common set of tools like their tool box. This includes things like power drills, etc. All of these common tools and overall design of building a house would be the IRP. Each of them has an individual piece they need to work on to make this happen, for example, the plumber needs the plans on where to put the pipe, how much pipe he has, etc. These could be interpreted as the
IO_STACK_LOCATION as his specific job is to do the piping. The carpenter could be building the framework for the house and the details of that would be in his
IO_STACK_LOCATION. So, while the entire IRP is a request to build a house, each person in the stack of people has their own job as defined by the
IO_STACK_LOCATION to make this happen. Once everyone has completed their job, they then complete the IRP.
The device driver we will be building will not be that complex and will basically be the only driver in the stack.
There are a lot of pitfalls that you will need to avoid but they are mostly unrelated to our simple driver. To be more informed, however, here is a list of items called �things to avoid� when it comes to driver development.
There is so much to explain, however, I think it�s time we simply started to develop the driver and explain as we go. It is hard to digest theory or even how code is supposed to work, without actually doing anything. You need some hands on experience so you can bring these ideas out of space and into reality.
The prototype for the DriverEntry is the following.
NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pRegistryPath);
The
DRIVER_OBJECT is a data structure used to represent this driver. The
DriverEntry routine will use it to populate it with other entry points to the driver for handling specific I/O requests. This object also has a pointer to a
DEVICE_OBJECT which is a data structure which represents a particular device. A single driver may actually advertise itself as handling multiple devices, and as such, the
DRIVER_OBJECT maintains a linked list pointer to all the devices this particular driver services request for. We will simply be creating one device.
The �Registry Path� is a string which points to the location in the registry where the information for the driver was stored. The driver can use this location to store driver specific information.
The next part is to actually put things in the
DriverEntry routine. The first thing we will do is create the device. You may be wondering how we are going to create a device and what type of device we should create. This is generally because a driver is usually associated with hardware but this is not the case. There are a variety of different types of drivers which operate at different levels, not all drivers work or interface directly with hardware. Generally, you maintain a stack of drivers each with a specific job to do. The highest level driver is the one that communicates with user mode, and the lowest level drivers generally just talk to other drivers and hardware. There are network drivers, display drivers, file system drivers, etc., and each has their own stack of drivers. Each place in the stack breaks up a request into a more generic or simpler request for the lower level driver to service. The highest level drivers are the ones which communicate themselves to user mode, and unless they are a special device with a particular framework (like display drivers), they can behave generally the same as other drivers just as they implement different types of operations.
As an example, take the hard disk drive. The driver which communicates to user mode does not talk directly to hardware. The high level driver simply manages the file system itself and where to put things. It then communicates where it wants to read or write from the disk to the lower level driver which may or may not talk directly to hardware. There may be another layer which then communicates that request to the actual hardware driver which then physically reads or writes a particular sector off a disk and then returns it to the higher level. The highest level may interpret them as file data, but the lowest level driver may simply be stupid and only manage requests as far as when to read a sector based off where the read/write head is located on the disk. It could then determine what sector read requests to service, however, it has no idea what the data is and does not interpret it.
Let�s take a look at the first part of our �
DriverEntry�.
NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pRegistryPath) { NTSTATUS NtStatus = STATUS_SUCCESS; UINT uiIndex = 0; PDEVICE_OBJECT pDeviceObject = NULL; UNICODE_STRING usDriverName, usDosDeviceName; DbgPrint("DriverEntry Called \r\n"); RtlInitUnicodeString(&usDriverName, L"\\Device\\Example"); RtlInitUnicodeString(&usDosDeviceName, L"\\DosDevices\\Example"); NtStatus = IoCreateDevice(pDriverObject, 0, &usDriverName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE, &pDeviceObject);
The first thing you will notice is the
DbgPrint function. This works just like �
printf� and it prints messages out to the debugger or debug output window. You can get a tool called �DBGVIEW� from and all of the information in those messages will be displayed.
You will then notice that we use a function called �
RtlInitUnicodeString� which basically initializes a
UNICODE_STRING data structure. This data structure contains basically three entries. The first is the size of the current Unicode string, the second is the maximum size that the Unicode string can be, and the third is a pointer to the Unicode string. This is used to describe a Unicode string and used commonly in drivers. The one thing to remember with
UNICODE_STRING is that they are not required to be
NULL terminated since there is a size parameter in the structure! This causes problems for people new to driver development as they assume a
UNICODE_STRING is
NULL terminated, and they blue-screen the driver. Most Unicode strings passing into your driver will not be
NULL terminated, so this is something you need to be aware of.
Devices have names just like anything else. They are generally named \Device\<somename> and this is the string we were creating to pass into
IoCreateDevice. The second string, �\DosDevices\Example�, we will get into later as it�s not used in the driver yet. To the
IoCreateDevice, we pass in the driver object, a pointer to the Unicode string we want to call the driver, and we pass in a type of driver �
UNKNOWN� as it�s not associated with any particular type of device, and we also pass in a pointer to receive the newly created device object. The parameters are explained in more detail at �IoCreateDevice�.
The second parameter we passed 0, and it says to specify the number of bytes to create for the device extension. This is basically a data structure that the driver writer can define which is unique to that device. This is how you can extend the information being passed into a device and create device contexts, etc. in which to store instance data. We will not be using this for this example.
Now that we have successfully created our \Device\Example device driver, we need to setup the Driver Object to call into our driver when certain requests are made. These requests are called IRP Major requests. There are also Minor requests which are sub-requests of these and can be found in the stack location of the IRP.
The following code populates certain requests:
for(uiIndex = 0; uiIndex < IRP_MJ_MAXIMUM_FUNCTION; uiIndex++) pDriverObject->MajorFunction[uiIndex] = Example_UnSupportedFunction; pDriverObject->MajorFunction[IRP_MJ_CLOSE] = Example_Close; pDriverObject->MajorFunction[IRP_MJ_CREATE] = Example_Create; pDriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = Example_IoControl; pDriverObject->MajorFunction[IRP_MJ_READ] = Example_Read; pDriverObject->MajorFunction[IRP_MJ_WRITE] = USE_WRITE_FUNCTION;
We populate the
Create,
IoControl,
Read and
Write. What do these refer to? When communicating with the user-mode application, certain APIs call directly to the driver and pass in parameters!
CreateFile->
IRP_MJ_CREATE
CloseHandle->
IRP_MJ_CLEANUP & IRP_MJ_CLOSE
WriteFile->
IRP_MJ_WRITE
ReadFile->
IRP_MJ_READ
DeviceIoControl->
IRP_MJ_DEVICE_CONTROL
To explain, one difference is
IRP_MJ_CLOSE is not called in the context of the process which created the handle. If you need to perform process related clean up, then you need to handle
IRP_MJ_CLEANUP as well.
So as you can see, when a user mode application uses these functions, it calls into your driver. You may be wondering why the user mode API says �file� when it doesn�t really mean �file�. That is true, these APIs can talk to any device which exposes itself to user mode, they are not only for accessing files. In the last piece of this article, we will be writing a user mode application to talk to our driver and it will simply do
CreateFile,
WriteFile,
CloseHandle. That�s how simple it is.
USE_WRITE_FUNCTION is a constant I will explain later.
The next piece of code is pretty simple, it�s the driver unload function.
pDriverObject->DriverUnload = Example_Unload;
You can technically omit this function but if you want to unload your driver dynamically, then it must be specified. If you do not specify this function once your driver is loaded, the system will not allow it to be unloaded.
The code after this is actually using the
DEVICE_OBJECT, not the
DRIVER_OBJECT. These two data structures may get a little confusing since they both start with �D� and end with �_OBJECT�, so it�s easy to confuse which one we�re using.
pDeviceObject->Flags |= IO_TYPE; pDeviceObject->Flags &= (~DO_DEVICE_INITIALIZING);
We are simply setting the flags. �
IO_TYPE� is actually a constant which defines the type of I/O we want to do (I defined it in example.h). I will explain this in the section on handling user-mode write requests.
The �
DO_DEVICE_INITIALIZING� tells the I/O Manager that the device is being initialized and not to send any I/O requests to the driver. For devices created in the context of the �
DriverEntry�, this is not needed since the I/O Manager will clear this flag once the �
DriverEntry� is done. However, if you create a device in any function outside of the
DriverEntry, you need to manually clear this flag for any device you create with
IoCreateDevice. This flag is actually set by the
IoCreateDevice function. We cleared it here just for fun even though we weren�t required to.
The last piece of our driver is using both of the Unicode strings we defined above. �\Device\Example� and �\DosDevices\Example�.
IoCreateSymbolicLink(&usDosDeviceName, &usDriverName);
�
IoCreateSymbolicLink� does just that, it creates a �Symbolic Link� in the object manager. To view the object manager, you may download my tool �QuickView�, or go to and download �WINOBJ�. A Symbolic Link simply maps a �DOS Device Name� to an �NT Device Name�. In this example, �Example� is our DOS Device Name and �\Device\Example� is our NT Device Name.
To put this into perspective, different vendors have different drivers and each driver is required to have its own name. You cannot have two drivers with the same NT Device name. Say, you have a memory stick which can display itself to the system as a new drive letter which is any available drive letter such as E:. If you remove this memory stick and say you map a network drive to E:. Application can talk to E: the same way, they do not care if E: is a CD ROM, Floppy Disk, memory stick or network drive. How is this possible? Well, the driver needs to be able to interpret the requests and either handle them within themselves such as the case of a network redirector or pass them down to the appropriate hardware driver. This is done through symbolic links. E: is a symbolic link. The network mapped drive may map E: to \Device\NetworkRedirector and the memory stick may map E: to \Device\FujiMemoryStick, for example.
This is how applications can be written using a commonly defined name which can be abstracted to point to any device driver which would be able to handle requests. There are no rules here, we could actually map \Device\Example to E:. We can do whatever we wish to do, but in the end, however, the application attempts to use the device as how the device driver needs to respond and act. This means supporting IOCTLs commonly used by those devices as applications will try to use them. COM1, COM2, etc. are all examples of this. COM1 is a DOS name which is mapped to an NT Device name of a driver which handles serial requests. This doesn�t even need to be a real physical serial port!
So we have defined �Example� as a DOS Device which points to �\Device\Example�. In the �communicating with usermode� portion, we will learn more about how to use this mapping.
The next piece of code we will look at is the unload routine. This is required in order to be able to unload the device driver dynamically. This section will be a bit smaller as there is not much to explain.
VOID Example_Unload(PDRIVER_OBJECT DriverObject) { UNICODE_STRING usDosDeviceName; DbgPrint("Example_Unload Called \r\n"); RtlInitUnicodeString(&usDosDeviceName, L"\\DosDevices\\Example"); IoDeleteSymbolicLink(&usDosDeviceName); IoDeleteDevice(DriverObject->DeviceObject); }
You can do whatever you wish in your unload routine. This unload routine is very simple, it just deletes the symbolic link we created and then deletes the only device that we created which was \Device\Example.
The rest of the functions should be self explanatory as they don�t do anything. This is why I am only choosing to explain the �Write� routine. If this article is liked, I may write a second tutorial on implementing the IO Control function.
If you have used
WriteFile and
ReadFile, you know that you simply pass a buffer of data to write data to a device or read data from a device. These parameters are sent to the device in the IRP as we explained previously. There is more to the story though as there are actually three different methods that the I/O Manager will use to marshal this data before giving the IRP to the driver. That also means that how the data is marshaled is how the driver�s Read and Write functions need to interpret the data.
The three methods are �Direct I/O�, �Buffered I/O� and �Neither�.
#ifdef __USE_DIRECT__ #define IO_TYPE DO_DIRECT_IO #define USE_WRITE_FUNCTION Example_WriteDirectIO #endif #ifdef __USE_BUFFERED__ #define IO_TYPE DO_BUFFERED_IO #define USE_WRITE_FUNCTION Example_WriteBufferedIO #endif #ifndef IO_TYPE #define IO_TYPE 0 #define USE_WRITE_FUNCTION Example_WriteNeither #endif
The code was written so if you define �
__USE_DIRECT__� in the header, then
IO_TYPE is now
DO_DIRECT_IO and
USE_WRITE_FUNCTION is now
Example_WriteDirectIO. If you define �
__USE_BUFFERED__� in the header, then
IO_TYPE is now
DO_BUFFERED_IO and
USE_WRITE_FUNCTION is now
Example_WriteBufferedIO. If you don�t define
__USE_DIRECT__ or
__USE_BUFFERED__, then
IO_TYPE is defined as 0 (neither) and the write function is
Example_WriteNeither.
We will now go over each type of I/O.
The first thing I will do is simply show you the code for handling direct I/O.
NTSTATUS Example_WriteDirectIO(PDEVICE_OBJECT DeviceObject, PIRP Irp) { NTSTATUS NtStatus = STATUS_SUCCESS; PIO_STACK_LOCATION pIoStackIrp = NULL; PCHAR pWriteDataBuffer; DbgPrint("Example_WriteD = MmGetSystemAddressForMdlSafe(Irp->MdlAddress, NormalPagePriority);; }
The entry point simply provides the device object for the device for which this request is being sent for. If you recall, a single driver can create multiple devices even though we have only created one. The other parameter is as was mentioned before which is an IRP!
The first thing we do is call �
IoGetCurrentIrpStackLocation�, and this simply provides us with our
IO_STACK_LOCATION. In our example, the only parameter we need from this is the length of the buffer provided to the driver, which is at
Parameters.Write.Length.
The way buffered I/O works is that it provides you with a �
MdlAddress� which is a �Memory Descriptor List�. This is a description of the user mode addresses and how they map to physical addresses. The function we call then is �
MmGetSystemAddressForMdlSafe� and we use the
Irp->MdlAddress to do this. This operation will then give us a system virtual address which we can then use to read the memory.
The reasoning behind this is that some drivers do not always process a user mode request in the context of the thread or even the process in which it was issued. If you process a request in a different thread which is running in another process context, you would not be able to read user mode memory across process boundaries. You should know this already, as you run two applications they can�t just read/write to each other without Operating System support.
So, this simply maps the physical pages used by the user mode process into system memory. We can then use the returned address to access the buffer passed down from user mode.
This method is generally used for larger buffers since it does not require memory to be copied. The user mode buffers are locked in memory until the IRP is completed which is the downside of using direct I/O. This is the only downfall and is why it�s generally more useful for larger buffers.; PCHAR pWriteDataBuffer; DbgPrint("Example_WriteBuff = (PCHAR)Irp->AssociatedIrp.System; }
As mentioned above, the idea is to pass data down to the driver that can be accessed from any context such as another thread in another process. The other reason would be to map the memory to be non-paged so the driver can also read it at raised IRQL levels.
The reason you may need to access memory outside the current process context is that some drivers create threads in the SYSTEM process. They then defer work to this process either asynchronously or synchronously. A driver at a higher level than your driver may do this or your driver itself may do it.
The downfall of using �Buffered I/O� is that it allocates non-paged memory and performs a copy. This is now overhead in processing every read and write into the driver. This is one of the reasons this is best used on smaller buffers. The whole user mode page doesn�t need to be locked in memory as with Direct I/O, which is the plus side of this. The other problem with using this for larger buffers is that since it allocates non-paged memory, it would need to allocate a large block of sequential non-paged memory.
The first thing I will do is show you the code for handling neither Buffered nor Direct I/O.
NTSTATUS Example_WriteNeither(PDEVICE_OBJECT DeviceObject, PIRP Irp) { NTSTATUS NtStatus = STATUS_SUCCESS; PIO_STACK_LOCATION pIoStackIrp = NULL; PCHAR pWriteDataBuffer; DbgPrint("Example_WriteNeither) { /* * We need this in an exception handler or else we could trap. */ __try { ProbeForRead(Irp->UserBuffer, pIoStackIrp->Parameters.Write.Length, TYPE_ALIGNMENT(char)); pWriteDataBuffer = Irp->User); } } } __except( EXCEPTION_EXECUTE_HANDLER ) { NtStatus = GetExceptionCode(); } } return NtStatus; }
In this method, the driver accesses the user mode address directly. The I/O manager does not copy the data, it does not lock the user mode pages in memory, it simply gives the driver the user mode address buffer.
The upside of this is that no data is copied, no memory is allocated, and no pages are locked into memory. The downside of this is that you must process this request in the context of the calling thread so you will be able to access the user mode address space of the correct process. The other downside of this is that the process itself can attempt to change access to the pages, free the memory, etc., on another thread. This is why you generally want to use �
ProbeForRead� and �
ProbeForWrite� functions and surround all the code in an exception handler. There�s no guarantee that at any time the pages could be invalid, you can simply attempt to make sure they are, before you attempt to read or write. This buffer is stored at
Irp->UserBuffer.
These directives you see simply let the linker know what segment to put the code and what options to set on the pages. The �
DriverEntry�, for example, is set as �
INIT� which is a discardable page. This is because you only need that function during initialization.
Your homework is to create the Read routines for each type of I/O processing. You can use the Write routines as reference to figure out what you need to do.
A lot of tutorials will go and explain the registry, however, I have chosen not to at this time. There is a simple user mode API that you can use to load and unload the driver without having to do anything else.); DeleteService(hService); CloseServiceHandle(hService); } CloseServiceHandle(hSCManager); } return 0; }
This code will load the driver and start it. We load the driver with �
SERVICE_DEMAND_START� which means this driver must be physically started. It will not start automatically on boot, that way we can test it, and if we blue-screen, we can fix the issue without having to boot to safe mode.
This program will simply pause. You can then run the application that talks to the service, in another window. The code above should be pretty easy to understand that you need to copy the driver to C:\example.sys in order to use it. If the service fails to create, it knows it has already been created and opens it. We then start the service and pause. Once you press Enter, we stop the service, delete it from the list of services, and exit. This is very simple code and you can modify it to serve your purposes.
The following is the code that communicates to the driver.; }
This is probably simpler than you thought. If you compile the driver three times using the three different methods of I/O, the message sent down from user mode should be printed in DBGVIEW. As you notice, you simply need to open the DOS Device Name using \\.\<DosName>. You could even open \Device\<Nt Device Name> using the same method. You will then create a handle to the device and you can call
WriteFile,
ReadFile,
CloseHandle,
DeviceIoControl! If you want to experiment, simply perform actions and use DbgPrint to show what code is being executed in your driver.
This article showed a simple example of how to create a driver, install it, and access it via a simple user mode application. You may use the associated source files to change and experiment. If you wish to write drivers, it�s best to read up on many of the basic concepts of drivers, especially, some of the ones linked to in this tutorial.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/system/driverdev.aspx | crawl-002 | refinedweb | 6,069 | 61.26 |
We've seen that it's straightforward to call malloc to allocate a block of memory which can simulate an array, but with a size which we get to pick at run-time. Can we do the same sort of thing to simulate multidimensional arrays? We can, but we'll end up using pointers to pointers.
If we don't know how many columns the array will have, we'll clearly allocate memory for each row (as many columns wide as we like) by calling malloc, and each row will therefore be represented by a pointer. How will we keep track of those pointers? There are, after all, many of them, one for each row. So we want to simulate an array of pointers, but we don't know how many rows there will be, either, so we'll have to simulate that array (of pointers) with another pointer, and this will be a pointer to a pointer.
This is best illustrated with an example:
#include <stdlib.h> int **array; array = malloc(nrows * sizeof(int *)); if(array == NULL) { fprintf(stderr, "out of memory\n"); exit or return } for(i = 0; i < nrows; i++) { array[i] = malloc(ncolumns * sizeof(int)); if(array[i] == NULL) { fprintf(stderr, "out of memory\n"); exit or return } }array is a pointer-to-pointer-to-int: at the first level, it points to a block of pointers, one for each row. That first-level pointer is the first one we allocate; it has nrows elements, with each element big enough to hold a pointer-to-int, or int *. If we successfully allocate it, we then fill in the pointers (all nrows of them) with a pointer (also obtained from malloc) to ncolumns number of ints, the storage for that row of the array. If this isn't quite making sense, a picture should make everything clear:
Once we've done this, we can (just as for the one-dimensional case) use array-like syntax to access our simulated multidimensional array. If we write
array[i][j]we're asking for the i'th pointer pointed to by array, and then for the j'th int pointed to by that inner pointer. (This is a pretty nice result: although some completely different machinery, involving two levels of pointer dereferencing, is going on behind the scenes, the simulated, dynamically-allocated two-dimensional ``array'' can still be accessed just as if it were an array of arrays, i.e. with the same pair of bracketed subscripts.)
If a program uses simulated, dynamically allocated multidimensional arrays, it becomes possible to write ``heterogeneous'' functions which don't have to know (at compile time) how big the ``arrays'' are. In other words, one function can operate on ``arrays'' of various sizes and shapes. The function will look something like
func2(int **array, int nrows, int ncolumns) { }This function does accept a pointer-to-pointer-to-int, on the assumption that we'll only be calling it with simulated, dynamically allocated multidimensional arrays. (We must not call this function on arrays like the ``true'' multidimensional array a2 of the previous sections). The function also accepts the dimensions of the arrays as parameters, so that it will know how many ``rows'' and ``columns'' there are, so that it can iterate over them correctly. Here is a function which zeros out a pointer-to-pointer, two-dimensional ``array'':
void zeroit(int **array, int nrows, int ncolumns) { int i, j; for(i = 0; i < nrows; i++) { for(j = 0; j < ncolumns; j++) array[i][j] = 0; } }
Finally, when it comes time to free one of these dynamically allocated multidimensional ``arrays,'' we must remember to free each of the chunks of memory that we've allocated. (Just freeing the top-level pointer, array, wouldn't cut it; if we did, all the second-level pointers would be lost but not freed, and would waste memory.) Here's what the code might look like:
for(i = 0; i < nrows; i++) free(array[i]); free(array);
Read sequentially: prev next up top
This page by Steve Summit // Copyright 1996-1999 // mail feedback | http://c-faq.com/~scs/cclass/int/sx9b.html | CC-MAIN-2014-52 | refinedweb | 683 | 52.73 |
Hi all,
I am trying to write a program that will extract data from a web site. And out put it to a file, previously I have used piping to input/output data, but I though it was time I learnt another method, with to me seems much more effective. But where I have hit a brick wall is that I want it to loop and every time I want it to increment the url by 1. I had a stab in the dark as how to do it, but it wont work. Any one able to tell me where I am going wrong?
sorry if i am not that clear, but hopefully the code i have posted below clears every thing up.
Code:#include <iostream> #include <fstream> using namespace std; int main () { ofstream siteHTML; for (int i=0; i<100; i++) { siteHTML.open(""i, iso::in); } return 0; } | http://cboard.cprogramming.com/cplusplus-programming/91167-input-data-website.html | CC-MAIN-2015-48 | refinedweb | 149 | 87.25 |
With the richness of .NET, I want more. I want web form controls in ASP.NET that have built in validation -- no messing with all the validation controls! You should be able to just create an IntegerTextBox or a MoneyTextBox, etc. and specify that it won't accept being blank or that it has a value within a range, etc. Plus, it should return the value in the right format so I don't have to mess with it. I would even like it to change colors when there is an issue.
IntegerTextBox
MoneyTextBox
So, I have struggled to figure out how to do this so you won't have to.
I delved into the SDK documentation and discovered that any control can be a page validator if it implements the IValidator interface. Here is a simple example derived from TextBox.
IValidator
TextBox
using System;
using System.Web.UI.WebControls;
using System.Web.UI;
namespace MyValidatingControls {
public class TextBox : System.Web.UI.WebControls.TextBox, IValidator {
private bool _valid = true;
private string _errorMessage = "";
public bool IsValid {
get { return _valid; }
set { _valid = value; }
}
public string ErrorMessage {
get { return _errorMessage; }
set { _errorMessage = value; }
}
public void Validate() {
}
}
}
Of course this doesn't do anything, but the code above fulfills the basic IValidator contract (i.e. it will compile). I created two private fields to hold the state and the error message, if there is one. To ensure our validator is executed, we have to add our validator to the list of page validators for the containing page.
I did a little homework reading the SDK and it mentions that validators add themselves to the list during initialization. IValidators basically register themselves. So, we override OnInit and OnUnload to add and remove our validator from the page's Validators list.
OnInit
OnUnload
Validators
protected override void OnInit(EventArgs e) {
base.OnInit(e);
Page.Validators.Add(this);
}
protected override void OnUnload(EventArgs e) {
if (Page != null) {
Page.Validators.Remove(this);
}
base.OnUnload(e);
}
Before we can write our validator, I want to setup a few more helper items that will make things a little neater. I don't want to have to provide error messages based on each one of the validation issues. I will program those into the control, based on what type of data it should expect. Therefore, I need to provide a little more information to the control so that it can properly give error messages.
I will add a property called FriendlyName which will be used in all error messages to refer back to this control. So, if the control we are asking for has an ID of RetailPrice we make our FriendlyName be Retail Price or whatever it is labeled on the page.
FriendlyName
RetailPrice
Retail Price
private string _friendlyName = "";
public string FriendlyName {
get { return _friendlyName; }
set { _friendlyName = value; }
}
Last, before we write our validation, I want to update IsValid to change my control to a light red color if it is invalid.
IsValid
public bool IsValid {
get { return _valid; }
set {
_valid = value;
if (!_valid) {
this.BackColor = Color.LightCoral;
}
else {
this.BackColor = Color.White;
}
}
}
For our first validation, lets make it optional that the text field won't accept blanks. We need to make a property that can be set to "enable" this validation.
private bool _blankAllowed = true;
public bool AllowBlank {
get { return _blankAllowed; }
set { _blankAllowed = value; }
}
Finally, we can write the Validation function and place it on a web page.
Validation
public virtual void Validate() {
this.IsValid = true;
if (!this.AllowBlank) {
bool isBlank = (this.Text.Trim() == "");
if (isBlank) {
this.ErrorMessage =
String.Format("'{0}' cannot be blank.",
this.FriendlyName);
this.IsValid = false;
}
}
}
Now that we have a basic text field with built-in validation, we can expand on the idea and create more interesting validating text box controls.
The next simple expansion on the idea would be an IntegerTextBox. I want my IntegerTextBox to set the range of valid values, but still we can allow for blanks. So, like before, we add the needed properties.
Since we built the basic TextBox, we only need derive from it and override the Validate and add new properties and we are in business.
Validate
private int _minValue = Int32.MinValue;
private int _maxValue = Int32.MaxValue;
public int MinValue {
get { return _minValue; }
set {
_minValue = value;
if (_minValue > _maxValue) {
int swap = _minValue;
_minValue = _maxValue;
_maxValue = swap;
}
}
}
public int MaxValue {
get { return _maxValue; }
set {
_maxValue = value;
if (_minValue > _maxValue) {
int swap = _minValue;
_minValue = _maxValue;
_maxValue = swap;
}
}
}
Then, we update our Validate method and add a native value output.
public override void Validate() {
this.IsValid = true;
bool isBlank = (this.Text.Trim() == "");
if (isBlank) {
if (!AllowBlank) {
this.ErrorMessage = String.Format("'{0}' " +
"cannot be blank.", this.FriendlyName);
this.IsValid = false;
}
} else {
try {
_value = Int32.Parse(this.Text);
if (_value < this.MinValue) {
this.ErrorMessage = String.Format("'{0}' cannot " +
"be less than {1}",
this.FriendlyName, this.MinValue);
this.IsValid = false;
}
if (_value > this.MaxValue) {
this.ErrorMessage = String.Format("'{0}' " +
"cannot be more than {1}",
this.FriendlyName, this.MinValue);
this.IsValid = false;
}
} catch {
this.ErrorMessage = String.Format("'{0}' " +
"is not a valid integer.", this.FriendlyName);
this.IsValid = false;
}
}
}
public int Value {
get { return _value; }
set {
_value = value;
this.Text = _value.ToString();
}
}
That's about it! Just extend on this class and you can create a DateTextBox or a CurrencyTextBox all with built-in validation. I have included a sample usage page that shows how nice it works.
DateTextBox
CurrencyTextBox
Before we had:
<asp:TextBox
<asp:RequiredFieldValidator
<asp:RangeValidator
Now we have:
<MyControls:IntegerText
Mind you, my classes are far from finished nor does it provide the exact functionality as existing validation controls. One definite improvement would be to add client side scripting so that all validation doesn't happen on the server.
But, for someone like myself who doesn't use Visual Studio .NET, this can save a lot of typing and setting of properties.
I wanted everyone to see an example of how this is done, in case you are looking for the same kind of thing. Maybe in the future I will feel inspired enough to show you the completed set of classes I use to do this with.
I noticed in the SDK that adding the validator should occur in Init and not Load. So, I updated the text and code samples. I also added remove.
Init. | https://www.codeproject.com/Articles/5137/Self-Validating-ASP-NET-Text-Box?msg=806146 | CC-MAIN-2017-26 | refinedweb | 1,046 | 57.98 |
Namespaces are used in C# to organize and provide a level of separation of codes. They can be considered as a container which consists of other namespaces, classes, etc.
A namespace can have following types as its members:
- Namespaces (Nested Namespace)
- Classes
- Interfaces
- Structures
- Delegates
We will discuss about these topics in later tutorials. For now we will stick with classes and namespaces.
Namespaces are not mandatory in a C# program, but they do play an important role in writing cleaner codes and managing larger projects.
Let's understand the concept of namespace with a real life scenario. We have a large number of files and folders in our computer. Imagine how difficult it would be to manage them if they are placed in a single directory. This is why we put related files and folders in a separate directory. This helps us to manage our data properly.
The concept of namespace is similar in C#. It helps us to organize different members by putting related members in the same namespace.
Namespace also solves the problem of naming conflict. Two or more classes when put into different namespaces can have same name.
Defining Namespace in C#
We can define a namespace in C# using the namespace keyword as:
namespace Namespace-Name { //Body of namespace }
For example:
namespace MyNamespace { class MyClass { public void MyMethod() { System.Console.WriteLine("Creating my namespace"); } } }
In the above example, a namespace
MyNamespace is created. It consists of a class
MyClass as its member.
MyMethod is a method of class
MyClass.
Accessing Members of Namespace in C#
The members of a namespace can be accessed using the
dot(.) operator. The syntax for accessing the member of namespace is,
Namespace-Name.Member-Name
For example, if we need to create an object of MyClass, it can be done as,
MyNamespace.MyClass myClass = new MyNamespace.MyClass();
We will discuss about creating objects in later tutorials. For now just focus on(); } } }
When we run the program, the output will be:
Creating my namespace
In the above program, we have created our own namespace
MyNamespace and accessed its members from
Main() method inside
MyClass. As said earlier, the
dot (.) operator is used to access the member of namespace.
In the
Main() method,
myMethod() method is called using the
dot (.) operator.
Using a Namespace in C# [The using Keyword]
A namespace can be included in a program using the using keyword. The syntax is,
using Namespace-Name;
For example,
using System;
The advantage of this approach is we don't have to specify the fully qualified name of the members of that namespace every time we are accessing it.
Once the line
using System;
is included at the top of the program. We can write
Console.WriteLine("Hello World!");
Instead of the fully qualified name i.e.
System.Console.WriteLine("Hello World!");
Nested Namespace in C#
A namespace can contain another namespace. It is called nested namespace. The nested namespace and its members can also be accessed using the
dot (.) operator.
The syntax for creating nested namespace is as follows:(); } } }
When we run the program, the output will be:
Nested Namespace Example
This example illustrates how nested namespace can be implemented in C#.
Here, we now have an extra namespace inside
MyNamespace called
Nested. So, instead of using
MyNamespace.SampleClass.myMethod(), we have to use
MyNamespace.Nested.SampleClass.myMethod(). | https://cdn.programiz.com/csharp-programming/namespaces | CC-MAIN-2020-40 | refinedweb | 557 | 57.57 |
Hi
I'm trying to get a picker working for a custom class. My ItemsSource binding works fine but when I select an item the breakpoint I have in the property setter is not hit.
I looked at the MonkeyApp sample and copied some code from that (I can't run the sample directly as it needs Windows 10 and I'm on W7 using VS Community 2017) but I'm having the same problem with the sample code.
I implemented another picker to select from a list of strings where SelectedItem is bound to a public string property, for this picker the property setter breakpoint is hit.
I read something that suggested older versions of the Picker/Xamarin forms might not work so I used Nuget to install Xamarin.Forms 3.1.0.583944. Still doesn't work.
xaml:
<Picker Title="string list" ItemsSource="{Binding StringList}" SelectedItem="{Binding SelectedString}"/> <Label Text="{Binding SelectedString}"/> <Picker Title="Select a monkey" ItemsSource="{Binding Monkeys}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding SelectedMonkey, Mode=TwoWay}" /> <Label Text="{Binding SelectedMonkey.Location}" FontAttributes="Italic" HorizontalOptions="Center" />
viewmodel:
string selectedString; public string SelectedString { get { return selectedString; } set { selectedString = value; OnPropertyChanged(); } } Monkey selectedMonkey; public Monkey SelectedMonkey { get { return selectedMonkey; } set { if (selectedMonkey != value) { selectedMonkey = value; OnPropertyChanged(); } } }
ViewModelBase class:
public class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } }
Can anyone tell me where I am going wrong?
Thanks in advance.
Answers
How do you construct your viewmodel and set the
StringList,
Monkeysproperty? Can you share your sample to help us reproduce your issue? MonkeyApp works properly on my side.
Hi LandLu. Thanks for replying and sorry for the delay in responding - this is a hobby project and I haven't had any free time to spend on it for a while.
I've managed to get the MonkeyApp demo that I downloaded running in my environment now (I got rid of the IOS and UWP projects and just kept the Droid one) and it has exactly the same problem, the SelectedMonkey property setter is not hit and therefore the labels bound to it don't update. I've modified it slightly to add a second Picker of type string with a corresponding label for its SelectedString and that one is working fine.
Here's a cut and paste of relevant bits of code. I will try to upload a .zip of the whole solution as well.
MonkeysPage.xaml
code behind of MonkeysPage that constructs the view model:
MonkeysPageViewModel:
MonkeyData class (not posted all of it - you get the idea and I haven't changed it so should be same as the demo)
Monkey class:
ViewModelBase class:
I think the problem is something in my environment so I've also changed the Droid project to compile using Android 8.1 (it was 7.1 previously) and updated all Nuget packages which hasn't made any difference. I'm now using Xamarin.Forms 3.1.0.697729
Hi LandLu, sorry for the delay in replying. This is a hobby project and I haven't had any free time lately.
I've got the MonkeyApp demo running in my environment now (got rid of the UWC and IOS projects and just kept the Droid one) and it's got exactly the same problem. I've modified it to add a string property and label and this one works fine.
Here's the MonkeysPage. xaml (I've had to chop out the xml namespaces because this forum won't let me post links:
and its code behind:
and the MonkeysPageViewModel:
I updated the Droid project to use Android 8.1 (was previously 7.1) which allowed me to update the Nuget packages. So I am now using Xamarin.Forms 3.1.0.697729. | https://forums.xamarin.com/discussion/128766/picker-selecteditem-property-setter-not-being-hit-for-custom-class-works-for-strings | CC-MAIN-2019-22 | refinedweb | 637 | 53.61 |
Data mining Heroes of the Storm replays
As I mentioned in a previous post, I’ve recently been working on data mining and analyzing Heroes of the Storm replay files. I’ve got some posts coming in the next week or two covering some of my initial analysis, but I thought I’d take a few minutes and write about the process of data mining the files themselves, in case anyone else is interested.
First, you’ll need to go and get a hold of Blizzard’s heroprotocol library, which is written in Python. They update this library every time they release a new build of Heroes of the Storm. It has some basic information about what kind of information is contained in the replay files, but one thing you’ll notice, once you start digging into some replay files, is that the documentation is quite sparse.
That’s unfortunate, because there’s a ton of information in these replay files. They contain information such as the interface settings for every player, which hero they chose, what battleground the game was played on, in which game mode, and so on. They also have event information such as when minions or heroes are killed, when heroes selected a new talent, and coordinate information of just about anything that happened in the game. Since the documentation didn’t give many details at all about what was in the files, what I ended up doing was opening up some replays and just digging around for a while. I was trying to see what kinds of things were in there, and how they fit together.
So, let’s walk through an example. To get started, what you need to do is open a replay file and turn it into a usable Python object. Replays in Heroes are in the mpq format, so we need to use the mpq library (included with heroprotocol).
from mpq import MPQArchive mpq = MPQArchive('your_replay.StormReplay')
You’re still going to need the heroprotocol library itself to get something meaningful from the replay. You’ll want to use the protocol with the same build number as the replay you’re examining (e.g. ‘protocol47133’ if your replay is from build 47133). If these don’t match, sometimes the protocol won’t be able to read the replay properly. It appears that in most cases you can use just about any protocol to read the replay’s header information (which contains the replay’s build number), so we’ll use that to help us load the correct protocol without having to know what build our replay was from beforehand. At the time of this writing, the latest Heroes build is 47133, so we’re just going to use that.
from heroprotocol import protocol47133 as protocol
Let’s get the replay’s header information and the build number.
header = protocol.decode_replay_header(mpq.header['user_data_header']['content']) build_number = header['m_version']['m_baseBuild']
Now make sure that you’re loading in the correct protocol to read the rest of the replay data.
from importlib import import_module module_name = 'heroprotocol.protocol{}'.format(build_number) protocol = import_module(module_name)
If we wanted to know who the players were and which hero they selected, we can now do that as follows:
details = protocol.decode_replay_details(mpq.read_file('replay.details')) player_list = details['m_playerList'] for player in player_list: name = player['m_name'] hero = player['m_hero'] result = player['m_result'] # this is 1 (victory) or 0 (defeat) ...
What if we wanted to get a look at information on units and statistics? A lot of that is stored away in what heroprotocol calls tracker events. They can be acquired in a similar way to the details we grabbed above:
tracker_events = protocol.decode_replay_tracker_events( mpq.read_file('replay.tracker.events') )
This returns a generator object, so you can loop through it and take a look at the different kinds of data found in there. One of the things I was interested in researching was the influence that hero talent choices have on the game. We can get that information from the ‘EndOfGameTalentChoices’ event, which is a type of tracker event.
for tracker_event in tracker_events: if tracker_event['_event'] == 'NNet.Replay.Tracker.SStatGameEvent': if tracker_event['m_eventName'] == 'EndOfGameTalentChoices': talents = tracker_event['m_stringData'] ...
Of course, you’ll likely still have to process the result in some way, depending on what your end goal is. One issue that I ran into with a different type of event dealing with talent selection is that I had to cross-reference ID numbers with the player IDs (obtained in one of the earlier steps above), but in some replays these IDs didn’t always match up. I’m still not sure why this is the case, but I suspect it has something to do with the presence of Observers in the replays I was parsing.
Anyway, this should give you a good idea of where to start with Heroes replay files! My first pass at a replay parser is up on Github now if you’d like to check it out. | http://tommyhall.ca/data-mining-heroes-of-the-storm-replays/ | CC-MAIN-2019-39 | refinedweb | 830 | 59.43 |
Created on 2017-01-08 11:13 by serhiy.storchaka, last changed 2018-05-11 03:02 by mbussonn. This issue is now closed.
Some deprecated ElementTree features are deprecated only in the documentation or in Python implementation (that is virtually the same since C implementation is default). Proposed patch adds missed deprecations is code. It also makes warnings be ignored only in tests where they are expected. This is possible since converting doctests to unittests some time ago.
Added deprecations:
* Element.getchildren() and Element.getiterator() methods. They were deprecated in the documentation and in Python implementation in 2.7 and 3.2.
* The xml.etree.cElementTree module. Deprecated in the documentation in 3.3.
* The html argument of XMLParser. Deprecated in the documentation in 3.4.
Ned, is it appropriate to commit the patch (or its part) in 3.6? The discrepancy between Python and C implementation can be considered as a bug. What are your thoughts?
Isn’t cElementTree useful and recommended in 2.7? It would be awkward to deprecate it in Python 3. But I guess the other cases should be okay to deprecate in 3.7.
Yes, I have a doubt about this too.
Perhaps it can be just removed. The idiomatic code in Python 2 is:
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
I'm ok with the deprecations.
Regarding the cElementTree module, this is a bit problematic. The idiomatic import has lost its use in Py2.5 when ET and cET were added to the stdlib, so code that was written for Py2.5 or later (e.g. because it uses generators) might no longer have that cascade. On the other hand, issuing a warning for the module would also hit this import cascade, even though the code would work just fine without cElementTree. One argument speaks for deprecation, the other for removal.
However, cElementTree is redundant now, so it should be removed eventually. And since that removal would break some code anyway, I'd be ok with just removing it without prior import warnings. People can then decide whether they want to fix their code by adding the well-known import cascade (and not get annoying warnings for it) or by switching entirely to plain ET and not looking back.
New changeset 762ec97ea68a1126b8855996c61fa8239dc9fff7 by Serhiy Storchaka in branch 'master':
bpo-29204: Emit warnings for already deprecated ElementTree features. (#773)
The deprecation of the cElementTree module was excluded. | https://bugs.python.org/issue29204 | CC-MAIN-2020-40 | refinedweb | 413 | 60.92 |
I've solved the problem, thank you very much for the respons! :)
I've solved the problem, thank you very much for the respons! :)
Hi! I'm having some problems with a program i'm writing, the problem i'm facing is that i've created a few buttons using swing. But when I press the buttons nothing happens except for one button. For...
@copeg - Thanks! that worked like a charm! =)
Ah thanks helloworld922! That solved my problem! =)
Now another question, if I wish to search for a title in the arraylist, is there a simple way to do this?
Rewrote the comparable code to:
public int compareTo(Book objekt) {
if (objekt.getTitle().compareTo(this.getTitle()) < 0) {
return 0;
} else if...
Ah yes this is confusing =/
But since I do use the Comparable class with:
public class Book implements Comparable<Book>
I can't see the problem by using
List<Book> temp = cob.remoteSort();...
It is correct, however I see that the error is that i only pass the List to be sorted and not what method to be used with comparable. So it should look something like this:
Pseudo-code:
...
Hi I'm having problems with java and the collections.sort method. I can't figure out how to sort an arraylist using the compareTo and Comparable interface. I've created the compareTo method and so... | http://www.javaprogrammingforums.com/search.php?s=02777deae04ac56e54f8aa21890931c4&searchid=1075714 | CC-MAIN-2014-41 | refinedweb | 227 | 66.84 |
Event Processor Framework
Project description
EvProc is a framework for building complex event processors. There are many similar frameworks available, so why EvProc? EvProc provides a few advantages. First, a @want() decorator is available to pre-filter events, as opposed to registering an event handler on specific events. (Filtering works primarily with an event name, allowing flexibility, but it is also possible to register arbitrary filter functions, which can evaluate an event to determine whether to call the event handler.) A second advantage is the ability to register event handlers using the “entrypoint” support of setuptools, allowing extensibility. Finally, EvProc provides limited inter-handler communication, using the proc property of Event instances, and backs this up with the ability to specify ordering among event handlers using requirements.
Defining Events
An event in EvProc is an instance of a subclass of evproc.Event. The Event class is an abstract class; subclasses must implement a name property, the contents of which will be a unique string naming the event. The constructor takes a single optional argument, a ctxt argument, which may be used to pass a context in to event handlers. The constructor may, of course, be extended as required to provide any necessary information about the event, such as a specific resource that the event occurred on.
The Event class also provides a special proc property. This property may be used by event handlers to store data for use by other event handlers, by setting attributes. To minimize the possibility of two unrelated handlers attempting to manipulate the same attribute, the proc property is namespaced; that is, attributes on proc may not be set, but attributes on those attributes may.
As an example of the use of the proc property, consider two event handlers that wish to communicate with each other. Assume that these handlers interact to perform testing; perhaps one handler selects test parameters, and the second handler actually performs the test (e.g., there may be multiple tests to perform). The first handler could set, say, proc.tests.args and proc.tests.kwargs, and the second handler would then retrieve the values it needed.
Event Handlers
An event handler is simply a function that will be called with two arguments; the first argument will be an instance of evproc.Processor (described below), and the second will be an instance of evproc.Event (described above). The event handler may perform any code necessary to process the event. Each event handler must have a unique name; by default, the name will be the same as the function name, but this may be overridden when registering the event handler. Event handlers may also be loaded from setuptools entrypoints; in this case, the name used is the entrypoint name.
There are three optional decorators that may be used on an event handler function. The first is the @evproc.want() decorator, which may be called with one or more event names; the handler function will only be called if the event being handled matches one of these event names. The decorator may also be passed one or more filter functions; in this case, the event handler will only be called if all of the filter functions return True. If event names are also passed, then the event must also match one of those names. The @want() decorator may be used multiple times to specify other sets of filters; the event need only match one filter specified by @want(). For instance, consider this example:
@evproc.want('ev1', 'ev2') @evproc.want('ev3', lambda ev: ev.resource.name == 'resource') def handler(proc, ev): ...
This handler will be called for all events with the names “ev1” and “ev2”, but will only be called for the event “ev3” if ev.resource.name contains the value "resource".
Event handlers are able to interact with each other, as mentioned above. To do this, it is necessary to enforce certain ordering guarantees on the event handler. This is controlled by the @evproc.requires() and @evproc.required_by() decorators. These decorators take the names of one or more event handlers (names are set at registration time, as mentioned above). The @requires() decorator is used to indicate that the specified functions must run before the decorated function, while the @required_by() decorator is used to indicate that the specified function require the decorated function to be run first. In both cases, the @want() decorators of the functions must be compatible.
The @requires() and @required_by() decorators are used to define a dependency graph, which is then topologically sorted to ensure that the handler functions are called in the correct order. As an example, consider the split test functions mentioned above. We could declare the functions like so:
def test_prepare(proc, ev): ... ev.tests.args = args ev.tests.kwargs = kwargs @evproc.requires('test_prepare') def test_run(proc, ev): args = ev.tests.args kwargs = ev.tests.kwargs intermediate = getattr(ev.tests, 'auxiliary', []) ... @evproc.required_by('test_run') @evproc.requires('test_prepare') def test_auxiliary(proc, ev): ... ev.tests.auxiliary = results
In this example, the test_prepare() handler function would be called first, followed by the test_auxiliary() handler function, and finally the test_run() handler function would be called.
An event handler may optionally return a list of events, which will be processed in order.
The Event Processor
The evproc.Processor class is responsible for processing events. To use EvProc, instantiate a Processor instance and use its register() or load_from() methods to declare event handler functions. Then, simply pass Event instances to the process() method to invoke the event processors in the correct order.
The Processor.register() method may be used to register individual event handler functions. By default, the function’s declared name (func.__name__) is used as the handler name, but this may be overridden by passing the optional name parameter to register().
To load event handlers from a setuptools entrypoint, use the Processor.load_from() method. This method takes, as its sole argument, the entrypoint group name; as an example, if one installed application has a setup.py containing:
entry_points={ 'app.handlers': [ 'test_prepare = app:test_prepare', 'test_run = app.test_run', ], }
And if a second installed application has the following in its setup.py:
entry_points={ 'app.handlers': [ 'test_auxiliary = otherapp:test_auxiliary', ], }
Then all three handler functions could be loaded into the Processor instance proc with the following call:
proc.load_from('app.handlers')
The Processor.process() method may be called as many times as necessary. In fact, most event-driven applications consist of a loop which constructs Event instances, then passes them to the Processor.process() method. A full application could look something like the following:
def main(): proc = evproc.Processor() proc.load_from('app.handlers') while True: # Construct event objects ... ev = AppEvent(...) # Process the event proc.process(ev)
Processor.process() returns None unless an event processor raises a evproc.StopProcessing exception initialized with a retval, in which case it returns the exception’s retval.
Stop Processing
It may be necessary for one event processor to stop all event processing. This could, for instance, be used by a processor that performs an authorization check if the event fails that check. To allow this, an event processor may raise the evproc.StopProcessing exception. When an event processor raises a StopProcessing exception, no additional event processors will be called for that event. If the StopProcessing exception is raised without a retval, yet-unprocessed events returned by prior event processors will still be processed. If the StopProcessing exception is raised with a retval (even if None), Processor.process() will immediately return the exception’s retval, and yet-unprocessed events returned by prior event processors will not be processed.
Conclusion
EvProc provides an easy to extend event processing framework, capable of not only calling event handler functions, but of ensuring certain ordering constraints and limited inter-handler communication. The ability to use setuptools entrypoints allows new event handlers to be inserted into the event processing loop easily without having to modify the original application, and the ordering constraints can allow such inserted event handlers to interact with the existing ones just as easily.
Project details
Release history Release notifications
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/evproc/ | CC-MAIN-2019-04 | refinedweb | 1,355 | 56.86 |
A good friend of mine recently got a job as a technical reviewer - I guess he'll be reviewing code other people write for static analysis. I'm excited, because he's been a longtime Java user, and the job works with C#. So this post goes out to him, as well as all the other people looking to learn the basics of C#.
When I came to C#, I came primarily from a JavaScript background, with about a semester of University Java on top of it. By the time I got to C#, I had already broken down the basics of strong typing (that was a painful exercise, but now I can't go back), and had learned some object-oriented fundamentals. But, we hadn't worked much at all with the AWT or Swing in my intro to Java course, and what little we had exposed only little things - registering an event listener to listen to a button here, making sure that I implemented this interface there - etc. It seemed straightforward enough, but from what little I had done in dabbling with Visual Basic over the years (mostly I never comprehended what I was looking at), it seemed like an awkward way of dealing with user input.
I saw that C# had events, very similar to the Visual Basic events that I was familiar with - and actually, somewhat like JavaScript's DOM events. I understood that in order to capture a button's Click event, I had to double-click on the button in the designer and then edit the body of a method with a cryptic name and signature, such as btnSave_Click(object sender, EventArgs e). It took me a solid four months to wrap my head around the concept of events - how they functioned, how to create and fire them, and how to handle them. Since then, I've also had the privilege of learning some of the best practices for using them. So here we go!
This might seem like a blinding flash of the obvious, but it wasn't to me. An event is a way for one object to inform one or more objects (note I did not say "other" in there - it could inform itself) of a state transition, or an external or internal stimulus.
Only objects or types (classes or structs, specifically) can own an event, and only the owning type (or object) can fire the event. Class-owned events must be declared with the static modifier. We'll get to the semantics of declaring and invoking an event in a short while.
Delegates are one of the five main types of objects in the CLR (classes, structures, enums, delegates, and events). They provide a type-safe indicator of method pointers; consider the following C API declaration:
typedef VOID (WINAPI * DeferredProcedureCallProc)(LPARAM lParam);
In C, that represents a callback type called DeferredProcedureCallProc with a single parameter of type LPARAM, and has no return value. However, C does not have a mechanism for enforcing type safety with this type of procedure; C#, however, does: it has delegates. Delegates are declared with the following syntax:
[access-modifier] delegate return-type identifier([parameter-list]);
Accounting for the C# type conversion of LPARAM to IntPtr, the above C callback can thusly be translated to:
1: public delegate void DeferredProcedureCallback(IntPtr lParam);
That means that an object of type DeferredProcedureCallback can be instantiated, referencing any method that has no return value and accepts an IntPtr as a parameter.
When a delegate is instantiated, it encapsulates two specific pieces of information: the method it reference, and the object it references. Consider this example:
1: public class Foo
2: {
3: public Foo()
4: {
5: DeferredProcedureCallback dpc = new DeferredProcedureCallback(this.Bar);
6: }
7: public void Bar(IntPtr info)
8: {
9: }
10: }
Note that the Bar function is referenced without parameters. The dpc variable also holds a reference to the Foo object it is accessing - so that only that specific instance of Foo will be notified.
Returning to the concept of events - events are semantically declared within a class in the following way:
[access-modifier] [static | ( abstract | virtual | override | sealed )] event delegate-type identifier;
An example of this would be:
1: public class Button
3: public event EventHandler Click;
4: }
In this, example, an event is declared that utilized the System.EventHandler delegate.
One of the neat things about events is that, at compile-time, delegates are all derived from System.MulticastDelegate. A multicast signal is one which targets specific objects, based on the fact that these objects registered to be signaled (as opposed to a broadcast signal, which doesn't require pre-registration). Any number of delegates can be registered with a given event, or unregistered. To register, we utilize the += operator (and to unregister, we use the -= operator) to indicate the inclusion or removal of a given event handler.
Here is a sample registration of an event handler using a Button control on a Windows Form:
1: public class MyForm : System.Windows.Forms.Form
3: private Button myButton;
4:
5: public MyForm()
6: {
7: myButton = new Button();
8: Controls.Add(myButton);
9: myButton.Click += new EventHandler(this.myButton_Click);
10: }
11:
12: private void myButton_Click(object sender, EventArgs e)
13: {
14: MessageBox.Show("I was clicked!");
15: }
16: }
In this example, a new Button was created on the form, and its Click event is handled by the myButton_Click method of this object.
I will get into why the following pattern is used in the next section, but here's the code to use for signaling the Click event:
1: public class Button : Control
4: protected virtual void OnClick(EventArgs e)
5: {
6: if (Click != null)
7: Click(this, e);
8: }
9: }
All you would need to do is call OnClick directly, and the Click event will be signaled.
Note that you should check the event as to whether it's null (for nullillity?) because otherwise a NullReferenceException will be thrown by the runtime. Finally, note that the Click event is called with the same signature as the delegate of the event.
The .NET Framework Best Practices and Guidelines indicate that you should utilize certain patterns. The above sample illustrates the pattern of implementation that should be utilized: an event, and a calling virtual method with "On" prepended to the identifier. The idea is that derived classes can override the default implementation and invoke the parent class's implementation to invoke the event. For example, consider an ImageButton class:
1: public class ImageButton : Button
3: protected override void OnClick(EventArgs e)
5: base.OnClick(e);
6:
7: this.ImageUrl = GetPressedStateImageUrl();
So, rather than needing to handle an event, the code is able to capture the Click event without specifically using the Click event.
Other best practices can be found in Event Usage Guidelines in the MSDN Library.
Finally, as an aside, just like properties, events can define event accessor blocks. By default, the compiler will create these blocks; it might be worthwhile to look into these for certain specific implementations. For more information, refer to the C# Language Specification, 10.7.2 - Event accessors.
I hope this overview was worthwhile! Events can be exceptionally useful and a new way of looking at cross-object communication; it is no longer necessary to create an entire interface and class to handle an event. The compiler can enforce type safety, and signaling multiple objects is incredibly easy. Use them! | http://geekswithblogs.net/robp/archive/2007/10/16/A-C-Primer---Understanding-Events.aspx | CC-MAIN-2019-43 | refinedweb | 1,236 | 50.06 |
page for the book should read:
For the Color property to work properly in this code, the System.Drawing namespace needs to be referenced
in the Imports section.
AUTHOR NOTE: The reader is correct in stating the need to import the System.Drawing
namespace when using the color constants like Color.White. Unfortunately,
this section demonstrates three solutions but the full code is only shown
for the first solution and that solution does not need the imports
statement. This can be a little confusing. While the book text and code is
correct, it probably would have been good to add a tip indicating the need
to import the System.Drawing namespace for solutions 2 and 3.
There are several errors in the chart listed below:
D ShortDatePattern
should be:
d ShortDatePattern
F Full date and time (long date and short time)
should be:
f Full date and time (long date and short time)
G General (short date and short time)
Should be:
g General (short date and short time)
T ShortTimePattern
should be:
t ShortTimePattern
U UniversalSortableDateTimePattern using the format for universal time display
should be:
u UniversalSortableDateTimePattern using the format for universal time display
The method in Example 1-55 is called Page_Load, not setupForm as in the text.
© 2017, 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://www.oreilly.com/catalog/errata.csp?isbn=9780596003784 | CC-MAIN-2017-09 | refinedweb | 237 | 60.65 |
Created on 2010-10-16 22:41 by Michael.Olson, last changed 2015-11-19 02:59 by python-dev. This issue is now closed.
In an application with an entry point of __main__.py, multiprocessing.Pool throws the following:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "D:\Dev\Python27\lib\multiprocessing\forking.py", line 346, in main
prepare(preparation_data)
File "D:\Dev\Python27\lib\multiprocessing\forking.py", line 454, in prepare
assert main_name not in sys.modules, main_name
AssertionError: __main__
These messages repeat as long as the application is running.
Demonstration Code, must be in file named __main__.py:
--------------------
import multiprocessing
import time
if __name__ == '__main__':
pool = multiprocessing.Pool()
time.sleep(2)
--------------------
I wrapped the offending assertion in a if main_name != '__main__'. I considered not checking the module_name against built-in modules but that seemed likely to be the sort of thing being guarded against, so I left it at an exception for __main__.
Ran a few trivial testing using Pool and Process and it seems to work fine.
Is this on Windows? Does it work for you now?
Sorry about that, yes, this is on Windows XP and 7, 32 bit.
And with the if statement it seems to work fine.
v/r
-- Michael Olson
Ummm, I think I've been unclear on where I was making changes, I changed lib\multiprocessing\forking.py to fix the issue.
Patch attached.
As a note, I didn't attach a patch at first because I was fairly sure I was kludging it into submission, but at least this makes it clear as to what I did.
v/r
-- Michael Olson
The fix from #10845 should be backported to Python 2.7 (bypassing the assertion isn't enough - you want to skip re-executing __main__ entirely)
I applied the patch from #10845 to 2.7.6 and it worked well for me.
Please fix this. Scripts with multiprocessing bundled as wheels are broken with Python 2.7 on Windows:
Marc's reference to pip meant I noticed something that I had missed previously - that this issue is referring specifically to the use of setuptools/pip entry points, not to the -m switch.
Entry points shouldn't be hitting this if they're importing the module containing the entry point normally - #10845 specifically related to invoking multiprocessing from a module run directly with the -m switch, which was worked around in 3.2 and 3.3, and then finally fixed properly in 3.4 by the implementation of #19946
So if there's an incompatibility between multiprocessing and entry points, it would be preferable to fix it in pip/setuptools, as that will reach many more installations than just fixing multiprocessing to better tolerate that situation.
Please see my latest comments to.
tl;dr It is related to the -m switch as pip's wheel launcher does
PYTHONPATH=script.exe python -m __main__
Thanks for the investigation Marc.
I'd been hesitant to backport the mitigation patch in #10845 to 2.7.x, (as it *does* represent a behavioural change), but if that code path is currently hitting an assert statement anyway, it seems reasonable to make the change for 2.7.11+
New changeset 5d88c1d413b9 by Nick Coghlan in branch '2.7':
Close #10128: don't rerun __main__.py in multiprocessing | https://bugs.python.org/issue10128 | CC-MAIN-2019-39 | refinedweb | 555 | 66.84 |
I have recently started to learn java and wanted skills to test my skills so far. I started making a small text-based game and have hit an early roadblock.
I have two classes so far, one for the menu system and the core processes, another for the character's stats and information.
While testing the two classes interacting, I was able to successfully print the stats, call it in an if by setting two variables equal (operation and stats).
The problem came when I wanted to use scanner to allow the user to type "stats" and show the stats. I have tried both if and while with the variables equal, so I know that the problem has something to do with scanner.
Here are the classes.
GameD01.java
import java.util.Scanner; public class GameD01 { public static void main(String args[]){ Scanner input = new Scanner(System.in); characterStats charStats = new characterStats(); String operation, stats = null; System.out.println("What would you like to see?"); operation = input.nextLine(); if(stats){ System.out.println("Your stats are: "); System.out.println("HP: "+ charStats.health); System.out.println("MP: "+ charStats.magic); System.out.println("Str: "+ charStats.strength); System.out.println("Def: "+ charStats.defense); operation = null; }else{ System.out.println("Please work..."); } } }
characterStats.java
public class characterStats { public int health, magic, strength, defense; { health = 100; magic = 20; strength = 50; defense = 50; } } | http://www.javaprogrammingforums.com/whats-wrong-my-code/9756-my-string-not-activating-my-if-statment.html | CC-MAIN-2015-22 | refinedweb | 227 | 50.12 |
Opened 9 years ago
Closed 3 years ago
Last modified 11 months ago
#9893 closed Bug (fixed)
Filename + path length greater than 100 truncated on database insertion in Core.Storage
Description
In core.files.storage, the storage object doesn't check the length of filename + upload_to to ensure that it's less than 100 characters. If the path length is greater than 100, it is truncated to 100 characters when inserted into the database. With filename collision mitigation appending an '_' to the end of the filename, popular filenames can easily reach lengths that exceed the size of the.
To reproduce the issue, try uploading a file/image with a length over 100 characters.
Solution:
Here's some quick hackery that attempts truncate the filename. Note that it assumes the upload_to length to be less than 30 characters long. Also note that this should probably be divided up into a couple of different methods and this is more to get the ball rolling than anything.
def get_available_name(self, name): """ Returns a filename that's free on the target storage system, and available for new content to be written to. """ # If the filename already exists, append an incrementing integer # to the file until the filename doesn't exist. dir_name, file_name = os.path.split(name) flength = len(file_name) if flength > 70: # If filenameis longer than 70, truncate filename offset = flength - (flength % 40 + 20) # modulus of file name + 20 to prevent file type truncation file_name = file_name[offset:] name = os.path.join(dir_name, file_name) if self.exists(name): # filename exists, get dot index try: dot_index = file_name.rindex('.') except ValueError: # filename has no dot dot_index = -1 inc = 0 # Set incrementer to zero while self.exists(name): inc += 1 if dot_index == -1: # If no dot, append to end tname = file_name + str(inc) else: tname = file_name[:dot_index] + str(inc) + file_name[dot_index:] name = os.path.join(dir_name, tname) return name
Attachments (1)
Change History (48)
comment:1 Changed 9 years ago by
comment:2 Changed 9 years ago by
Milestone post-1.0 deleted
comment:3 Changed 9 years ago by
comment:4 Changed 9 years ago by
I ran into this issue when using the django-attachments re-usable app, but in my case the file name wasn't truncated – an exception was thrown instead. I'm storing files in subdirectories named after the user who uploads (max 30 characters), and apparently one of my users was uploading a file with a really long name so
len("attachments/<username>/<filename.ext>") exceeded 100 characters.
I wonder why an exception happened instead of truncation. I'm using PostgreSQL, maybe that's significant?
Here's the relevant part of the traceback:
File "attachments/attachments/models.py", line 137, in save super(Attachment, self).save(force_insert, force_update) File "django/db/models/base.py", line 408, in save self.save_base(force_insert=force_insert, force_update=force_update) File "django/db/models/base.py", line 484, in save_base result = manager._insert(values, return_id=update_pk) File "django/db/models/manager.py", line 177, in _insert return insert_query(self.model, values, **kwargs) File "django/db/models/query.py", line 1035, in insert_query return query.execute_sql(return_id) File "django/db/models/sql/subqueries.py", line 320, in execute_sql cursor = super(InsertQuery, self).execute_sql(None) File "django/db/models/sql/query.py", line 2290, in execute_sql cursor.execute(sql, params) DataError: value too long for type character varying(100)
comment:5 Changed 9 years ago by
Issues to consider:
Smart truncation can't be done in the storage object
since it doesn't know about the
max_length= of the
FileField.
The maximum length can be set to a different value than 100 in the model.
One possibility is to extend the signature of
Storage.get_valid_name() and
.get_available_name() to accept
a maximum file name length argument, but I assume that's sub-optimal.
Truncation should avoid collisions with existing file names.
Simply shortening the file name isn't sufficient,
but something similar to what VFAT did with its
FILENA~1.EXT
8.3-character filename representations should be used.
Storage.exists() can be called to check for collisions.
The
upload_to= kwarg of
FileField can be either
- a string specifying the target directory, or
- a callable which replaces
FileField.generate_filenameand returns the path to the file to be saved.
In case of a callable, do we leave length checking as responsibility of the callable,
or should we prepare to truncate the generated path?
Truncation could be done in
FileField.generate_filename(),
but how to ensure the generated filename is still valid for the storage?
This is an issue if a numbering scheme must be used to avoid file name collisions.
What if the directory is already too long without the actual file name?
This shouldn't be an issue when
upload_to= is a string,
but a callable might generate a long path if not coded carefully.
comment:6 follow-ups: 7 17 Changed 9 years ago by
What are the drawbacks to just making a FileField use Text instead of varchar in the database? It seems like a pretty simple solution that would completely resolve the issue.
comment:7 Changed 9 years ago by
comment:8 Changed 9 years ago by
I think ultimately akaihola's idea of modifying the
get_valid_name and
get_available_name to accept a max length is the right way to go. Using a text field is a bad idea for a bunch of reason -- speed, storage size, compatibility with Oracle -- but any hardcoded length could possibly be too short.
At this point past feature-freeze, though, changing that signature could cause too much heartache. I'm going to punt this to 1.2; for now, it's a simple workaround: use
FileField(max_length=SOMETHING_BIGGER).
comment:9 Changed 9 years ago by
comment:10 Changed 9 years ago by
comment:11 Changed 8 years ago by
comment:12 Changed 8 years ago by
comment:13 Changed 8 years ago by
comment:14 Changed 8 years ago by
Jacob,
To elaborate the changes needed:
- the following methods need a
max_length=100kwarg:
Storage.get_valid_name
Storage.get_available_name
FileSystemStorage._save
Storage.save
FileField.get_filenameneeds to call
Storage.get_valid_namewith the field's
max_length
FileField.saveneeds to call
self.storage.savewith the field's
max_length
Storage.saveneeds to pass that value to
self._save
FileSystemStorage._saveneeds to pass it on to
self.get_available_name
In addition, shouldn't a smart filename truncation / collision prevention mechanism be put in place anyway? As pointed out in the ticket description, appending underscores will cause collisions if truncation happens.
I propose appending an underscore and a counter integer to the first part of a dot-separated filename. The first part should be truncated before appending to ensure that no truncation will happen at the end. Examples (with a max_length of 36):
/long/path/long-file-name.ext1.ext2(35 characters)
/long/path/long-file-nam_1.ext1.ext2(36 characters; first part truncated)
/long/path/long-file-nam_2.ext1.ext2(36 chars) and so on until...
/long/path/long-file-na_10.ext1.ext2(36 chars; first part further truncated)
This solution assumes that storage backends which don't allow underscores or digits in file names will implement their own
get_available_name (just like the same is currently assumed for underscores only).
It doesn't solve the case when the length of the directory path approaches
max_length and causes even truncated file names to overflow.
streetcleaner, do you intend to write a patch? If not, I volunteer to do that.
comment:15 Changed 8 years ago by
comment:16 Changed 8 years ago by
With no concrete patch at this point, I don't see this having a chance to make it into 1.2.
comment:17 Changed 7 years ago by
What are the drawbacks to just making a FileField use Text instead of varchar in the database? It seems like a pretty simple solution that would completely resolve the issue.
Another point from Shai Berger in the googlegroups thread mentioned earlier:
In many engines, text fields are kept out-of-table; then, what's kept in the
table, is (effectively) the name of a file where the text is kept. Even if
this doesn't seriously affect performance, using such a field to keep a
filename must raise a few eyebrows.
Changed 7 years ago by
comment:18 Changed 7 years ago by
I just ran into this problem last week and decided to try and write a patch. The problem was reported before model validation was incorporated, so it seemed like an easy fix to just add a validate method to the FileField model class now that those are validated. The patch just runs generate_filename to get the full length of the path that will be stored in the database and ensure it is less than max_length. Be kind, it's my first attempt at a patch.
comment:19 Changed 7 years ago by
comment:20 Changed 7 years ago by
comment:21 Changed 7 years ago by
I'd be nice if there was also some way of passing the maximum length allowed to the storage engine too so when it generates a unique name, it can truncate it down.
But even without that, this is a worthy addition.
comment:22 Changed 6 years ago by
Change UI/UX from NULL to False.
comment:23 Changed 6 years ago by
Change Easy pickings from NULL to False.
comment:24 Changed 6 years ago by
comment:25 Changed 6 years ago by
comment:26 Changed 6 years ago by
comment:27 Changed 6 years ago by
comment:28 Changed 5 years ago by
I'm going to revert that commit because of the regression reported in #19525.
Here are the relevant bits of that ticket:
As of dcd43831 (fixing #9893), a FileField will call
generate_filename() as part of the validation step for a FileField on a form. This was then updated in 05d333ba to address #18515.
Unfortunately, this means that the filename function provided as an argument to upload_to can no longer reference any field with a pre-save behavior.
The common use case for this is to organize files on disk according to upload date. For example:
def user_filename(instance, filename): return os.path.join('user_files', instance.uploaded_timestamp.strftime('%Y-%m-%d'), filename) class UserFile(models.Model): uploaded_timestamp = models.DateTimeField(auto_now_add=True) data = models.FileField(upload_to=user_filename)
Under Django 1.5, attempting to call is_valid() on a Modelform for this model will raise a "'NoneType' object has no attribute 'strftime'" exception, because instance.uploaded_timestamp hasn't been instantiated yet. This is despite the fact that the uploaded data has been provided, the generated filename would be valid, and the upload timestamp can be computed.
In Django 1.4 and earlier, this works because no validation was performed for FileFields filenames; the uploaded_timestamp was evaluated as part of the model pre-save, and the persistence of the file to disk occurred after the model was saved.
To my reading, the documentation is ambiguous on whether this is expected behavior or not. It says that the model may not be saved to the database yet, but points at AutoField as the cause for problems. However, it also explicitly talks about using strftime as part of file paths. A file datetimes of 'now' would seem to be an obvious usage of this feature.
For the record, I discovered this by upgrading a commercial project to Django 1.5, so there is at least one project in the wild that will be affected by this change. Although I've discovered it with a auto_now_add FileField, it's not hard to see that this change also affects any field with a pre_save behaviour.
It also has the potential to lead to incorrect validation. Consider the case of a field with a pre_save behavior that updates the field (auto_now is one example, but any denormalization/summary field would be an example). The call to validate occurs *before* the call to pre_save is made, which means that you're going to get the pre_save value used as part of your validation. If you then save the model, the pre_save() will be called, and the actual filename that is used for saving the file will be different to the one used for validation.
Some initial thoughts about possible solutions:
- Document that you can't use a field with pre-save behaviour. Not ideal IMHO, since it rules out an obvious use case for upload_to.
- Roll back the fix. Also less than ideal; #9893 is an edge case bug, but it's something that has been seen in the wild, and isn't *too* hard to generate.
- Invoke pre_save on all model fields prior to validation. Given that most validation doesn't need this, this approach seems a little excessive.
I've just checked with my production code, and yes,
default=timezone.now works for the
auto_now_add case. However, it won't address
auto_now, or the
pre_save conflict problem.
comment:29 Changed 5 years ago by
comment:30 Changed 5 years ago by
comment:31 Changed 5 years ago by
comment:32 Changed 5 years ago by
comment:33 Changed 5 years ago by
I don't know how to solve this properly.
comment:34 Changed 5 years ago by
comment:35 Changed 5 years ago by
comment:36 Changed 5 years ago by
So, I ran into bug #13314. These are all similar but not quite the same.
#9893 -- Filename + path length greater than 100 (when making filenames unique)
#10410 -- FileField saves one filename on disk and another on DB
#13314 -- validation does not account for "upload_to" when counting characters
This ticket #9893 is about the changed filenames when making them unique.
Ticket #13314 is just about the upload_to parameter. For that problem the fix could be done like this:
--- django/db/models/fields/files.py.orig 2013-04-01 17:03:59.752332630 +0200 +++ django/db/models/fields/files.py 2013-04-01 17:08:15.833870239 +0200 @@ -290,6 +290,8 @@ if 'initial' in kwargs: defaults['required'] = False defaults.update(kwargs) + # And deduct the upload_to length from the max_length. + defaults['max_length'] -= len(self.upload_to) return super(FileField, self).formfield(**defaults) class ImageFileDescriptor(FileDescriptor):
With this environment:
- ImageField with max_length default 100
- An upload_to value of "profile/" (8 characters)
Without the fix, I get a DatabaseError for a 99-byte length filename.
With the fix, I get a nice ValidationError until I reduce the filename to 92 bytes.
That should be at least be one less problem, right?
This was tested with Django 1.3.7.
comment:37 Changed 4 years ago by
comment:38 Changed 4 years ago by
Hey guys
Long time no activity on the ticket...
I have recently run into this bug on production myself. We needed a solution ASAP, so I ended up with an overwrite for get_available_name(), providing max_filename_length as an argument. Pretty much what @akaihola first suggested in. Seem to be working fine for us. I can try implement this as a general solution now, if you think this would be a proper fix.
Cheers.
comment:39 Changed 4 years ago by
pavel_shpilev put together a PR based on ticket:9893#comment:1 that still requires some adjustments.
comment:40 Changed 3 years ago by
Pavel Shpilev wants another review.
comment:41 Changed 3 years ago by
comment:42 Changed 3 years ago by
Comment for improvement is on the PR.
comment:43 Changed 3 years ago by
comment:44 Changed 3 years ago by
comment:45 Changed 3 years ago by
comment:46 Changed 11 months ago by
Hello,
could it be that this bug still exists?
Both on Django 1.8.18 and 1.11.2 I see this behavior isn't corrected yet.
The validation of max_length takes only file_name into account and ignores upload_to, causing truncation on the database level, exactly as described in
When I check out the relevant code I strongly suspect this bug was never fixed:
Wouldn't it be easy to change the length of the field to > 100 characters? It's not like increasing the space to 255 would hurt anybody and it would surely make the problem go away for a huge percentage of file names. I just ran in to this myself. | https://code.djangoproject.com/ticket/9893 | CC-MAIN-2018-17 | refinedweb | 2,703 | 56.15 |
Hi On Fri, Aug 11, 2006 at 07:54:31PM +0200, Marco Manfredini wrote: > On Friday 11 August 2006 19:11, Michael Niedermayer wrote: > > > ill leave this to our Makefile maintainer but my oppinion is rejected > > as this 1. will break with some compilers and 2. doesnt belong to the > > Makefile > > The Makefile already assigns per file opcode extension flags. After my > addition it continues with: > > ifeq ($(TARGET_BUILTIN_VECTOR),yes) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > i386/fft_sse.o: CFLAGS+= -msse > depend: CFLAGS+= -msse > endif > ifeq ($(TARGET_BUILTIN_3DNOW),yes) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ [...] > So it seems to belong in the Makefile and neither -m3dnow nor -msse have been > cause for concern regarding older compilers. no, see above, they are under ifeq ... [...] -- | http://ffmpeg.org/pipermail/ffmpeg-devel/2006-August/007333.html | CC-MAIN-2016-36 | refinedweb | 109 | 65.12 |
K.O.L.M. Prototype
A demo of the K.O.L.M. Kickstarter game.4.18 / 5.00 8,425 Views
Quantum Of Light
A relaxed yet challenging puzzle with 24 levels.3.91 / 5.00 4,628 Views
At 7/8/06 08:40 AM, randomfunkychicken wrote: hi could some one please do a tutorial for mini games it dusnt metter what one just PLLLLEEEEAAAASSSEEE DDDOOOO IIIITTTTT
CHHHEEEESSEEEEE
Shut Up. What do you mean mini-game. There's millions of mini-games, a pong game, a shooter, a RPG, anything. Be a little more specific.
Just make a game, and link to it, tada.
idiot.
the game im looking for is the sorta game you know where you have to press a button as fast as you can to fill up a bar b4 the other dudes bar fils up and each time you press the button it shows the guy doin sumfin you know what i mean?
also i was looking for onw where you have to run by pressing the left <~ then right ~>
keys and you gotta get to the specific zone before the time runs out (i dont know how to do a timer)
id really appreciate this and for you guys not to slag me off then tell me to learn syntax/action script bcoz THATS Y IM ERE TO TRY AND LEARN!!!
any way thanks
At 7/10/06 02:38 PM, randomfunkychicken wrote: the game im looking for is the sorta game...
You make a new thread for that. Don't spam the AS: Main, its too precious.
AS: RGB
AS: LocalConnection by GuyWithHisComp
<a href="/bbs/topic.php?id=528519">AS: LocalConnection</a> by <b>GuyWithHisComp</b>
Had to move things round a bit since the Intermediate section is pushing the post limit
Notepad version of the list
AS: Main - Alphabetic List - No longer updated since Page 44
BASIC - GENERAL
AS: _currentframe by True_Darkness
AS: _name by Darkfire_Blaze
AS: _x and _y by True_Darkness: Varables - More by phyconinja
AS: Video by Depredation
BASIC - SPECIFIC-
INTERMEDIATE - GENERAL
AS: Arrays
AS: Arrays by Creeepy
AS: Artificial Thinking by -Vengeance-
AS: AsBroadcaster by liam
AS: Basic Combos by -Toast-
AS: Binary and Bitwise Operators by Claxor
AS: Camera Control by Inglor: File Upload (uses PHP) by Khao
AS: Filters (Flash 8) by GuyWithHisComp
AS: Filters (Flash 8) by Inglor
AS: Flash & PHP by shazwoogle
AS: Flash > ASP > Txt: Save and Load: Try And Catch (Error Handling) by authorblues
AS: Upload/Download (Flash 8) by -liam-
INTERMEDIATE - SPECIFIC
AS: Black and White (Flash 8) by fwe
AS: Cannon by reality_check7
AS: Fading Trail Effect (Bullet Time)
AS: Fireworks (API) by Inglor
AS: Flash/PHP Webpage Hit Counter
AS: Flash Registration Form by bigftballjock: Timer by GuyWithHisComp
AS: Typewriter Effect by Atomic: Art-based Normal Detection by Glaiel_Gamer
OTHER USEFUL LINKS:
Flash Newbie Help by -ArcticHigh-
Flash (noob) tutorial by -hellraiser-
Starting with Flash by Otacon
NG's best tutorial movies
Flash tuts list by AGH
The Big Tutorial List by IWantSomeCook
Flash/ASP scoreboard
Flash/PHP scoreboard
Cross-domain policies
Sprite page list by different
Music and Sound Effect sites V2 by different
Bookmarking and favicons by Ozcar
Flash: Shortcut Keys by -Unknown-
Flash: Code Shortcut keys by Rantzien
Claymation info by schorhr
FOSS: Main
AS3 Language Specs
Fixing problems with importing sound
How to: Flash to animated .gif
A tut on running javascript functions in AS :D
At 7/19/06 08:19 AM, soul_blade1 wrote: What about a tutorial on making a battle engine sort of like pokemon and adding how to randomize what the enemy does
A battle engine's very specific, and probably should go under FOSS
(or) where you pressed a button and everything in the specified area disappeared so it could be printed it was cool
AS: Print
AS: Swap Depths
...
At 7/22/06 04:17 PM, True_Darkness wrote: AS: API Scritped Camera
Nice. The e.g doens't work for me though, lol.
My 2nd, yay!
AS : .txt File Incorporation
Making swf file information editing easier for everyone.
there... im pretty sure its not that good, but oh well
various speed tests to be used as a resource, done in flash 9 alpha with AS3, but most of it par one or two are the same for AS2 in terms of which is fastest
using ShamelessPlug; NapePhysicsEngine.advertise();
Hey i just thought, noone has made a tutorial on how to make a game like worms! I don't know myself, it's just that would be really useful
Song of the Firefly is on Steam Greenlight and Facebook. Give them a look and support the project!
------------------------------
At 7/29/06 11:06 AM, Hoeloe wrote: Hey i just thought, noone has made a tutorial on how to make a game like worms! I don't know myself, it's just that would be really useful
That uses Bitmap Data, which -liam- made a tutorial on, but I WOULD like to see the actual scripting for that rather than just commands for bitmap data, since I hardly use or know bitmapo data.
Yeah, i wanted to make a puzzle game like that, oh well! Back to my 2 collabs and The Battle of Evermore...
Song of the Firefly is on Steam Greenlight and Facebook. Give them a look and support the project!
------------------------------
The last thing we probably need is another platformer tutorial but I wanted to get this old engine out in the open, and in any case it does demonstrate a slightly wider range of features than just variables and if(); statements.
White Noise/TV Static Effect by electricfreak
White Noise/TV Static Effect by electricfreak
Don't know if you want it, but I'm gonna link it to people because I'm sick of answering it. :)
- AS: Rounding to the nearest ...
External Audio Optimization
They're not strictly AS, but it's a recource. Useful links, maybe?
if the thread grows a little, anyway.
AS: Preloader not appearing
[6,11,4,10,2,10,-68,5,15,-68,16,4 ,1,-68,-2,1,15,16,-67].map(function(v){ return String.fromCharCode(v + 100) }).join(""); // updated for web 2.0!
Can anyone make a specific-section tutorial about something like this.
That means it would calculate how much time it would take to the target and the bullet to arrive to places, and then find an angle that would make a collision with the target and the bullet if you shoot.
I hope I made it clear. | http://www.newgrounds.com/bbs/topic/229808/43 | CC-MAIN-2014-35 | refinedweb | 1,093 | 63.53 |
The UI provides a "CHECK NOW" button on the dataset settings, schema tab
Can this be run in code?
Hello,
You can achieve the same as the dataset schema tab "CHECK NOW" button with the following code sample:
import dataiku client = dataiku.api_client() p = client.get_project('PROJECT_KEY') future = p.get_dataset('DATASET_NAME').test_and_detect() future.wait_for_result() try: warningLevel = future.get_result()['format']['schemaDetection']['warningLevel'] print('Warning level:' + warningLevel) except KeyError: print('No warning')
In the schemaDetection dict you have many informations like the reasons of the warning in "textReasons" and the type of the warning in "type".
I hope it helps,
Arnaud
Hi Arnudde,
Thanks for the response.
Will this work with custom defined SQLServer datasets?
I get this exception on test_and_detect():
DataikuException: java.lang.ClassCastException: Cannot cast com.dataiku.dip.datasets.sql.ManagedSQLTableDatasetTestHandler to com.dataiku.dip.datasets.sql.ExternalSQLDatasetTestHandler
Actually I raised a support ticket on a similar question for which the response was that this was not currently possible with the API.
I would need something that also emulated the "Reload schema from table" button if a warning was found.
Hi,
Do you get the same "Java.lang.ClassCastException" exception when using the "Check Now" button ?
You can achieve the same as the "Reload schema from table" button by extracting the detected schema from the result of "test_and_detect()" method and set it for the dataset with the DSSDataset.set_schema method
detected_schema = future.get_result()['format']['schemaDetection'["detectedSchema"]
Hope it helps, | https://community.dataiku.com/t5/Using-Dataiku/Python-API-equivalent-to-quot-CHECK-NOW-quot-button/td-p/15177 | CC-MAIN-2021-43 | refinedweb | 239 | 51.34 |
<<
128 Reader Comments
Muhammed Tapdancing Allah.
Drive letters. In 2011.
1983 called. They want their CPM back.
Muhammed Tapdancing Allah.
Drive letters. In 2011.
1983 called. They want their CPM back.
Oh my God. DID YOU WARN THEM?
AFAIK, racks come in regular sizes, so can't be cyclopean (massive irregular blocks) by definition, unless you mean "like a cyclops", but that would limit them, surely, to one blinkenlight each?
Try Brobdingnagian.
Pfff. These have a neato glowing logo though!
Yes, well, given that Isilon has been selling their solutions for about 10 years, it is indeed nothing new.
That's what I was thinking. GPFS meets FreeNAS or something along those lines. But on the other hand, I don't think companies buy these sorts of appliances for their technical superiority so much as for the support that comes with them. It's probably not the sort of product an IT enthusiast would use for his personal pr0n collection, even if it is a petabyte (maybe an LTO tape library and SAM-QFS).
If you wanted to make it truly neutral, you'd remove all of the brand name references. Then we could appreciate it as a technology primer.
Also, there's no mention whatsoever of cost: is this something that's insanely expensive and only people who could afford to buy EMC or NetApp price levels would be interested? Or would a small company that needs 20-30 TB of NAS be able to fit this into a reasonable budget?
Comparing these prices to the prices of raw disk drives is not the way to go, the cost of the actual disk has been trending toward $0/GB; you pay for all the R&D and software and support, no so much for raw disk.
E.g. 3 x X200 nodes with 12 x 2TB SATA each, give you about 72TB total, at say $3/GB that's about $210k. Plus accessories and maintenance contract.
Oh and I dunno how the pricing is under EMC but prior to their ownership Isilon wasn't the cheap way to get a lot of nearline storage so no most small companies would look elsewhere.
The IBM XIV and (now) EMC Isilon arrays are the two most interesting and important enterprise arrays on the market. Isilon has a little bit of maturing to do as far as non disruptive upgrades (they have them, but only for minor releases which isn't good enough) and better block mode (better than iSCSI) to catch up with XIV, but they are both fantastic systems. It's going to be fascinating to watch these guys continue to develop and see them kill off the old dinosaur Symmetrix/HDS/DS8000 architectures.
Conceptually we make a similar product. Practically, our offering is far simpler to manage and far easier to deploy. We regularly have customers go from opening boxes to accessing their nodes in half a day and go from 2-4 storage managers to less than 1. There are lots of storage technologies on the market, and more than any other company (I think), we focus on simplifying management without sacrificing performance. The needs of enterprise storage houses like we sell to are pretty specific and very, very different than smaller houses.
Because this isn't a shootout, it's an article about a particular thing. Just like any other article on Ars that's about a laptop, a graphics card, a new music-playing device, a new service, a new CPU, etc. If Jon Stokes worked for Intel, would his CPU articles seem worse?
(I also got permission to write the article from both EMC & Isilon PR before I put pen to paper. They had no editorial input & I was given a totally free hand, but they are aware of it and everything is above-board.)
Last edited by Pokrface on Fri May 13, 2011 11:26 am
IBM has in the past year released its scale out NAS product called (not surprisingly) SoNAS. It is an appliance built around GPFS, and has many of the same functions as the product described in the article, though the internals function somewhat differently.
It is interesting to see how this system is implemented compared to SoNAS. In order to avoid any flame wars, that's all I will say. Good article.
No, it really isn't. EQL does not do anything like OneFS.
Ha, awesome. I've been talking to so many EMC folk lately. It's cool to suddenly be part of a larger company. Like someone bought me an ultra-fancy tailored suit and I'm just getting used to how awesome it feels.
I encourage you to contact an Isilon sales rep if you're considering a purchase, but we sell several products, so this isn't a cut-and-dried question. If you want our most "dense" product, the 108NL, then 12PB will be 114 nodes. If you assume 12% protection overhead (which might be less than you would actually want for this kind of setup), you'll actually want around 130 nodes. That's 520U of space or just over 12 server racks. Since you'll want to reserve space for switches and the like, it's probably more like 14 racks.
That's 4,680 3TB server-quality drives. They don't call it "big iron" for no reason. ;-)
Each node has two 1kw power supplies, one active and one failover, so power draw from these nodes is a maximum of 2kw each if both were somehow turned on. In reality it's a maximum of 1kw per node.
This information is all available through public whitepapers on our website.
Also, Equalogic while nice for midsize to small datacenter; and particularly VMWare, I wouldn't say it compares to Isilon. Honestly, I wouldn't scale on Equalogic. On topic of Dell their recent purchase of Compellent puts Dell in more Enterprise than Equalogic did. Compellent has very similar technology, but more flexabilty and scalability on SAN features.
I just picked up 96TB of Netapp for $130,000 ($1,354 / TB). It's not exactly the same but it is in the same class as the subject hardware. When purchasing systems like this you really have to include support costs from the provider - usually adds 20% of the purchase price per year of operation to the total cost
That's a lot of rotational energy! I wonder if the building is lighter on one side due to gyroscopic precession?
Seriously though, has anyone studied the effect of aligning the drives so that their spin axis is parallel with the Earth's? It seems to me that there should be a (small -- tiny -- minuscule?) power saving by doing this.
I was going to say that it sounds as if the 12PB is close to the limit that the current solution can go to (given the current 144 limit on the nodes, the 108TB that the biggest piece of kit has and the need for protection overhead).
In terms of building larger arrays, is there any limitation to just adding HD's to the individual nodes? Or is the 144 node limit on the infiniband back-end a technical limitation, or simply that no-one has needed a higher capacity before?
Keep watching our press releases. ;-)
Ditto. You can't just characterize SANs as "that block thing that has no concurrent access to namespaces". Not in a world where there's Stornext. A Stornext SAN with two metadata controllers and two or more round-robin NAS heads can still give block access to the systems that may need it and most of the redundancy of a SONAS system.
What it can't have, is transparent tiering that includes SSDs. AFAIK, Stornext Advanced only does tiering-out to tape.
That's a big PDF file.
EDIT: Also, I loved the "blinkenlights" reference. I was, oh, about 30 years from being born when it went around the first time, and my boss (the server admin at my little ~150-person outfit) was about 20 years from being born himself, so I'm posting that in the server room to see if he notices and gets the reference.
Well worth the time to read.
You must login or create an account to comment. | http://arstechnica.com/business/2011/05/isilon-overview/?comments=1 | CC-MAIN-2015-27 | refinedweb | 1,385 | 71.24 |
OBInternalCoord Class Reference
Used to transform from z-matrix to cartesian coordinates. More...
#include <openbabel/internalcoord.h>
Detailed Description
Used to transform from z-matrix to cartesian coordinates.
Used with OpenBabel::InternalToCartesian and OpenBabel::CartesianToInternal methods. Does not perform any actions itself. You must create or free OBAtom pointers yourself.
The z-matrix representation uses coordinates relative to up to three atoms, which need not be bonded in any fashion. A rough sketch of the a, b, and c atoms would be:
'*' / / a----b / / c
where the OBInternalCoord record reflects the '*' atom.
- Warning:
- Does not detect if NULL pointers are used. You should be careful.
Constructor & Destructor Documentation
Constructor.
Member Data Documentation
First connection for this atom (i.e., distance).
Second reference atom (i.e., angle).
Third reference atom (i.e., dihedral / torsion angle).
Distance between this atom and _a.
Angle between this, _a, and _b (i.e., _a is the vertex).
Torsional/dihedral angle between this, _a, _b, and _c.
The documentation for this class was generated from the following file: | http://openbabel.org/dev-api/classOpenBabel_1_1OBInternalCoord.shtml | CC-MAIN-2020-16 | refinedweb | 172 | 54.49 |
>
EDIT: Problem solved. It actually was super simple. Let this be a lesson to you: When you get confused, get up, take a walk and then come back and re-look at your code. It could save you hours. In this case, it was here:
public Block reinforcedIron = new Block(1, "Reinforced Iron");
This gets executed before Awake(). I had to just put the definition into Start(). So easy!**
Hello there.
I've been working on a game similar to Terraria where you can place "blocks" and break them again. For this I have been trying to make a class for the blocks to easily add new blocks and get information from them later on in the game. This is my "Block" class so far: using UnityEngine; using System.Collections; using System.Collections.Generic;
public class Block {
public int ID;
public string Name;
public Transform Prefab;
public Block(int sentID, string sentName) {
ID = sentID;
Name = sentName;
if(Control.instance.prefabs[ID] != null) {
Prefab = Control.instance.prefabs[ID];
} else {
Debug.LogError ("Warning! There is no prefab for block with ID " + ID);
}
}
}
I want to later on be able to make a new Block by doing "Block dirt = new Block(1, "Dirt");" for example to make a dirt block. Then the Block class will auto assign all the information for it (e.g. it will search an Array (seen in the next script) for the Transform corresponding to it's ID) and I can get the ID via dirt.ID, the name via dirt.Name and the prefab via dirt.Prefab).
This is my "Control" class: using UnityEngine; using System.Collections; using System.Collections.Generic;
public class Control : MonoBehaviour {
public static Control instance;
public static int[,] blocks = new int[999,999];
Vector2 mousePos;
public Block reinforcedIron = new Block(1, "Reinforced Iron");
public Transform[] prefabs = new Transform[999];
void Awake() {
instance = this;
}
void Start () {
Debug.Log (prefabs[0].name);
for(int x=0; x < blocks.GetLength(0); x++) {
for(int y=0; y < blocks.GetLength(1); y++) {
blocks[x,y] = -1;
}
}
}
void Update() {
mousePos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10));
}
}
It's a Singleton so that I can access the prefab array for prefabs from the Block class and assign the prefabs in the Editor. This way I can search a prefab by its ID in the Block class (see above for more info).
Now I am getting these two Errors when I start the game:
NullReferenceException: Object reference not set to an instance of an object
Block..ctor (Int32 sentID, System.String sentName) (at assets/Block.cs:14)
Control..ctor ()
IndexOutOfRangeException: Array index is out of range.
Block..ctor (Int32 sentID, System.String sentName) (at assets/Block.cs:14)
Control..ctor ()
Why? What am I doing wrong? For those interested, the "prefab" in my Editor is empty, I however to test added 1 prefab to it (made size to 1 and added a prefab) to see if it can store things. Why is the Block class throwing an IndexOutOfRangeException when I haven't even accessed anything through it yet? And why is there an NullReferenceException when I am using a Singleton?
Thank you, Sincerely, aleichert
Please post an answer instead of placing an answer in Again Arrays In ExecuteInEditMode() Gives NullReferenceException Errors??
1
Answer
"Null Reference Error" when using a custom class as an array
1
Answer
Pushing GameObject into JS Array returns NullReferenceException
1
Answer
C# custom class array error in adding a new entry.
1
Answer
Instantiating gameobjects in an array / class problem | NullReferenceException:
0
Answers | https://answers.unity.com/questions/1007608/problem-with-singleton-and-nullreferenceexception.html | CC-MAIN-2019-22 | refinedweb | 592 | 57.67 |
Well, my frustrations with MySQL and MacOSX continue. This time after a copmlete clean reinstall of everything I have stumbled upon the ‘old friend’ MySQLdb Python module. Apparently setting up this one causes a lot of frustration and blogging. Here is what I have found.
1. Check your platform. I have an old MacBook and naively installed 32 bit MySQL on it. Man, I was wrong. Since I wanted to use the default MacOSX Python I should have checked that one fist. You can do that by executing the following commands in the Python interactive shell:
import sys
import math
math.log(sys.maxint, 2)
It gave me… “63.0”. Wow… Apparently I do have 64-bit Python!
2. Having 64 bit Python you must install 64 bit MySQL. So go and get the proper version.
3. If you think you’re there you’re not getting my frustration yet. If you would get MySQLdb, build it now and run as I did, the following statement
import MySQLdb
will likely to result in
Traceback (most recent call last):
File "/oleksii/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
Referenced from: /Users/oleksii/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
Reason: image not found
Ok, this was it. I had to dig around and finally found out that it is a known bug in the at least 5.5 version of MySQL, explanation and the fix can be looked up at the MySQL bugs website.
In short you have to perform the following
sudo install_name_tool -id /usr/local/mysql/lib/libmysqlclient.18.dylib libmysqlclient.dylib
where ’18’ needs to be replaced with your version.
4. Finally get the MySQLdb (I’ve got 1.2.3). Build it, make sure the proper architecture is used. The architecture can be enforced with e.g. the following commands:
export VERSIONER_PYTHON_PREFER_64_BIT=yes
(or the coresponding one for 32 bits)
Wow, finally import worked as I had expected. WTFx10…
…and all this after several hours debugging for a problem that existed for 10+ years and appeared due to changes in the new Visual Studio compiler optimizations… great… another sleepless night… | https://blog.bidiuk.com/tag/mysqldb/ | CC-MAIN-2021-31 | refinedweb | 378 | 67.76 |
This tutorial will show
you how to design the set of event handlers that will define
the user experience. It will cover how to add mouse
and keyboard event handlers to the main camera
and other nodes, as well as how to filter and consume events.
1.
Setup
We need to create a window with a Piccolo canvas, so that
we can add the interface components to the canvas.
import edu.umd.cs.piccolo.*;
import edu.umd.cs.piccolo.event.*;
import edu.umd.cs.piccolo.nodes.*;
import edu.umd.cs.piccolo.util.*;
import edu.umd.cs.piccolox.*;
using UMD.HCIL.Piccolo;
using UMD.HCIL.Piccolo.Nodes;
using UMD.HCIL.Piccolo.Event;
using UMD.HCIL.Piccolo.Util;
using UMD.HCIL.PiccoloX;
PNode
PForm
PFrame
PCanvas
initialize
public class InteractionFrame extends PFrame {
public void initialize() {
//Add Piccolo code here.
}
}
public class InteractionForm : PForm {
public override void Initialize() {
//Add Piccolo code here.
}
}
2.
Create a Camera Event Listener
Event listeners can be attached to any node in the hierarchy.
The events that you get depend on the node that you have registered
with. For example you will only get mouse moved events when
the mouse is over the node that you have registered with, not when
the mouse is over some other node.
As explained in
Piccolo Patterns, events are dispatched to the PPickPath
associated with the appropriate focus node (MouseOver, MouseFocus or
KeyboardFocus). They percolate up the pick path, giving each
node along the way a chance to handle the event if that node has a
registered event handler. The events will keep
percolating up the pick path until they are consumed by a node's
event handler or they reach the originating camera node. Often
you will attach event handlers directly to the main camera, in order
to receive all events that come from the canvas.
PPickPath
public class SquiggleHandler extends PBasicInputEventHandler {
protected PCanvas canvas;
// The squiggle that is currently getting created.
protected PPath squiggle;
public SquiggleHandler(PCanvas aCanvas) {
canvas = aCanvas;
setEventFilter(new PInputEventFilter(InputEvent.BUTTON1_MASK));
}
public void mousePressed(PInputEvent e) {
super.mousePressed(e);
Point2D p = e.getPosition();
// Create a new squiggle and add it to the canvas.
squiggle = new PPath();
squiggle.moveTo((float) p.getX(), (float) p.getY());
squiggle.setStroke(new BasicStroke(
(float) (1 / e.getCamera().getViewScale())));
canvas.getLayer().addChild(0, squiggle);
// Reset the keydboard focus.
e.getInputManager().setKeyboardFocus(null);
}
public void mouseDragged(PInputEvent e) {
super.mouseDragged(e);
// Update the squiggle while dragging.
updateSquiggle(e);
}
public void mouseReleased(PInputEvent e) {
super.mouseReleased(e);
// Update the squiggle one last time.
updateSquiggle(e);
squiggle = null;
}
public void updateSquiggle(PInputEvent aEvent) {
// Add a new segment to the squiggle
// from the last mouse position to
// the current mouse position.
Point2D p = aEvent.getPosition();
squiggle.lineTo((float) p.getX(), (float) p.getY());
}
}
class SquiggleHandler : PBasicInputEventHandler {
protected PCanvas canvas;
// The squiggle that is currently getting created.
protected PPath squiggle;
// The last mouse position.
protected PointF lastPoint;
public SquiggleHandler(PCanvas canvas) {
this.canvas = canvas;
}
public override void OnMouseDown(object sender, PInputEventArgs e) {
base.OnMouseDown (sender, e);
// Create a new squiggle and add it to the canvas.
squiggle = new PPath();
squiggle.Pen = new Pen(Brushes.Black,
(float)(1/ e.Camera.ViewScale));
canvas.Layer.AddChild(0, squiggle);
// Save the current mouse position.
lastPoint = e.Position;
// Reset the keyboard focus.
e.InputManager.KeyboardFocus = null;
}
public override void OnMouseDrag(object sender, PInputEventArgs e) {
base.OnMouseDrag (sender, e);
// Update the squiggle while dragging.
UpdateSquiggle(e);
}
public override void OnMouseUp(object sender, PInputEventArgs e) {
base.OnMouseUp (sender, e);
// Update the squiggle one last time.
UpdateSquiggle(e);
squiggle = null;
}
protected void UpdateSquiggle(PInputEventArgs e) {
// Add a new segment to the squiggle
// from the last mouse position to
// the current mouse position.
PointF p = e.Position;
if (p.X != lastPoint.X || p.Y != lastPoint.Y) {
squiggle.AddLine(lastPoint.X, lastPoint.Y, p.X, p.Y);
}
lastPoint = p;
}
public override bool DoesAcceptEvent(PInputEventArgs e) {
// Filter out everything but left mouse button events.
return (base.DoesAcceptEvent(e)
&& e.IsMouseEvent && e.Button == MouseButtons.Left);
}
}
PBasicInputEventHandler
PInputEventListener
PBasicInputEventListener
When the mouse is pressed, we create a new PPath
called squiggle and add it to the canvas's main layer.
Notice that we set the path's pen width to 1 / ViewScale, so
that we will always draw with a uniform width. We also
save the current mouse position as the lastPoint.
PPath
lastPoint
When the mouse is dragged, we call UpdateSquiggle().
This method will add a new line segment from the lastPoint to
the current mouse position. Finally it will set the
lastPoint to be the current mouse position.
UpdateSquiggle()
When the mouse is released, we will call updateSquiggle one
more time and then set our current squiggle to null.
Finally, you might notice that the C# version of this code
snippet, overrides the DoesAcceptEvent method. This method
is part of the PInputEventListener interface and is used to
implement event filtering in Piccolo.NET. Any event handler class can
override this method and return true if it wants to accept an
event, or false otherwise. Filtered events will never be
dispatched to the event handler. In this case, we only
accept left mouse button events, so that the right mouse button
cannot be used to draw squiggles.
// Remove the pan event handler that is installed by default so that it
// does not conflict with our new squiggle handler.
getCanvas().setPanEventHandler(null);
// Create a squiggle handler and register it with the Canvas.
PBasicInputEventHandler squiggleHandler = new SquiggleHandler(getCanvas());
getCanvas().addInputEventListener(squiggleHandler);
// Remove the pan event handler that is installed by default so that it
// does not conflict with our new squiggle handler.
Canvas.PanEventHandler = null;
// Create a squiggle handler and register it with the Canvas.
PBasicInputEventHandler squiggleHandler = new SquiggleHandler(Canvas);
Canvas.AddInputEventListener(squiggleHandler);
Next we create our
squiggle event handler. Notice that the Java version of
this code snippet calls the setEventFilter() method
and passes it a new instance of PInputEventFilter. In
Piccolo.Java, event filtering is accomplished by creating a new
event filter object and setting various masks on that object.
In particular, an event will be accepted if it contains all the
modifiers listed in the andMask, at least one of the modifiers
listed in the orMask, and none of the modifiers listed in the
notMask. In this case, we set the andMask to a
BUTTON1_MASK, so that it will only accept left mouse button
events.
setEventFilter()
PInputEventFilter
andMask
orMask
notMask
BUTTON1_MASK
Finally, we register our new squiggle event handler to
receive events from the camera. Notice that we do this by
calling the canvas's AddInputEventListener() method. This is
just a convenience method that adds the given event listener to
the main camera associated with the canvas. We could have
also gotten the camera from the canvas and added the event
listener directly.
AddInputEventListener()
3. Create a Node Event
Listener
Now that we have added an event handler to the camera,
lets try adding an event handler to another node.
// Create a green rectangle node.
PNode nodeGreen = PPath.createRectangle(0, 0, 100, 100);
nodeGreen.setPaint(Color.GREEN);
getCanvas().getLayer().addChild(nodeGreen);
// Create a green rectangle node.
PNode nodeGreen = PPath.CreateRectangle(0, 0, 100, 100);
nodeGreen.Brush = Brushes.Green;
Canvas.Layer.AddChild(nodeGreen);
// Attach event handler directly to the node.
nodeGreen.addInputEventListener(new PBasicInputEventHandler() {
public void mousePressed(PInputEvent event) {
event.getPickedNode().setPaint(Color.ORANGE);
event.getInputManager().setKeyboardFocus(event.getPath());
event.setHandled(true);
}
public void mouseDragged(PInputEvent event) {
PNode aNode = event.getPickedNode();
PDimension delta = event.getDeltaRelativeTo(aNode);
aNode.translate(delta.width, delta.height);
event.setHandled(true);
}
public void mouseReleased(PInputEvent event) {
event.getPickedNode().setPaint(Color.GREEN);
event.setHandled(true);
}
public void keyPressed(PInputEvent event) {
PNode node = event.getPickedNode();
switch (event.getKeyCode()) {
case KeyEvent.VK_UP:
node.translate(0, -10f);
break;
case KeyEvent.VK_DOWN:
node.translate(0, 10f);
break;
case KeyEvent.VK_LEFT:
node.translate(-10f, 0);
break;
case KeyEvent.VK_RIGHT:
node.translate(10f, 0);
break;
}
}
});
protected void nodeGreen_MouseDown(object sender, PInputEventArgs e) {
PNode aNode = (PNode)sender;
aNode.Brush = new SolidBrush(Color.Orange);
e.InputManager.KeyboardFocus = e.Path;
e.Handled = true;
}
protected void nodeGreen_MouseDrag(object sender, PInputEventArgs e) {
PNode aNode = (PNode)sender;
SizeF delta = e.GetDeltaRelativeTo(aNode);
aNode.TranslateBy(delta.Width, delta.Height);
e.Handled = true;
}
protected void nodeGreen_MouseUp(object sender, PInputEventArgs e) {
PNode aNode = (PNode)sender;
aNode.Brush = new SolidBrush(Color.Green);
e.Handled = true;
}
protected void nodeGreen_KeyDown(object sender, PInputEventArgs e) {
PNode node = (PNode)sender;
switch (e.KeyCode) {
case Keys.Up:
node.TranslateBy(0, -10);
break;
case Keys.Down:
node.TranslateBy(0, 10);
break;
case Keys.Left:
node.TranslateBy(-10, 0);
break;
case Keys.Right:
node.TranslateBy(10, 0);
break;
}
}
When the mouse is
pressed, we get the pressed node and set it's fill color to be
orange. Next, we get the InputManager from the event and
set it's keyboard focus node to be the current pick path
generated from this mouse pressed event. This ensures that
all future keyboard events will be dispatched to that pick path.
Otherwise, our key pressed event handler would never get called.
For more information about focus nodes, picking and event
dispatch, see Piccolo Patterns. Finally, we consume the event by
marking it as handled. If we did not do this, the event
would percolate up to the camera and get dispatched to our
squiggle event handler.
When the mouse is dragged, we get the distance that the mouse
has moved from it's last position and we translate the node by
that amount. This is how dragging is implemented.
Notice that we get the distance by calling
GetDeltaRelativeToNode, ensuring that the value returned is in
the local coordinate system of this node. We also mark
this event as handled.
GetDeltaRelativeToNode
When the mouse is released, we set the node's fill back to
green and mark the event as handled.
When an arrow key is pressed, we will translate the node by
10 in the direction of the arrow. Note the key pressed
event handler will only get called when our node has the
keyboard focus. So, once we click on the node, we will be
able to move it with the arrow keys . But, after we draw a
squiggle, the arrow keys will no longer move the node, since the
squiggle event handler resets the keyboard focus to null.
We would then have to click on the node again to give it back
the keyboard focus.
// Attach event handler directly to the node.
The Java version defines and attaches the event handler using an anonymous
class. See previous code sample.
// Attach event delegates directly to the node.
nodeGreen.MouseDown += new PInputEventHandler(nodeGreen_MouseDown);
nodeGreen.MouseDrag += new PInputEventHandler(nodeGreen_MouseDrag);
nodeGreen.MouseUp += new PInputEventHandler(nodeGreen_MouseUp);
nodeGreen.KeyDown += new PInputEventHandler(nodeGreen_KeyDown);
PInputEventHandler | http://www.cs.umd.edu/hcil/piccolo/learn/interaction.shtml | crawl-001 | refinedweb | 1,757 | 51.14 |
Opened 8 years ago
Closed 7 years ago
Last modified 7 years ago
#6412 closed defect (fixed)
no images/css
Description
Thank you for writing this plugin, it helps me with having an externally available trac instance. I did notice that css and images don't show up though, which is a problem for external vendors who may think I'm unprofessional. I fixed this by adding '/chrome' to the paths list in filter.py, and I thought it might be a change other people would want as well.
Attachments (0)
Change History (9)
comment:1 Changed 7 years ago by
comment:2 Changed 7 years ago by
comment:3 Changed 7 years ago by
Disclaimer: I don't use the plugin or know anything about its code, I just noticed this one change by 'accident' :-)
For the change to make sense, you really need to exclude all
/chrome. Plugins that adds own static resources extend the
/chrome namespace. Most plugins will likely be blocked by your plugin before they get a chance to serve their static content (like my FullBlogPlugin that serves under
/chrome/tracfullblog/, but something like a Theme-type plugin will make the problem quite apparent as that is intended to change the overall layout and look-and-feel for all requests.
comment:4 follow-up: 5 Changed 7 years ago by
Thanks for review. I intentionally did not include all
/chrome requests as the purpose of this plugin is to exclude requests from anonymous users to all Trac parts except login. I am not sure that
/chrome/plugin access will not trigger some plugin code and that the code will not be a source of information leaks.
Do you know how
/chrome/plugin resources are processed?
comment:5 Changed 7 years ago by
Do you know how
/chrome/pluginresources are processed?
All
/chrome/<something> is processed by the Trac Chrome module. It looks in static resources for plugins depending on what the plugin has registered. No code is executed on the server, it is a straight resource lookup just as it is for
common and
site which are the two basic locations/namespaces known on to an environment.
comment:6 Changed 7 years ago by
I must admit that I am unable to find information on t.e.o. about how plugins register their resources and where these resources are placed.
comment:7 Changed 7 years ago by
See
trac.web.chrome.ITemplateProvider interface - for this particular purpose
get_htdocs_dirs() method that plugins use to return locations for static resources with corresponding path prefix.
comment:8 Changed 7 years ago by
Need more round tuits. For now documented some behavior at
Thanks for report, my static resources are served directly by Apache, so I didn't notice the issue.
Adding /chrome/site and /chrome/common to the exclusion list should be enough to close the issue. | https://trac-hacks.org/ticket/6412 | CC-MAIN-2017-34 | refinedweb | 479 | 67.69 |
How do you Append a Symbolic Matrix?
To All:
I am trying to make a function that will take a set of dynamics and a set of independent variables that can or cannot be within the dynamics equations to create a "frozen" state space matrix, A. I would like to tell you all now that I am mostly a FORTRAN coder and am in the process of trying to understand SageMath, which is why I am coding in a brute force method.
I previously checked to make sure that the derivative function was producing reasonable answers and created the matrices like this.
rmag = r[0]^2 + r[1]^2 + r[2]^2; dyn = -mu*r/rmag^3; # spherical gravity assumption ddyn_dx = dyn.derivative(r[0]);ddyn_dy = dyn.derivative(r[1]);ddyn_dz = dyn.derivative(r[2]); pdyn_pr = (transpose(matrix([ddyn_dx,ddyn_dy,ddyn_dz])));
As you might have discovered, this is exceptionally tedious when the number of independent variables get larger. Therefore, I desired to code something like this:
def FindDynMatrix(dynamics,xvect): # Find the length of the vector defining the internal variables # within dynamics are independent variables: leng = len(xvect); for j in range(leng): vect = dynamics.derivative(xvect[j]); if j == 0: mat = vect; else: mat=matrix([mat,vect]) #mat = mat.append(vect) # didn't work return mat
In "FindDynMatrix", symbolic vector that is dependent on a multitude of variables including those within the symbolic vector "xvect". The hope was to "black box" the production of the A matrix for a little controls tool that I am coding up.
However, I can not find a way to get this to work. Help would be appreciated.
It would be easier for us to understand your question if you provide the definition if the list
rin your first line (which seems different from the
ryou used in your second line), the type and an example of
mu,
xvect,
dynamics, ... so that we can try.
'r' is a vector so the equation is correct. x,y,z = var('x,y,z') mu = var('mu') r = vector([x,y,z]) The variable 'dyn' is just an assumed spherical earth gravitational equation. 'mu' is a constant. One should be able to get 'pdyn_pr' as produced by the first set of equations by calling 'FindDynMatrix' like this, FindDynMatrix(dyn,r)
I believe that I have found the solution for part of this problem. By calling Jacobian(dyn,r), I can produce 'pdyn_pr'. Reference: (...)
However, I would still like to know how to append to symbolic matrices for future reference. | https://ask.sagemath.org/question/32406/how-do-you-append-a-symbolic-matrix/ | CC-MAIN-2020-10 | refinedweb | 422 | 52.6 |
for...in Statement
Executes one or more statements for each property of an object, or each element of an array or collection..
The following example illustrates the use of the for ... in statement with an object used as an associative array.
This function returns the string that contains the following.
This example illustrates the use of the for ... in statement with a JScript Array object that has expando properties.
function ForInDemo2() { // Initialize the array. var arr = new Array("zero","one","two"); // Add a few expando properties to the array. arr["orange"] = "fruit"; arr["carrot"] = "vegetable"; // Iterate over the properties and elements // and create the string result. var s = ""; for (var key in arr) { s += key + ": " + arr[key]; s += "\n"; } return (s); }
This function returns the string that contains the following.
The following example illustrates the use of the for ... in statement with a collection. Here, the GetEnumerator method of the System.String object provides a collection of the characters in the string.
function ForInDemo3() { // Initialize the collection. var str : System.String = "Test."; var chars : System.CharEnumerator = str.GetEnumerator(); // Iterate over the collection elements and // create the string result. var s = ""; var i : int = 0; for (var elem in chars) { s += i + ": " + elem s += "\n"; i++; } return(s); }
This function returns the string that contains the following. | http://msdn.microsoft.com/en-us/library/4z08sst3.aspx | CC-MAIN-2014-15 | refinedweb | 216 | 60.61 |
Implement queue using stack
In last post, we learned about stack data structure, in this post, we will discuss another data structure called queue. However, problem at hand is to implement queue using stack. Implement following functions on queue using stack
1. push() : inserts element at the back of queue.
2. pop() : removes element from front of the queue.
3. peek() : return element at front of the queue.
4. empty() : returns true if there is no element in queue.
Keep in mind that you can only use standard stack operations : push(), pop(), peek() and empty()
Stack is data structure where the element which is entered at top is taken out from top. It’s called LIFO pattern. Oppose to that queue is a FIFO data structure, where elements are entered at the rear and taken out from front. So effectively, we have to implement a FIFO data structure using LIFO data structure.
Implement queue using stack : Line of thoughts
To implement a FIFO using LIFO data structure, we need two stacks.
Push()
When element is inserted i.e
push() operation, new element has to be pushed down the stack at bottom, as this should be the last element to be popped. So, to push an element in queue, we will take out all existing elements from stack s1 and put them into stack s2. Now, push the new element on to stack s1. At last, pop all elements from stack s2 back to stack s1. Below picture shows what happens when you we push 3 to queue and what happens behind the scene using stacks.
/>
Complexity of push operation with this method is
O(n). If there are n elements already inserted into queue, inserting a new element will require n pops from s1, n pushes to s2, then n pops from s2 and then again pushes to s1.
Pop()
If we follow the push operation described above, pop operation would be nothing but to return top of s1, which is constant operation with complexity of
O(1).
/>
Peek and empty functions also run always on stack s1. For peek, return
s1.peek() and for empty return
s1.empty()
Queue with stack : Push O(n), pop O(1) implementation
package com.company; import java.util.Stack; /** * Created by sangar on 23.9.18. */ public class QueueWithStack { private Stack<Integer> s1; private Stack<Integer> s2; public QueueWithStack(){ s1 = new Stack<>(); s2 = new Stack<>(); } public void push(int x){ if(s1.empty()) s1.push(x); else{ while(!s1.empty()){ s2.push(s1.pop()); } s2.push(x); while(!s2.empty()){ s1.push(s2.pop()); } } } public int pop(){ if(s1.empty()) return -1; return s1.pop(); } public boolean isEmpty(){ return s1.empty(); } public int peek(){ return s1.peek(); } }
Test class for above implementation would be:
package test; import com.company.QueueWithStack; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Created by sangar on 23.9.18. */ public class QueueWithStackTest { QueueWithStack tester = new QueueWithStack(); @Test public void queueTest() { tester.push(2); tester.push(3); tester.push(5); tester.push(1); assertEquals(2, tester.pop()); assertEquals(3, tester.pop()); assertEquals(5, tester.peek()); assertEquals(false, tester.isEmpty()); } }
Can we do better than
O(n) while pushing element in queue?
Queue with stack : Push O(1), pop amortized complexity O(1) implementation
Push()
What if we push on s1 as it is. What does it change? It make push operation on queue
O(1).
Pop()
How does it impacts pop operation? If we pop all element from s1 and push them onto s2, at the top of s2 is actually the element we need. Also, due to this pop and push operation, s2 now contains all the elements in correct pop order for queue.
So idea is to always push in s1 as it is, however when popping out, check if s2 is empty or not? If not, then pop from s2 and return, if it is empty, pop all elements from s1 and push them all on s2 and return the top.
/>
How does it impact the performance? Well, it is true that if there is not element in s2, we have pop and push on s2, which has complexity of
O(n). HOwever, all subsequent pop operations are O(1), this is called amortized complexity of
O(1).
Empty()
Queue to be empty, there should not any element in either s1 or s2.
Peek()
If s2 is empty, then pop from s1 and push on to s2 and then return peek of s2.
package com.company; import java.util.Stack; /** * Created by sangar on 23.9.18. */ public class QueueWithStackOptimized { private Stack<Integer> s1; private Stack<Integer> s2; private int front; public QueueWithStackOptimized(){ s1 = new Stack<>(); s2 = new Stack<>(); } public void push(int x){ if(s1.empty()) front = x; s1.push(x); } public int pop(){ if(!s2.empty()) return s2.pop(); if(!s1.empty()) return -1; while(!s1.empty()){ s2.push(s1.pop()); } return s2.pop(); } public boolean isEmpty(){ return s1.empty() && s2.empty(); } public int peek(){ if(!s2.empty()) return s2.peek(); return front; } }
Complexity of peek function is again amortized to
O(1). Can you write test cases for implemented queue?
Please share if there is something wrong or missing. If you want to have personal coaching from our experienced coaches, please reach out to us at [email protected] | https://algorithmsandme.com/tag/queue-with-stack/ | CC-MAIN-2020-40 | refinedweb | 892 | 68.67 |
CapturePRO interfaces with any Video…
EAGetMail POP3 IMAP4 .NET Component Crack Download 🔷
EAGetMail POP3 & IMAP4 .NET Component is a software utility dedicated to email application developers who intent to work with C++, C#, VB6, VB.NET, ASP, JScript.NET, ASP.NET or other .NET frameworks in a more efficient manner.
It is important to note that EAGETMAIL Component comes not only with an ActiveX version but also with a .NET edition for all developers out there.
A series of advanced features are included in this software utility, with Outlook .MSG file parser, TNEF parser (winmail.dat), and S/MIME being among them and offering increased flexibility.
Parsing and receiving email messages should raise no issues whatsoever, considering that the EAGetMail .NET namespace comprises classes you could turn to when working on your projects. What’s more, parsing encrypted messages as well as winmail.dat should be an approachable task. It is also worth pointing out that using the classes in this namespace in C#, VB.NET, ASP.NET, and more, is possible.
In order to get a better idea of EAGetMail POP3 & IMAP4 .NET Component’s capabilities, you may want to know that support for Embedded Images, TLS, SSL, Live OAUTH, Gmail OAUTH, S/MIME, HTML, and more is provided.
EAGetMail POP3 IMAP4 .NET Component Crack Free Download (2022)
EAGetMail POP3 IMAP4 .NET Component License Keygen
91bb86ccfa
EAGetMail POP3 IMAP4 .NET Component
What’s New in the?
System Requirements For EAGetMail POP3 IMAP4 .NET Component:
OS: Windows 7
CPU: 2.4 GHz
Memory: 2 GB RAM
Hard disk space: 8 GB available space
Game Disk Space: 1.2 GB
Controller: Joystick (XBox 360 compatible)
Screenshots:
Game Overview
1. Kingdom Under Fire
2. With the release of Kingdom Under Fire: Heroes I, King, you now have the opportunity to command and direct the most feared force in the world. Whether you are a brand new recruit and just need to get the | https://madisontaxservices.com/eagetmail-pop3-imap4-net-component-crack-download | CC-MAIN-2022-40 | refinedweb | 321 | 69.58 |
I've spent way too much time over the last four years reading and writing frame buffer memory. Admitting that I have this problem is, for me, cleansing. Almost spiritual. Let me share my enlightenment. And if you're doing rendering using the Game Kit, or working with off screen bitmaps, you might even find my confessions interesting.
The first thing that you realize when you use a fast machine (like my beloved 225 MHz PowerPC) is that PCI is a pain. This thing is so slow compared to the speed of the CPU that thinking a little bit about the way you will access memory can have some nice paybacks.
For the next few examples, let's assume that the frame buffer is in 24-bit mode and has a width of 800 pixels.
The easiest way to draw a square 128 pixels wide is:
#define
BUFFER_BASE0x14000020 #define
ROWBYTE(800*4) void
test1() { ulong *
p; ulong
my_color; int
x; int
y;
my_color= 0x00ff0000; // a nice red color. for (
y= 0;
y< 128;
y++) {
p= (ulong*)(
BUFFER_BASE+ (
y*
ROWBYTE)); for (
x= 0;
x< 128;
x++) { *
p++ =
my_color; } } }
On my machine with a Twin Turbo video card, this piece of code runs in 3550 usecs. This is a bandwidth of about 18 MB/sec. If we run the same test using conventional memory, the code now runs in only 730 usecs -- about 5 times faster!! Excuse me, I have to get the phone.
I'm back. Moral #1: When you have a LOT of rendering to do, it's faster to render in an off screen bitmap and then blit the final result to the screen. This is even more apparent if you try to READ stuff out of the buffer. If we change the previous code into
for (
y= 0;
y< 128;
y++) {
p= (ulong*)(
BUFFER_BASE+ (
y*
ROWBYTE)); for (
x= 0;
x< 128;
x++) { *
p++ ^= 0xffffffff; } }
The execution time now goes up to a hugely 15100 microseconds, 4.5 times slower than the previous write only case. Say it not, reading the contents of a PCI frame buffer is a bad idea! In real memory, it takes only 800 microseconds. As you can see, the off screen method is the clear winner.
Back to the simple writing case. It turns out that writing doubles into the frame buffer helps the performance of the PCI transaction:
void
test1() { double *
p; double
temp_double; ulong
my_color; int
x; int
y;
my_color= 0x00ff0000; // a nice green color. *((ulong*)&
temp_double) =
my_color; *(1 + (ulong*)&
temp_double) =
my_color; for (
y= 0;
y< 128;
y++) {
p= (double*)(
BUFFER_BASE+ (
y*
ROWBYTE)); for (
x= 0;
x< 128/2;
x++) { *
p++ =
temp_double; } } }
This one runs in 1970 usec—about 50% better than the one using 32 bits transfer!
If we unroll the loop...
for (
x= 0;
x< 128/8;
x++) { *
p++ =
temp_double; *
p++ =
temp_double; *
p++ =
temp_double; *
p++ =
temp_double; }
...we don't actually gain anything. This runs in exactly the same time as the non-unrolled version. This is because any overhead between the write instructions is hidden by the time taken to do the write. If you do some computation between writes, you may find that it is free. For example:
for (
x= 0;
x< 128/2;
x++) { *
p++ =
temp_double;
my_color+= (
x<<24) | (
x<< 8) ^
x; *((ulong*)&
temp_double) =
my_color;
my_color+= (
x<<24) | (
x<< 8) |
x; *(1 + (ulong*)&
temp_double) =
my_color; }
It looks busy. It is busy. But this thing still runs in EXACTLY the same time—so much for optimization! (By the way, this random piece of code looks very nice if you run it a few thousand times, try it!)
Note that although the double write only needs to be aligned on a 4-byte boundary, you should stick with 8-byte alignment. 4-byte alignment carries an 80% performance penalty.
A few nice tricks
When doing graphic-intensive operations in 32-bit mode, you may find some of these functions useful. They're a collection of tricks to speed up common blending operations. Have fun decoding them!
The first one blends two RGB values...
The trivial implementation would be :
ulong
calc_blend(ulong
color1, ulong
color2) { ulong
result;
result= ((1 + ((
color1>> 24) & 0xff) + ((
color2>> 24) & 0xff)) >> 1) << 24;
result|= ((1 + ((
color1>> 16) & 0xff) + ((
color2>> 16) & 0xff)) >> 1) << 16;
result|= ((1 + ((
color1>> 8) & 0xff) + ((
color2>> 8) & 0xff)) >> 1) << 8;
result|= ((1 + ((
color1) & 0xff) + ((
color2) & 0xff)) >> 1); return
result; }
The fast version is:
ulong
calc_blend(ulong
color1, ulong
color2) { return ((
color1& 0xFEFEFEFE)>>1)+ ((
color2& 0xFEFEFEFE)>>1)+ (
color1&
color2& 0x01010101L)); }
A fast color addition with clipping to 0xff:
ulong
calc_add(ulong
c1, ulong
c2) { return ((((((
c1^
c2)>>1)^((
c1>>1)+ (
c2>>1))) & 0x80808080L)>>7)*0xFF)|(
c1+
c2); }
Now subtraction:
ulong
calc_sub(ulong
c1, ulong
c2) {
c2^= 0xFFFFFFFFL; return ((((((
c1^
c2)>>1)^((
c1>>1)+(
c2>>1))) & 0x80808080L)>>7)*0xFF) & (
c1+
c2+1); }
By the way, thanks to Pierre for some of these tricks!
You know how you read magazine articles that start, "By the time you read this..."
Well, it's Thursday before our developer's conference and I'm sitting here making up things that will sound OK by the time you read this next week. How about starting with things we do know.
We now have accelerated 3D support for OpenGL®!! How the heck? Well, start with the Diamond Monster3D board, add the current 2.4 glide library support from 3Dfx, and mash on the freely available Mesa OpenGL® implementation, and there you have it. I'm telling you, you have done 3D until you've done 3D with a nice cheap hardware accelerator.
This will work with any of the 3Dfx Voodoo based graphics cards, not Voodoo Rush at the moment. Go buy one of these cards (~$200), plug it into your Mac, and have at it. If you are at the developer's conference, you'll see this in action, if not, you'll just have to wait.
Speaking of the conference, what else will you see? Well, since you won't see this until next week anyway, you'll see a whole bunch of other nifty graphics stuff, as well as a glimpse of what I fondly call WetTV. Not to dwell on my favorite Bt848 subject, but I'm programming and I can't stop!! Have you ever watched television where channel changes have movie transitions? You will need a towel to run this application because after you do, you will find that you have peed your pants with excitement. Bold statements? Yes of course, this stuff is kicking and you won't see it on XYZ operating systems because those programmers simply aren't as motivated. They're too busy poo pooing how little chance we have of succeeding.
My brother has this favorite little statement, "We're going to go eat from the big dog's bowl while he's not looking."
So here we are. Some software available. Some interesting hardware support, including a new processor, and hungry agile programmers who are willing to take advantage of superior technology. Thanks for all your support.
So what kind of support do you get from us? Let me tell you a story. We were at the local sandwich shop waiting for our food. Geoff had just come from the local hardware store where he had bought some stain or some such. He was trying to balance the can on his head, but lacking enough hair, it didn't stay too well and ended up on the floor. Boy that stuff spreads fast!! He and one of the other customers quickly mopped it up while Brian and I quickly got our food and distanced ourselves from the scene. To redeem himself, he did the 3Dfx support.
That's the kind of tech support personnel we have around here! A little fool hardy, but we can program up a storm when the need arises. I hope you all benefit from the fruits of our labors.
Six months ago, we exited the hardware business. We loved our BeBox very much, but we love to create opportunities for BeOS developers even more. Our software running on Power Mac compatibles was warmly received. As a result, BeOS developers could see a much broader installed base than the one provided by BeBoxen. Apple, Power Computing, Motorola and Umax were very helpful in making this possible.
Once it became clear we were in the business of adding value to popular hardware, the next logical step didn't require much thought. We claimed and proved the portability of our OS; porting it to Intel Architecture systems made sense. At a time when our engineering resources were stretched by our work on the major improvements in the Preview Release, Intel helped us to get started by providing engineers who, for a while, came to work in our cramped cubicles. Their contribution to this important project is gratefully acknowledged: We wouldn't be this far along without their excellent work.
Now, such a move raises many new questions. I'll answer a few today, leaving the rest to other columns—or BeWeek columnists.
First, does this put us more squarely in competition with Microsoft? In other words, are we even crazier than previously perceived?
Crazy, perhaps, but not suicidal. Actually, as one of our co-founders, Steve Sakoman, remarks, one must be crazy to do something original, as opposed to derivative. But not all craziness is productive. What do we have to gain by competing more directly with Microsoft?
Let's start by noting that, more and more, when you write a line of C++, or Java code, you could be competing with Microsoft, whose strategy could be summarized by one word: Everything.
But universality has its drawbacks. Windows 95 is an excellent general purpose desktop OS. Windows NT is a holy terror in the enterprise market. Are we going to be flattened by these two steamrollers? For us, the idea is to exist to the left or right of them, not in their path. Put another way, our focus is the digital media content creation space.
The situation opposes a dedicated tool, the BeOS, versus respected general purpose platforms. Some developers and users will prefer the benefits of specialization, others will pick the general purpose platform. Historically, this leads to 75-25%, or 80-20% situations.
Let's continue by noting many advanced PC users already run more than one OS. Popular software tools called boot managers provide for such coexistence: Windows NT offers its own, there is the extremely successful System Commander and Lilo, a very nice Linux utility. We're proud of our work, we see incredible potential in our OS, but the logical consequence of specialization is coexistence with general purpose products, as opposed to attempting to displace them with a (yet) unproven OS such as ours.
Second, does this mean we are abandoning the PowerPC? Again, no. Why should we do this at the very moment our OS could run on most personal computers? As we have said in the past, we are processor agnostic.
Agnostic, and hopeful. Comparing the performance between Intel-based PCs and PowerPC systems, we see unrealized potential in the PowerPC space. In the Intel market, competitive forces have honed many parts of the system, chip sets, bus, memory, disks, graphic accelerators...
As a result, with roughly equivalent Pentium and PowerPC processors, system performance tends to be superior on the Intel Architecture side. It's not always pretty, but advances such as USB and FireWire are about to remove many scars from the past—and it is fast and inexpensive. A system based on an Intel dual Pentium Pro motherboard, with high-speed SCSI storage, Ethernet, sound, nice video, etc., can be had for about $2,500, monitor included.
On the other hand, until recently, the Mac market has been deprived from the competitive forces which make hardware subsystems more efficient and less expensive. This is where we see an opportunity for the PowerPC. There is a chance the much awaited CHRP will finally become a reality. If it does, an active Mac clone industry will finally actualize the "power" in PowerPC.
I wrote above we were processor agnostic and hopeful. We aren't blind either. Apple is still struggling with its licensing dilemma. As everyone else, I've read the New York Times story reporting Apple Board's statement to clone makers they were, in essence, no longer wanted. I hope the NYT was misinformed but I'm struggling with the knowledge John Markoff, the reporter, is well connected and very careful.
We'll see. In the mean time, we have to take care of our business, which is to expand opportunities for BeOS developers. That's what we are doing with the Intel Architecture version. | http://www.haiku-os.org/legacy-docs/benewsletter/Issue2-31.html | crawl-001 | refinedweb | 2,117 | 71.75 |
msys.shareSet
Last updated March 2020
Name
msys.shareSet — Associate a value with a keystring in the global share space
Synopsis
msys.shareSet(keystring, value);
keystring: string value: string
Description
This function associates a value with
keystring in the global share space. This association is thread-safe and consistent across all Lua interpreters and co-routines. The act of setting the value is thread safe and does not require an explicit mutex, but it is recommended that you use a mutex to coordinate modification of the value.
value may be a number, string, boolean or nil value.
Note
This function has been made obsolete by the data sharing features introduced in version 3.2. For more information see msys.runInPool.
... incrementing a counter in a thread safe manner msys.lock("counter-example"); local c= msys.shareGet("my-counter"); if c == nil then c = 0; end msys.shareSet("my-counter", c + 1); msys.unlock("counter-example");
Because this function is in the
msys namespace, an explicit
require is not necessary.
See Also
Was this page helpful? | https://support.sparkpost.com/momentum/3/3-reference/lua-ref-msys-share-set | CC-MAIN-2022-05 | refinedweb | 175 | 60.21 |
With the release of React 17 we also had to change the way we import React:
To clarify:.
— Dan Abramov (@dan_abramov) September 23, 2020
Kent C. Dodds goes over all ways to import React into your code, and explains why the good ole
import React from "react" no longer works and why he went for
import * as React from "react"
Importing React Through the Ages →
That screenshot shows the exact problem with modern JS. Who can still follow?
That’s why it’s a breaking change + is explicitly mentioned the release notes + comes with a migration script to take care of it for you.
The only thing that’s really changed is that the “ESModules default import” approach (third one) no longer works. Before you could use all ESModules variants, now you can’t. Note that this only affects React, other JS projects are not affected by this. | https://www.bram.us/2020/12/07/the-several-ways-to-import-react/ | CC-MAIN-2021-17 | refinedweb | 148 | 70.13 |
Go is great, but I just had to do something about its borderline insane dependency management.
Being able to do
import github.com/foo/bar is cute, but there’s very little guarantee that dependencies won’t change overnight, and no practical way of pinning stuff to a specific version/revision. Having a strong desire to avoid a repeat of my early experiences with NodeJS, where stuff like
express broke all of my code a few weeks down the road, I started looking for solutions early on.
But all the approaches I came across required third-party tools that are entirely too much hassle to set up and use reproducibly, so after a little experimentation, I converged on a rather lazy approach that mimics my usual Python pattern:
I set
GOPATH to a
vendor directory inside each project repository,
go dep into that and clean out the
.git/
.hg folders in order to commit all the dependencies together with the project.
It’s a little wasteful in terms of storage, but perfectly doable for my ongoing projects and ensures that I’ll be able to rebuild things six months down the line. Plus it’s trivial to automate with a
Makefile like so (which also makes it easy for me to do cross-compiles):
export GOPATH:=$(shell pwd)/vendor export PATH:=$(PATH):$(GOPATH)/bin BINARY=foobar $(BINARY): *.go go build -o $(BINARY) deps: mkdir -p vendor go get github.com/rakyll/globalconf go get github.com/efarrer/iothrottler find vendor -name .git | xargs rm -rf find vendor -name .hg | xargs rm -rf git add vendor/src clean: rm -f $(BINARY) go fmt *.go pi: GOARCH=arm GOARM=6 go build -o $(BINARY)-rpi synology: GOARCH=arm GOARM=5 go build -o $(BINARY)-syno
So to add a dependency I just add another
go get line, do a
make deps and all the required code is added to the project. To update a dependency, I just remove its files and do it again. A trifle unsubtle, for sure, but it works, and has the additional side benefit of my being able to organize my projects anywhere on the filesystem without having to submit to Go’s “there can be only one way to organize your code” silliness.
Since
make is available pretty much everywhere and not something that is likely to go out of fashion (outside the NodeJS world, that is, where they keep reinventing it), I think this solves my problems for the foreseeable future – or until Go standardizes on something at least as simple to use and maintain. | http://taoofmac.com/space/blog/2014/08/18/2300 | CC-MAIN-2016-50 | refinedweb | 429 | 56.18 |
(The code examples in this post are also available here.)
Although I have already written something on binary exponentiation, as it applied to modular exponentiation, there’s plenty more to be said about it in more general settings. Basically, today we are after computing the n-th power of a, but a need not be an integer, rational, real or even complex number, but can be any more general mathematical object that can be raised to a power, as a square matrix or a polynomial could be…
For an n-th power to exist, the object being exponentiated must fulfill certain conditions, which can basically be summarized in belonging to a more general set that has a well-behaved multiplication operation defined. Good behavior can be translated into closure and associativity, which in mathematical slang can be expressed as the object belonging to a semigroup. This will often mean that the object belongs to a monoid, and even to a ring or rng… But I’ll follow V.I. Arnold‘s advice, and not get too carried away with the abstract generalizations, so enough said: the thing must be multipliable, and the result must be of the same kind.
Defining Multiplication
Because we are dealing with general mathematical objects, we first need to define the multiplication operation. There are two ways of dealing with this in python. To work on an example, say we want to deal with 2×2 matrices. We could define a
Matrix2x2 class, and write a
__mul__ method for it, so that whenever we write
a*b, what gets evaluated is
a.__mul__(b). For the same price, I’ve thrown in an
__add__ method…
class Matrix2x2(object) : def __init__(self,elements = None) : if elements : self._data_ = elements[:4] else : self._data_ = [0] * 4 def __repr__(self) : as_string = [str(j) for j in self._data_] str_length = [len(j) for j in as_string] longest = max(str_length) for j in xrange(4) : as_string[j] =' '*(longest - str_length[j]) + as_string[j] ret = 'Matrix2x2 object:' for j in xrange(2) : ret += '\n[ %s %s ]' % (as_string[2*j], as_string[2*j+1]) return ret def __mul__(self, b) : ret = [self._data_[0]*b._data_[0] + self._data_[1]*b._data_[2]] ret += [self._data_[0]*b._data_[1] + self._data_[1]*b._data_[3]] ret += [self._data_[2]*b._data_[0] + self._data_[3]*b._data_[2]] ret += [self._data_[2]*b._data_[1] + self._data_[3]*b._data_[3]] return Matrix2x2(ret) def __add__(self, b) : return Matrix2x2([self._data_[j] + b._data_[j] for j in xrange(4)])
Or if we don’t want to go through the hassle of dealing with objects, we can agree with ourselves in keeping the matrix’s data in a list in row-major order, and define a standalone multiplication function…
def mat_mul(a, b) : """ Returns the product of two 2x2 square matrices. Computes the product of two 2x2 matrices, each stored in a four element list in row major order. """ ret = [a[0]*b[0] + a[1]*b[2]] ret += [a[0]*b[1] + a[1]*b[3]] ret += [a[2]*b[0] + a[3]*b[2]] ret += [a[2]*b[1] + a[3]*b[3]] return ret
Direct Multiplication
To set a baseline for performance, the starting point has to be the most direct implementation of exponentiation: repeated multiplication. There really isn’t much mistery to it…
import nrp_base @nrp_base.performance_timer def direct_pow(a, n, **kwargs) : """ Computes a**n by direct multiplication. Arguments a - The object to be exponentiated. n - The integral exponent. Keyword Argument mul - A function taking two arguments of the same type as a, and returning their product. If undefined, a's __mul__ method will be used. """ mul = kwargs.pop('mul',None) ret = a if mul is None : mul = lambda x,y : x*y for j in xrange(n-1) : ret = mul(ret,a) return ret
The Two Flavors of Binary Exponentiation
OK, so now we are ready for the fun to begin… The basic idea behind speeding exponentiation up is that a4 can be computed with two, instead of three, multiplications, if rather than doing it as a4 = a·a·a·a, we do it as a2 = a·a, a4 = a2·a2, storing the intermediate result for a2…
To expand this idea to exponents other than 4 we basically need to write the exponent in binary. Examples are great for figuring out this kind of things, so we’ll take computing a19 as ours. Knowing that 19 in binary is 10011, we now have a choice on how to proceed, which basically amount to start using the bits of the exponent from the least significant one, or from the most significant one…
Least Significant Bit First
That 19 in binary is 10011 can also be interpreted as 19 = 20 + 21 + 24, and so a19 = a20·a21·a24… The algorithm then is pretty straightforward:
- start computing sequentially from j = 0 the values of a2j, where each new value is the square of the preceding one,
- when the first non-zero bit is found, set the return value to the corresponding a2j value,
- for subsequent non-zero bits, multiply the return value by the corresponding a2j value,
- once all bits of the exponent have been searched, the return value holds the sought value.
If the exponent is n, then there will be log2 n squarings, to compute the a2j values, plus one multiplication less than there are 1’s in the binary expansion of the exponent.
Most Significant Bit First
It is also possible to write a19 = ((a23·a)2)·a. While it is easy to verify that is the case, it may be harder to see where does it come from. The algorithm is as follows:
- Take the exponent bits from most to least significant,
- since the first bit is always a 1, set the return value to a,
- for every bit processed, first square the return value, and then, if the bit is a 1, multiply the return value by a,
- again, once the last bit is used, the return value holds the sought value.
The analysis of the algorithm is similar to the previous one: there will again be log2 n squarings, and the same number of multiplications as well.
These second flavor has one clear disadvantage: there’s no simple way to generate the bits of a number from most to least significant. So this approach requires computing and storing the bits from least to most significant, and then retrieve them in inverse order. No that it is anything too complicated, but there are additional time costs involved.
So why would one even worry about this scheme then? Well, it also has a potential advantage: the multiplications performed always involves the original object being exponentiated. This can prove beneficial in two different ways:
- it lends itself better for optimization of particular cases, and
- if the original element involves small numbers, but the end result involves large numbers, the multiplications are usually faster than in the previous algorithm.
To see the differences with examples, it is better to first write the python code…
@nrp_base.performance_timer def bin_pow(a, n, **kwargs) : """ Computes a**n by binary exponentiation. Arguments a - The object to be exponentiated. n - The integral exponent. Keyword Argument mul - A function taking two arguments of the same type as a, and returning their product. If undefined, a's __mul__ method will be used. sqr - A function taking a single argument of the same type as a, and returning its square. If undefined, mul(a,a) will be used. To use a method of the object's class, use sqr=ClassName.function_name. lsb - Set to True to use least significant bits first. Default is False. msb - Set to True to use most significant bits first. Overrides lsb. Default is True. """ mul = kwargs.pop('mul',None) sqr = kwargs.pop('sqr',None) lsb = kwargs.pop('lsb',None) msb = kwargs.pop('msb',None) if mul is None : mul = lambda x, y : x * y if sqr is None : sqr = lambda x : mul(x, x) if lsb is None and msb is None : msb = True lsb = False elif msb is None : msb = not lsb else : lsb = not msb if msb : bits = [] while n > 1 : # The last bit is always a 1... if n & 1 : bits += [1] else : bits += [0] n >>= 1 ret = a while bits : ret = sqr(ret) if bits.pop() : ret = mul(ret,a) else : val = a while not n & 1 : n >>= 1 val = sqr(val) ret = val while n > 1: n >>= 1 val = sqr(val) if n & 1 : ret = mul(ret,val) return ret
Taking
bin_pow for a Ride…
To get a better grip on how the algorithm performs, we’ll take a very simple matrix, which we will find again in a future post, when we discuss Fibonacci numbers…
>>> a = Matrix2x2([1,1,1,0])
>>> a
Matrix2x2 object:
[ 1 1 ]
[ 1 0 ]
So lets raise it first to a small power, and see how the two algorithms perform…
>>> val = bin_pow(a,10,lsb=True,verbose=True,timer_loops=100)
Call to bin_pow took:
2.84952e-05 sec. (min)
0.000205613 sec. (max)
3.363e-05 sec. (avg)
0.000178629 sec. (st_dev)
>>> val = bin_pow(a,10,msb=True,verbose=True,timer_loops=100)
Call to bin_pow took:
3.12889e-05 sec. (min)
5.16825e-05 sec. (max)
3.32891e-05 sec. (avg)
2.93951e-05 sec. (st_dev)
Not many surprises here, as the algorithm having to store and retrieve bits is a little slower than the other. But lets see what happens if we scale things…
>>> val = bin_pow(a,1000000,lsb=True,verbose=True)
Call to bin_pow took 2.599 sec.
>>> val = bin_pow(a,1000000,msb=True,verbose=True)
Call to bin_pow took 1.76194 sec.
This sort of shows that the multiplication thing can be very relevant. A last little experiment gives more insight into the workings of this…
>>> 2**20
1048576
>>> val = bin_pow(a,2**20,lsb=True,verbose=True)
Call to bin_pow took 1.95651 sec.
>>> val = bin_pow(a,2**20,msb=True,verbose=True)
Call to bin_pow took 1.90171 sec.
Funny, isn’t it? Why would it be that the time differences are so much smaller now, even though the exponents are roughly the same? This other times may help answer that…
>>> val = bin_pow(a,2**20-1,lsb=True,verbose=True)
Call to bin_pow took 2.61069 sec.
>>> val = bin_pow(a,2**20-1,msb=True,verbose=True)
Call to bin_pow took 1.89222 sec.
Got it now? 220 has a binary expression full of 0’s, 20 of them, preceded by a single 1. This means that neither algorithm is performing any multiplication, just squarings, so the performance is almost identical. On the other hand, 220-1 has a binary expression full of 1’s, 20 of them, with no 0 anywhere. This means that, although there will be one less squaring than for the previous case, there will be 19 multiplications more. And here’s where the
msb approach excels, because the involved multiplications are simpler. | https://numericalrecipes.wordpress.com/tag/binary-exponentiation/ | CC-MAIN-2017-13 | refinedweb | 1,842 | 59.03 |
Simple Unix tools
From HaskellWiki
Revision as of 15:06, 5 November 2011.
import Control.Monad.Instances import Data.List import Data.Char import Data.Maybe import Text.Printf import System.Environment -- First, two helpers io f = interact (unlines . f . lines) showln = (++ "\n") . show -- remove duplicate lines from a file (like uniq) uniq = nub -- Warning: Unix uniq discards *consecutive* dupes. But 'nub' discards all dupes. -- -- And our main wrapper main = do who <- getProgName maybe (return ()) id $ lookup who $ [("blank", io blank ) ,("cksum", interact (showln . cksum) ) ,("clean", io clean'' ) ,("echo" , interact id ) ,( ) ]
1 How to run; ln -s UnixTools cat"
) and then run those commands (
"./echo foo | ./cat"
would produce output of "foo"). | https://wiki.haskell.org/index.php?title=Simple_Unix_tools&diff=42758&oldid=6217 | CC-MAIN-2015-32 | refinedweb | 112 | 71.82 |
Thanks for all your comments. I will conclude to my first idea: tests
need to be run 2 times (one with traces to OFF or INFO, and the other
one with traces to ALL)
Regards,
Benoît.
Le 13-02-2014 10:25, Stephen Connolly a écrit :
> On 13 February 2014 09:23, Stephen Connolly <stephen.alan.connolly@gmail.com
>
>> wrote:
>
>> because if you enable ALL then the other side of the if will not be followed... you
need to combine runs with ALL and NONE to get both sides of the logging branches. Another
point that the "slf4j is the solution" camp misses is sometimes the log message needs evaluation
in order to generate the message. For example you might want to extract a meaningful string
representation out of a complex data structure... with a @CheckFoNull chain of methods to
dance through. While slf4j and other message formatting saves you a lot of the cases where
an `if (debug) { log }` is needed, it does not and can not eliminate all cases. And then there
is the final point where you are dealing with a mutable data structure (this is of more concern
with an async logger framework)... We had a case whereby the logging statements where logging
the object in a state which it could not possibly be in... because the log formatting and
hence toString() evaluation was taking place in a different thread async (to
prevent logging from slowing down the main code path)... so by the time the log message was
being formatted the object state had mutated and from if (!caller.isAuthenticated()) { logger.debug("Starting
authentication flow for caller {}", caller); ... } if (StringUtils.isEmpty(caller.getDisplayName)
&& StringUtils.isNotBlank(caller.getCallerId()) { logger.debug("Looking up display
name of {} using callerId {}", caller, caller.getCallerId()); ... caller.setDisplayName(displayName);
logger.debug("Set display name of {} to "{}" based on caller id lookup", caller, displayName);
... } you would get DEBUG: Starting authentication flow for caller Caller[id=0x67267, authenticated=true,
callerId=+14325551234, displayName="Jim Smith"] DEBUG: Looking up display name of id=0x67267,
authenticated=true, callerId= +14325551234, displayName="Jim Smith" using callerId +14325551234
DEBUG: Set display name of Caller[id=0x67267, authenticated=true, callerId= +14325551234,
displayName="Jim Smith"] to "Jim
Smith" based on caller id lookup which from the code should never happen... what you expect
is something like DEBUG: Starting authentication flow for caller Caller[id=0x67267, authenticated=false,
callerId=+14325551234, displayName=null] DEBUG: Looking up display name of Caller[id=0x67267,
authenticated=true, callerId=+14325551234, displayName=null] using callerId +14325551234 DEBUG:
Set display name of Caller[id=0x67267, authenticated=true, callerId= +14325551234, displayName="Jim
Smith"] to "Jim Smith" based on caller id lookup But because by the time the DEBUG message
was formatted we had mutated the object state already the logging statements were giving the
wrong output... the fix was to change the code to if (!caller.isAuthenticated()) { if (logger.isDebug())
logger.debug("Starting authentication flow for caller {}", caller.toString()); ... } if (StringUtils.isEmpty(caller.getDisplayName)
&& StringUtils.isNotBlank(caller.getCallerId()) { if (logger.isDebug())
logger.debug("Looking up display name of {} using callerId {}", caller.toString(), caller.getCallerId());
... caller.setDisplayName(displayName); if (logger.isDebug()) logger.debug("Set display name
of {} to "{}" based on caller id lookup", caller.toString(), displayName); ... } In such cases
you actually *have to* wrap the logging statement and force the .toString() when logging
>
> Well there are other solutions such as switching to immutable objects...
> but if you don't have the ability to make such a change...
> What a framework like slf4j and the other message formatting based frameworks gives you,
however, is the default behaviour is lazy toString and you can add the branches for those
cases where you need them. -Stephen P.S. this logging example is a rephrase of the actual
logging code which using a home baked framework and I have paraphrased the code somewhat,
since this was actually a state machine... but the same issue can occur in any multi-threaded
code base where you are logging mutable objects and expecting the log formatter to evaluate
the toString() On 13 February 2014 08:47, Baptiste Mathus <ml@batmat.net> wrote: My
first feeling is that not much time should be spent on that issue, logging isn't going to
take a lot of points of percentage down, having ~95% would already be great (but maybe you
already have). Anyway, on the other hand, if what you want is to get code coverage, why not
just enable the ALL logging level when recording code coverage and go ahead? Then, if the
verbosity if an issue, simply plug something like an existing or custom no-op/Null appender
[1]? That might sound the simplest solution, isn't it? [1]
[1] My 2 cents 2014-02-13 7:13 GMT+01:00 Benoît Berthonneau <benoit@berthonneau.com>:
Ron, Mirko, Kevin, Thanks for your feedback : you're right with Slf4j implementation. Unfortunately,
it is not. It is a home made logger interface implemented by Log4j. Benoît Le 12 févr. 2014
à 23:25, Ron Wheeler <rwheeler@artifact-software.com a écrit : Not really a Maven issue
but if you do your logging like this: package com.myco.testapp; import org.slf4j.Logger; import
org.slf4j.LoggerFactory; public class MyClass{ private Logger _logger=LoggerFactory.getLogger(this.getClass());
logger.debug("blah {} in the loop that contains {}", i, max); } You can sort out the enabling
of logs and destination of your logging
by
> severity and class(I think by package as well) in the log configuration
at
> run-time. Ron On 12/02/2014 4:20 PM, Mirko Friedenhagen wrote: Hello Benoit, Kevin is
right, using slf4j[0] one would use sth. like: logger.debug("blah {} in the loop that contains
{}", i, max); No need for iffing :-). [0] [2] Regards Mirko
-- [3] [4] (
[5]) [6] On Wed, Feb 12, 2014 at 10:10 PM, Kevin Krumwiede
<kjkrum@gmail.com
wrote:
> It does matter which implementation. The main reason it was
recommended to
> check the logging level was because string concatenation can be
expensive,
> and you want to avoid doing it for a message that won't be logged.
But if
> you're using a logging API like slf4j that uses parameter
replacement
> tokens in the message string, if the message isn't logged, the
replacement
> won't be performed and the call will be cheap. On Feb 12, 2014 1:57 PM, "Benoît Berthonneau"
<
benoit@berthonneau.com>
> wrote: Hi Paul, Don't think that I could play with exclusions. Here is an example : *A
Unit Test :* *The tested class with ALL traces activated:* *And the same tested class with
INFO traces activated:* -----Message d'origine----- De : paulus.benedictus@gmail.com [mailto:
paulus.benedictus@gmail.com]
> De la part de Paul Benedict Envoyé : mercredi 12 février 2014 21:36 À : Maven Users
List Objet : Re: Code coverage with debug logs: 100% branch coverage not possible?... IIRC,
there should be an option in Emma/Cobertura that allows you
to
> exclude coverage on certain classes. So if you can exclude your
log4j
> classes (you don't really want to test your logging, do you?), then
you
> should be able to raise your percentage. On Wed, Feb 12, 2014 at 2:30 PM, Benoît Berthonneau
<benoit@berthonneau.com>wrote: Hi all, I need your opinion/way to tackle the following
problem: In many projects we use a Logger (doesn't matter which implementation). It is often
recommend to test if the debug level
is
> activated before logging a debug trace like the following: if (logger.isDebugEnabled())
{ logger.debug("blah " + i + " in the loop that contains " +
max);
> } Now when you run unit tests on this kind of code you need to make
a
> choice: run tests with INFO level or run tests with ALL traces activated.
I
> choose the second option in order to: * Check that debug traces doesn't throw unwanted
exception
(like
> NPE) * Have a better code coverage in term of covered lines But in term of branches coverage
we could never have a 100% :( To me the only way to cover this is to run the tests suite 2
times:
> one with INFO traces configured, and another one with ALL traces activated. Did you face
this issue and how did you solve it ? Thanks, Benoît. -- Cheers, Paul
---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@maven.apache.org For
additional commands, e-mail: users-help@maven.apache.org -- Ron Wheeler
President Artifact Software Inc email: rwheeler@artifact-software.com -- Baptiste <Batmat>
MATHUS - [7] Sauvez un arbre, Mangez un castor !
nbsp;! <users-help@maven.apache.org>
Links:
------
[1]
[2]
[3]
[4]
[5]
[6]
[7] | http://mail-archives.apache.org/mod_mbox/maven-users/201402.mbox/%3C6fa00c7fead4fb6b61b247e7f3692283@berthonneau.com%3E | CC-MAIN-2015-22 | refinedweb | 1,425 | 53.41 |
16 June 2011 09:44 [Source: ICIS news]
SINGAPORE (ICIS)--Producers in ?xml:namespace>
Reliance Industries Limited (RIL), GAIL (India), Indian Oil and Haldia Petrochemicals cut the list prices for their LLDPE film by rupee (Rs) 1/kg (Rs1,000/tonne, $22.3/tonne), while their prices for LDPE film were cut by Rs4/kg
This is the second price reduction for the two products this month.
The new PE prices are at Rs74/kg
The price protections for all local PE purchases resumed on Thursday, after it was terminated on 2 June.
“We have to boost our customers’ confidence, otherwise they will not want to book new material,” a source close to GAIL said.
“There is price competition with imported material as well and to ease our high stock level, we have to introduce further price reduction,” a source close to Indian Oil said.
Discussions for imported LDPE, LLDPE and HDPE film on Thursday were heard at $1,520-1,600/tonne (€1,079-1,136/tonne) CFR (cost & freight) Mumbai, $1,270-1,300/tonne CFR Mumbai, and $1,300-1,340/tonne CFR Mumbai respectively, according to market sources.
($1 = Rs44.8, $1 = €0.71)
For more on eth | http://www.icis.com/Articles/2011/06/16/9469987/india-makers-cut-ldpe-lldpe-prices-by-up-to-rs4kg-hdpe-unchanged.html | CC-MAIN-2015-06 | refinedweb | 202 | 60.35 |
Last month, Brian Wilson published a survey on validation. He took the top 500 sites URI given by Alexa and sent them to the W3C Markup validator. Recently, W3C created a beta instance of html 5 conformance checker. Brian concluded that
32 of the 487 URLs passed validation (6.57%).
So today I decided to take the January 2008 list of web site and to send them to the beta instance of html 5 conformance checker. I created a very simple python script (As usual if you are in horror with my code, any kind suggestions to improve it is welcome). Be careful you will need to install httplib2. The file alexa.txt contains the list of uris, one by line. To be sure to check against html 5, I forced the html 5 doctype.
import httplib2 import time h = httplib2.Http(".cache") f = open("alexa.txt", "r") urllist = f.readlines() f.close() for url in urllist: # wait 10 seconds before the next request - be nice with the validator time.sleep(10) resp= {} url = url.strip() urlrequest = ""+url try: resp, content = h.request(urlrequest, "HEAD") if resp['x-w3c-validator-status'] == "Abort": print url, "FAIL" else: print url, resp['x-w3c-validator-status'], resp['x-w3c-validator-errors'], resp['x-w3c-validator-warnings'] except: pass
Before I give the results, repeat after me 10 times : html 5 Conformance checker is in beta, which means not stable and in testing. html 5 specification is a Working Draft, which means highly to change. The test is only on the home page of the site.
The January 2008 file contains 485 web sites. 23 (4.7%) could not be validated. Most of the time, the site was too slow. Only 4 (< 1%) sites were declared valid html 5 by the conformance checker. If Henri Sivonen could do the same thing with his instance of html 5 conformance checker that would help to know if my results are silly or in the right envelop.
11 thoughts on “Alexa Global Top 500 against HTML 5 validation”
I am surprised that there are sites which use the HTML5 doctype. All other sites fails HTML5 validation right from the doctype.
Please ignore my previous comment, I run a local v.nu instance, which does not override the document doctype as your does.
I set Preset to HTML5 (experimental), Parser to HTML5, but the original docype is still used.
Interesting… I thought one of the design principles of HTML5 was paving the cowpath and be backward-compatible, which, perhaps via simplistic logic, meant that anything conforming to an older version of HTML would still conform to HTML5. In other words, the number of sites passing the html5 check should be higher, not lower, than the dtd-based validation. At least that’s my assumption.
It would be interesting to look in more details at what errors made the html5 checking fail. That would clarify whether html5 has drifted from earlier versions of html, whether the checker has bugs, etc. Concatenate the XML output(s) of validation and look into that?
HTML5 makes non-conforming a lot of attributes that were conforming and popular in HTML 4.01 Transitional and even Strict.
I think HTML5 needs adjustment.
More than 99% (minus 4.7%, sorta) of sites without HTML 5 doctypes don’t validate as HTML 5? I think more tests may be needed here. Do pages with XHTML Strict tend to validate or not validate as HTML 4.01? Time permitting, maybe pages with HTML 5 doctypes could be checked for validation against HTML 5. ;)
In all seriousness, this is interesting information that’s difficult for me to apply to a question. Is this roughly the same as searching current pages for any use of a tag/attribute that is planned to change in HTML 5? Is it fair to read between the lines that this test indicates that over 99% of pages would need to be changed in some way to conform to HTML 5 as it stands?
Am I the only one who thinks this is utterly pointless. What exactly is the point of validating pages to a doctype they don’t even claim to implement? That’d be as stupid as calling valid HTML pages invalid because they aren’t well-formed XML, even when they make no claim to be.
Sure, most of these pages aren’t valid anything, but I’m sure most of them aren’t even aiming for HTML5. They’re much more likely to be some sort of HTML4 or XHTML or at least aiming for those two standards. (If, of course, the developers care at all. Sadly, many don’t.)
I support validation, and standards, and HTML5, but this is a waste of time and brains. I’m of the opinion that any page that triggers quirks mode should just be considered invalid anyway and ignored, which is probaly 486 (or so) of the 500 sites on the list.
@Levi,
HTML 5 is supposed to be designed by using the content as it is deployed on the Web. So to undestand the practices of users and tools, to try to not create too much discrepancy.
The goal of this validation was to show that in fact, switching to html 5 will require a lot of efforts from users. Do not forget that html 5 is a moving target, so this study, which didn’t take a long time (just the time to develop the script ;) ), could be run again anytime depending on the status of html5.
muy interesante tu articulo, Un buen ranking en Alexa siempre es una buena carta de presentación y aunque no es representativo y fiable al 100% indica que estamos haciendo las cosas bien en cuanto a nuestra página web
I support HTML5 and, of all industries, ours is certainly one where verything is constantly being imrpoved and upgraded. While some may argue that HTML5 is being pushed too far ahead of it’s development maturity I’m glad to see that things are being driven forward!
We have created sites that meet the current HTML5 standards and it did not take an overwhelming effort.
@Karl,
The Conformance Checker has improved greatly since your comment. Either version. Perhaps Brian Wilson would run a new report with the current Alexa 500: how interesting would the results be? compared with the previous report.
Just curious as to how many errors the top 100 online business based on revenue receive when run through W3C validation?
What’s the point of this again? | http://www.w3.org/blog/2008/09/top-500-html5-validity/ | CC-MAIN-2015-35 | refinedweb | 1,093 | 72.66 |
So I just scheduled an upcoming attempt at the Developing Applications using Cisco Core Platforms and APIs (DEVCOR 350-901) exam.
It's coming up quick in two weeks here & I'm starting to do some review / final prep before taking the exam.
Why does this matter? Well - I plan on doing a few write-ups & videos on some of the content I'm studying. There are a lot of people diving into the DevNet exams, and I want to do what I can to help other people succeed.
All that being said, check back here over the next few weeks - or subscribe on YouTube - to see the additional content that will follow. While this specific blog doesn't cover much from the exam blueprint, it's the beginning a simple project I'll be using in the further content.
Getting Started with Scrapli
For this project I opted to start with scrapli, and possibly migrate to using RESTCONF later on in the process. Mostly this was an excuse for me to try out scrapli, as I've heard a few people using it recently & was interested.
Scrapli is a screen scraping module for Python. If you're not familiar with screen scraping, it's the process of connecting to something via telnet/ssh/etc, then literally scraping or dumping the contents of the screen. There are other modules that do this as well, like paramiko, netmiko, or expect scripting.
In networking, too many of our devices still rely on CLI and don't have proper API endpoints. We're working on it, but yet still a ways from having it everywhere. So in the meantime, we still need screen scraping for automation.
On the whole, this isn't necessarily a bad thing. For example, most network engineers are very familiar and competent with the CLI of any network operating system. It's easier to jump into the world of automation if you can start with something you know, the CLI. It's harder to force someone to start their automation journey by giving up everything they know and shoving REST APIs at them.
Okay - enough rambling. Let's get scrapli installed and see what it can do.
Installing the module
Easiest part of the whole project. Install with pip:
pip install scrapli
Next we'll go ahead & import into our script.
Scrapli supports quite a handful of operating systems (including a few non-Cisco platforms as well!). In the case of my project though, I'm only using Cisco IOS-XE switches - so we'll only import the scrapli driver for that.
from scrapli.driver.core import IOSXEDriver
Connecting to a Device
Okay - now that we're all setup with the module, it's time to get working!
First thing, we need to authenticate to our device. Building off of the example code from the scrapli page - we'll create a short dictionary of authentication parameters first:
switch = { "host": "10.1.1.1", "auth_username": "net_api", "auth_password": "net_api_pass", "auth_strict_key": False } cli = IOSXEDriver(**switch) cli.open()
Once we build out dictionary, we'll use **switch to unpack our key/value pairs into the IOSXEDriver object & assign it to a variable called cli. Then, all we need to do is call cli.open() and scrapli will open a connection to our target device.
Now we can run any command we want by calling cli.send_command():
sh_int = cli.send_command("show interface") print(sh_int.output)
So in the above example, I want to issue a show interface - then print the output.
What we get is shown below:
GigabitEthernet1/0/1 is up, line protocol is up (connected) Hardware is Gigabit Ethernet, address is 78bc.1a81.e101 (bia 78bc.1a81.e101) Description: Test Port 00:00:11, output 00:00:03, output hang never Last clearing of "show interface" counters never Input queue: 0/2000/0/0 (size/max/drops/flushes); Total output drops: 198 Queueing strategy: fifo Output queue: 0/40 (size/max) 5 minute input rate 9000 bits/sec, 11 packets/sec 5 minute output rate 2066000 bits/sec, 221 packets/sec 2647548 packets input, 371883264 bytes, 0 no buffer Received 6985 broadcasts (6757 multicasts) 0 runts, 0 giants, 0 throttles 0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored 0 watchdog, 6757 multicast, 0 pause input 0 input packets with dribble condition detected 50905390 packets output, 60134059101 bytes, 0 underruns 0 output errors, 0 collisions, 2 interface resets 0 unknown protocol drops 0 babbles, 0 late collision, 0 deferred 0 lost carrier, 0 no carrier, 0 pause output 0 output buffer failures, 0 output buffers swapped out [**Output Truncated**]
What's that look like? Exactly the same output we would get if we entered show interface on the command line ourselves! (Only Gig1/0/1 shown here to keep this short & clean)
Using Cisco Genie to Parse CLI Output
So what if we wanted to pull a list of every interface on the switch? Maybe tally how many ports are connected vs down vs admin disabled? Or even check operational speeds & media types?
Well that's what I'm looking to do for this project.
Now at first it may seem like we have to use regular expressions to try & match the content we need from the output. However, there is an easier way!
Cisco Genie is an open source project, and part of the larger PyATS automated network testing suite. If you haven't looked at any of that yet, I would highly recommend you check it out.
So what's Genie do? It's a utility that handles all the output parsing for us. There are a ton of pre-existing parsers written, which handle all the hard work so we don't have to.
Best yet - scrapli has native integration into Genie. All we have to do is install one additional component:
pip install scrapli[genie]
And to make use of the power of Genie, we just need to pass our raw output to it.
So our new code will look like this:
sh_int = cli.send_command("show interface") sh_int_parsed = sh_int.genie_parse_output() print(sh_int_parsed)
That's it. And now, instead of that raw output - we get a native Python dictionary that's ready to consume by our script:
{ "GigabitEthernet1/0/1":{ "port_channel":{ "port_channel_member":False }, "enabled":True, "line_protocol":"up", "oper_status":"up", "connected":True, "type":"Gigabit Ethernet", "mac_address":"78bc.1a81.e101", "phys_address":"78bc.1a81.e101", "description":"Test Port", "delay":10, "mtu":1500, "bandwidth":1000000, "reliability":"255/255", "txload":"1/255", "rxload":"1/255", "encapsulations":{ "encapsulation":"arpa" }, "keepalive":10, "duplex_mode":"full", "port_speed":"1000mb/s", "media_type":"10/100/1000BaseTX", "flow_control":{ "receive":False, "send":False }, "arp_type":"arpa", "arp_timeout":"04:00:00", "last_input":"00:00:05", "last_output":"00:00:08", "output_hang":"never", "queues":{ "input_queue_size":0, "input_queue_max":2000, "input_queue_drops":0, "input_queue_flushes":0, "total_output_drop":198, "queue_strategy":"fifo", "output_queue_size":0, "output_queue_max":40 }, "counters":{ "rate":{ "load_interval":300, "in_rate":8000, "in_rate_pkts":11, "out_rate":1868000, "out_rate_pkts":205 }, "last_clear":"never", "in_pkts":2658450, "in_octets":372811780, "in_no_buffer":0, "in_multicast_pkts":6783, "in_broadcast_pkts":6783, "in_runts":0, "in_giants":0, "in_throttles":0, "in_errors":0, "in_crc_errors":0, "in_frame":0, "in_overrun":0, "in_ignored":0, "in_watchdog":0, "in_mac_pause_frames":0, "in_with_dribble":0, "out_pkts":51057453, "out_octets":60309072263, "out_underruns":0, "out_errors":0, "out_interface_resets":2, "out_collision":0, "out_unknown_protocl_drops":0, "out_babble":0, "out_late_collision":0, "out_deferred":0, "out_lost_carrier":0, "out_no_carrier":0, "out_mac_pause_frames":0, "out_buffer_failure":0, "out_buffers_swapped":0 } } }
This format makes our lives a lot easier. For example, let's say we wanted to determine the operational state of a port. Without the Genie integration, we would need to write some regex to comb through the raw output & find what we needed.
However, with Genie involved - its as easy as this:
print(sh_int_parsed['GigabitEthernet1/0/1']['oper_status'])
Collecting the Useful Bits
Now that we have everything in an easy-to-use format, all we need to do is write a few loops to run through our interface list & collect data.
The purpose of my script is to automate the collection of port utilization. For example, think about performing a switch refresh or some form of capacity planning scenario. You might need to inventory how many switches you have, how many ports are utilized vs how many are available, or count the number of copper vs fiber ports.
For this first iteration, we'll just collect the data then dump it out to a CSV file. As I mentioned earlier, this is just the start of a small project I'll be using to study for the DEVCOR exam - so this will be evolving into a web service later on.
The full script can be found here. But I've posted just a snippet of how we count the different interface characteristics:
# Count all Ethernet interfaces interfaceStats['total'] += 1 # Count admin-down interfaces if not sh_int_parsed[iface]['enabled']: interfaceStats['intdisabled'] += 1 # Count not connected interfaces elif sh_int_parsed[iface]['enabled'] and sh_int_parsed[iface]['oper_status'] == 'down': interfaceStats['intdown'] += 1 # Count up / connected interfaces - Then collect current speeds elif sh_int_parsed[iface]['enabled'] and sh_int_parsed[iface]['connected']: interfaceStats['intup'] += 1 speed = sh_int_parsed[iface]['bandwidth'] if speed == 10_000: interfaceStats['intop10m'] += 1 if speed == 100_000: interfaceStats['intop100m'] += 1 if speed == 1_000_000: interfaceStats['intop1g'] += 1 if speed == 10_000_000: interfaceStats['intop10g'] += 1 # Count number of interfaces by media type try: media = sh_int_parsed[iface]['media_type'] if '1000BaseTX' in media: interfaceStats['intmedcop'] += 1 else: interfaceStats['intmedsfp'] += 1 except KeyError: interfaceStats['intmedsfp'] += 1
Once all that runs, we create a CSV file to dump all of the data to.
For example, running the complete script against my lab Catalyst 9200 switch would output the following:
And that's it! Using the combination of scrapli & genie made this script very quick and easy to write - which means now I can focus more time on the next steps.
As I've mentioned a few times, this is hopefully the start of a short series of blog posts & videos as I wrap up studying for the DEVCOR exam.
If you found this content helpful - or you're interested in the future content - please check back soon! Or consider subscribing to my YouTube channel, where new content will be coming shortly. | https://0x2142.com/automating-the-cli-using-scrapli/ | CC-MAIN-2021-21 | refinedweb | 1,668 | 51.18 |
Red Hat Bugzilla – Bug 865680
[RFE] Ability to add "LINKDELAY=" to network config file
Last modified: 2013-01-16 23:33:30 EST
Description of problem:
Some NICs sometimes fail to get IP during boot up.
To work around the problem, recent RHELs provide "LINKDELAY=" parameter
in /etc/sysconfig/network-scripts/ifcfg-eth<X> file.
For example of RHEL6.3 Techinical Notes:
> 3.6. Networking
> kernel component
> Some e1000e NICs may not get an IPv4 address assigned after
> the system is rebooted. To work around this issue, add the following
> line to the /etc/sysconfig/network-scripts/ifcfg-eth<X> file:
>
> LINKDELAY=10
Because this can happen on the first boot up just after install
and then all test fails before starting any test, this cannot be
worked around by a test.
The snippet below provides "linkdelay=" kickstart metadata which
adds "LINKDELAY=" parameter to the config file of the active NIC.
--------------------------------------------------------------------------------
{% if linkdelay %}
IFACE=$(route -n 2> /dev/null | awk '/^0\.0\.0\.0/ {print $8}' | tail -n 1)
echo "LINKDELAY={{ linkdelay }}" >> /etc/sysconfig/network-scripts/ifcfg-$IFACE
{% endif %}
--------------------------------------------------------------------------------
Please add such a feature to the stage of kickstart %post.
(e.g. somewhere in the rhts_post snippet or so)
Would it be reasonable to add the LINKDELAY= line to every ifcfg-* file (except ifcfg-lo) instead of guessing the interface?
Yes, I think so.
On Gerrit:
Verified with build beaker-server-0.10.6-1.git.95.9d3b913.el6.
Submitted a job with:
<recipe kernel_options="" kernel_options_post="" ks_meta="linkdelay=20" role="RECIPE_MEMBERS" whiteboard="">
After provision, LLINKDELAY=20 is added into the ifcfg-* files:
$ cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE="eth0"
BOOTPROTO="dhcp"
HWADDR="52:54:3D:43:76:B6"
NM_CONTROLLED="yes"
ONBOOT="yes"
TYPE="Ethernet"
UUID="829c5a02-34c3-4dd4-9e2d-4ac2325f67eb"
LINKDELAY=20
Beaker 0.11.0 has been released. | https://bugzilla.redhat.com/show_bug.cgi?id=865680 | CC-MAIN-2017-47 | refinedweb | 301 | 54.63 |
Hide Forgot
Description of problem:
I tried to install from the live CD (F16 Beta RC) using anaconda-16.18-1.fc16.i686
Anaconda recognised the 8Gb USB disk and internal 60Gb SSD. I was offered two locations to install the bootloader
/dev/sdb MBR (this is the USB disk)
/dev/sda1 start of first partition (this is the SSD)
I wasn't able to install the bootloader to the MBR of the internal SSD and thus wasn't able to make the system bootable. Advanced choices didn't include the option to install to the MBR of sda which is what I needed.
Running grub2-install from the command line at the end of anaconda being finished wasn't successful (I tried with --force and --no-floppy but it complained of not recognising the partition.
I repeated this using LVM and not, in both cases I wasn't given the option to install to /dev/sda
Version-Release number of selected component (if applicable):
anaconda-16.18-1.fc16.i686
How reproducible:
100%
Steps to Reproduce:
1.install from live usb disk
2.
3.
Actual results:
no option to install to /dev/sda
Expected results:
system installs to /dev/sda by default and is bootable.
Additional info:
sfdisk didn't recognise the partition table, maybe my bios doesn't recognise it either and that stops the bootloader in /dev/sda1 from working.
can you please post the logs from the install? thanks! you should be able to find them in /root on the installed system.
throwing on the beta blocker list just so we don't lose it.
(In reply to comment #1)
> can you please post the logs from the install? thanks! you should be able to
> find them in /root on the installed system.
I will post them ASAP (this evening).
Created attachment 523605 [details]
anaconda ifcfg log
Created attachment 523606 [details]
anaconda log
Created attachment 523607 [details]
anaconda program log
Created attachment 523609 [details]
anaconda storage log
Created attachment 523610 [details]
dracut log
Created attachment 523611 [details]
rpm log
Logs attached as requested, all I could find in /root was a kickstart.cfg file. The other logs were in /var/log on the installed system.
Hmm I see lots of SELinux messages in anaconda.log, I'll try an install after booting with enforcing=0
This from anaconda program log:
00:57:00,454 INFO program: Running... grub2-install --force --no-floppy (hd0,1)
00:57:05,296 ERR program: /sbin/grub2-setup: warn: Attempting to install GRUB to a partitionless disk or to a partition. This is a BAD idea..
00:57:05,300 ERR program: /sbin/grub2-setup: warn: Embedding is not possible. GRUB can only be installed in this setup by using blocklists. However, blocklists are UNRELIABLE and their use is discouraged...)
(In reply to comment #13)
>.)
Is the bootloader in /dev/sda1 supposed to boot the system though (without an old grub in the MBR to chainload it for instance)?
no. the option to install to a partition header rather than the 'mbr' is there for those who want to chainload and know what they're doing. the bug here is as you initially suggested, that for some reason you don't get an option to install to the mbr..
(In reply to comment #16)
>.
Ah.. I used the whole disk option in Anaconda, so the unusual GPT disklabel thing comes from that. Should Anaconda be more proactive in offering to create a BIOS boot partition (should it even be the default?)
anaconda is actually supposed to pop up a dialog if you're installing to a GPT-labelled disk without a BIOS boot partition, and not let you out of the partitioning stage without one. And if you use the 'complete disk' option rather than custom partitioning, it's supposed to create one for you.
we're not entirely clear why it didn't in your case. It may be something to do with the presence of the USB stick (/dev/sdb) confusing it.
That's unfortunate!
When I added a BIOS boot partition manually, it then still offered to put grub2 on the boot partition (/dev/sda2 now) or the USB disk. I went for the boot partition but the resulting disk doesn't look bootable from this BIOS. I think maybe I should add some flags to the BIOS boot partition (I didn't look closely so there may have been a check box I missed in anaconda).)?
(In reply to comment #19)
> That's unfortunate!
>
> When I added a BIOS boot partition manually, it then still offered to put grub2
> on the boot partition (/dev/sda2 now) or the USB disk. I went for the boot
Can you upload /tmp/storage.log from this last attempt?
> partition but the resulting disk doesn't look bootable from this BIOS. I think
> maybe I should add some flags to the BIOS boot partition (I didn't look closely
> so there may have been a check box I missed in anaconda).
There's not much to it. It's just a raw/empty partition with the bios_grub flag set, which anaconda will do.
>
>)?
bios_grub on sda1. sda2 should be bootable. Anaconda should have done this for you.
Discussed in the 2011-09-16 blocker review meeting. We agreed that there isn't enough information to make a decision on the blocker status of this bug right now. It will be revisited when more information is available
I'm going to repeat the install and will upload the log. I have been fiddling with the GPT using parted and the best looking partition I can get is:
Model: ATA OCZ-VERTEX2 (scsi)
Disk /dev/sda: 60.0GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Number Start End Size File system Name Flags
1 1049kB 2097kB 1049kB bios_grub
2 2097kB 526MB 524MB ext4 ext4 boot
3 526MB 37.1GB 36.6GB ext4
4 37.1GB 42.2GB 5067MB linux-swap(v1)
5 42.2GB 60.0GB 17.9GB ext4
A 1Mb bios boot partition with the bios grub flag set, boot partition (/dev/sda2) with grub in it. This does not boot on my netbook (Insyde BIOS rev F12, HP mini 311c 1101SA). The BIOS doesn't recognise it as a system or bootable disk.
I will repeat the install to get the logs, but will then try using fdisk to make a traditional disk layout and get Anaconda to retry that.
If this doesn't turn out to be a blocker, because we don't know how many systems might be affected, at least it would be good to have the default GPT well documented and a traditional workaround available in case systems are installed non-bootable.
Created attachment 523687 [details]
storage.log copied after the filesystems have been laid out but before the bootloader is installed
I used LVM and whole disk, then edited the partitions. I had to steal 1Mb from the boot partition before anaconda would let me create the bios boot partition. Bios boot was then /dev/sda1 and linux boot was bumped to /dev/sda3.
Anaconda offered to install the bootloader to /dev/sda3 or /dev/sdb (live USB MBR)
I was able to install successfully by using the last option in Anaconda - create my own partition layout. The top two options seem to enforce GPT based layouts.
I used fdisk to check the layout and mark the boot partition bootable.
3 tests fail
1 network install of usb key default next next with unhashed lvm partion mbr gets installed on usb
2. Dvd on usb key same result
3. netboot of cd same result as in unbootable since it kinda goes without saying you cant write on the cd.
Definitely a Beta blocker
Custom partitioning also fails resulting in unbootable system
Just out of curiosity cold hard reality how prepared is anaconda for Grub2 ?
Is there a mandatory mbr partitioning that does not get created by default beside /boot?
USB install of DVD to HD:
Write 8GB Toshiba USB
dd if=Fedora-16-Beta-i386-DVD.iso of=/dev/sd(g) bs=2M
1787+1 records in 1787+1
records out 3747876864 bytes (3.7 GB) copied, 380.447 s, 9.9 MB/s
Installed to 250 GB USB ext HD
Booted USB
installed use whole disk (non LVM)
Anaconda shows USB and HD on left side; choose HD for install ==> to right
Default settings graphical; configure later
Sucess; reboot
Reboot HD
3.1.0-0.rc6 git o.3 ....PAE Kernel
firstboot; Tz; smolt; user; gdm login works
I used live tools to create the the bootable usb key and used x86_64 bit
Icelandic keyboard
Installed using whole disk
Anaconda shows USB and HD on left side; choose HD for install ==> to right ( Internal HD as in /dev/sda ) and I also clicked that circle in front of the HD for install.
Rest default next next...
All installation resulted in the bios not finding the master boot record on the internal drive.
When installing both via netboot and via dvd it installed the required boot partition on the usb key.
( bios found that one and successfully booted off it )
Performing netboot install of the cd resulted in the same thing.
damn, sorry, seem to have got bugs mixed up at some point. This one is for installing *from live*. satellit, johann: can you please file a new bug for the traditional-install-image-written-to-usb case? we should keep this for the live case.
I just hit something similar to cam's issue. I did a live install in a VM which had a USB key attached (via USB host passthrough), and anaconda failed to write a BIOS boot partition. I chose 'erase entire disk' with LVM checked, and didn't adjust the partitioning at all. I chose the VM's hard disk as an install target and did *not* choose the USB key as one, I left it on the left-hand side of the dialog.
There's some weird stuff going on in storage.log. The USB stick is /dev/sda ; it gets _gpt_disk_has_bios_boot partition run on it repeatedly, despite the fact that it a) is not an install target and b) does not have a gpt disk label (it's ms-dos). The test returns True, despite the fact that the USB stick does not have anything that resembles a BIOS boot partition; it's a single giant ext4 partition. The test is also run against vda - the VM's hard disk and actual install target - and fails as it should.
I see "skipping unneeded stage1 biosboot request" just after the first two runs of _gpt_disk_has_bios_boot against sda and vda. It subsequently gets run another two times against vda and three against sda.
Will attach all logs.
I also see is_valid_stage1_device running against sda and returning 'true', which also shouldn't happen.
oh, i see. gpt_disk_has_bios_boot should return 'true' for sda, it's designed to only return false if the disk is gpt-labeled and has no bios boot partition - so if the disk is msdos-labeled, then the test passes.
but if I set the disk in question only as storage and did not radio-button it as the bootloader target, it should not be considered a candidate for bootloader installation.
Created attachment 523929 [details]
storage.log from my test
sda is the USB stick attached to the system: it's not being installed from, it's just a device that's present. I did not choose it as an install target.
vda is the actual target drive, it's the VM's hard disk.
it looks like there's a hole in the logic somewhere: if you have a device present which passes the is_valid_stage1_device test and a device present which doesn't, and you explicitly pick the device which doesn't as the bootloader target, instead of checking whether it can make the chosen device pass the test, anaconda just decides the device which passes the test is a better candidate and goes with it.
I was able to reproduce this using anaconda-16.18-1 using the following setup:
KVM virtual machine
- minimal x86_64 install using netinstall boot.iso
- 20G disk (install target
- 10G disk (contains nothing, just exists on the system)
so i'm figuring some stuff out by inference here.
this same basic bug affects live and regular installs, but it looks slightly different.
in a regular install, you pick the bootloader location *after* partitioning and package install. in a live install, you pick it before.
in a live install, you can pick the hard disk, but it then decides not to install to it after all. in a regular install, it doesn't show the hard disk mbr as an option.
so it seems like anaconda checks for potential bootloader targets at the partitioning stage. if the only disk available doesn't have a bios boot partition, it decides to create one, and all's good; but if the target disk doesn't have a bios boot partition, but any other device it sees looks like a valid bootloader target, it figures that's good enough, and doesn't bother creating a bios boot partition on the target disk.
so in the regular install case, it then does the bootloader check again, figures that the target disk is no good, and doesn't offer to let you install the bootloader to the MBR of the target disk: it gives you a choice of the MBR of the 'valid' disk, or /boot on the target disk. in the live install case, it doesn't have any UI at that point, so it just decides for itself to install to the MBR of the 'valid' disk.
it looks like there's a few weak points in this chain, but the best thing to do might be to always have the bootloader target device selection done *before* the partitioning step, and have it try harder to use the target device at partitioning: if it's invalid but it can be made valid (by e.g. creating a BIOS boot partition...), do that. if it absolutely can't manage to do what you asked for, ask you again. that's a pretty major change for the non-live installer, though...
assigning to dlehman, this is his area.
Testing dd USB of live as installer to HD
Prepare USB 4 GB firefly:
gparted
make new partition table
format new fat 16
dd if=Fedora-16-Beta-rc1-i686-Live-Desktop.iso of=/dev/sdg
1175552+0 records in
1175552+0 records out
601882624 bytes (602 MB) copied, 280.445 s, 2.1 MB/s
Boot USB (enforcing=0) otherwise get Oh no!
install to HD (left icon in shortcuts gnome3-shell)
Anaconda
configure network (wireless wep ascii and password)
Los Angeles
root pswd
Use all space (non LVM)
------------------------------------------------------
Lexar JD Firefly
Seagate Freeagent 305254 MB ==> (install Target Device)
-----------------------------------------------------
write changes to disk
(creating devices sda 1-5)
Copying live image to hard drive
first boot
gdm login Oh no!
ctrl alt f4
log in user
$
su
root
#
cp anaconda.storage.log to /home/usr/
yum groupinstal XFCE
shutdown -h now
reboot
gdm
session XFCE
chmod 077 anaconda.storage.log
copy to 2nd usb
(In reply to comment #35)
> so i'm figuring some stuff out by inference here.
>
> this same basic bug affects live and regular installs, but it looks slightly
> different.
I'm wondering if there can be a better way of testing this. How viable would it be to record a data set representing the interesting / relevant aspects of a system as seen by Anaconda; then record the user choices as another data set. Would it then be possible to record the actions of Anaconda and wrap the whole lot up in a regression test suite that gives developers a good impression that changes to Anaconda's logic are likely to result in a working install and not likely to break anything?
When it works, it's amazing, and seems faster every time it changes (or is that my move to SSD), but it seems far too easy to break.
At least part of the problem is indeed the difference between automatic
partitioning and custom partitioning: if you use automatic partitioning you
choose your boot device before partitioning, while if you enter the custom
partitioner you can choose the boot device afterwards. This is hard to fix for
F16.
Another problem is related to the filtering of devices suitable as bootloader
stage1 and stage2 devices. We have a concept of "protected" devices in
anaconda, but there's a difference between being able to repartition and being
able to write a bootloader to a device. I have uploaded an updates image that
should improve this by marking as protected not only the live image's backing
device but also whatever devices it resides on. Currently, if the backing
device is a partition we only mark the partition as protected, and on non-live
installs we don't even do that even though there is a live-rw device that needs
protecting. With my updates we'll a) protect the backing device in both live
and non-live installs and b) in the case of a partition we will mark both it
and the disk it resides on as protected. This should resolve most of what's
being reported here.
I'm not in my normal work environment so this image is completely untested.
I came to about the same conclusion in re the live image :). Unfortunately, there's still one significant failure case the above fix won't address - the case where you have two hard disks, one with a safe F15 (say) installation on it, and one for 'experiments'. If you install F16 to the 'experiment' disk, you'll likely hit this bug, and F16's bootloader will get written to the MBR of the 'safe' disk, which is pretty impolite. This is the case tflink hit.
New updates available. These should come about as close as possible to making sure that all disks that might need a bios boot partition have one. Also untested.
(In reply to comment #40)
> New updates available. These should come about as close as possible to making
> sure that all disks that might need a bios boot partition have one. Also
> untested.
>
>
When I try this update, I get the following traceback immediately after selecting language and keyboard layout:
Traceback (most recent call last):
File "/usr/sbin/anaconda", line 582, in <module>
from pyanaconda import kickstart
File "/tmp/updates/pyanaconda/storage/__init__
looks like one parenthesis too many...
the background on the proposed fix is it basically sticks a bios boot partition on any gpt disk it can find, if there's space for one. this is a big hammer, but it sure ought to sort out this bug. :) we will need to do careful testing of it, though.
I'm a bit doubtful about the default of using GPT, having tried it on two machines and my best efforts failing to make either one boot. Are there any hard facts about compatibility? Maybe there are further bugs in the way Grub2 / Anaconda put together the GPT.
I'm thinking LVM merits a prominent opt-out check box, yet it's not half as dangerous as GPT from my experience.
cam: we're pretty clear on the bug, and how to fix it. the entire partitioning / bootloader bit of anaconda is being fundamentally redesigned for f17 anyway, so for f16, we just get to whack it with the big hammer.
gpt is not really the same case as lvm. gpt disk labels, and grub2, are The Future, with capital letters: we need to make them work properly. long experience has taught us that the fastest way to shake out all the bugs in supporting some Shiny New Thing is to get as many people using the SNT as possible in order to expose all the bugs. you are currently the meat in this particular sausage. =) given that pretty much everything going forward is going to have a gpt disk label and boot via grub2, it doesn't really make sense to have an 'opt out' option: we just need to suck it up and get the conversion done. remember, you're not even testing a beta, but the *release candidate* for a beta...this is kind of what's supposed to happen.
this isn't really an issue with gpt per se. there is nothing wrong with the disk label written to your machines. it's more to do with anaconda's workflow being based on assumptions that are valid for an msdos/grub world but are not really true for a gpt/grub2 world. this is a pretty classic bug category, and it's usually impossible to think through *all* the implications in advance: you have to throw actual use at the SNT, and then you realize all the things that look obvious with hindsight - like 'a bootloader location choice is not much use if it comes after the partitioning screen where you could have created the partition you'd need to install the bootloader where you want to install it.'
To be specific as to what happened in your case: you chose custom partitioning. if you choose that path, in current anaconda, you get to choose where the bootloader is installed much later in the install process than you do the partitioning step. Now, booting from a disk with a gpt disk label on a BIOS-based system with grub2 requires there to be this 'bios boot partition' thing on the disk.
In the simplest case - you install from a DVD on a system with one disk, and wipe that disk entirely - anaconda realizes at the partitioning stage that you won't be able to boot the system without the BIOS boot partition. There's only one place you could put the bootloader - on the target disk - and to do that, you need the special partition. So it forces you to create it.
In your case, though, there was another disk present: the USB stick you were installing from. anaconda has code to not consider a USB stick it's installing from as a valid target for installation, but thanks to this bug, we realized it only excepts it from consideration as a place *to put the system files*: it doesn't except it from consideration as a place where you could put the bootloader.
So in your case, at the partitioning stage, anaconda knew that you wouldn't be able to boot from your hard disk - but it then took a look at your USB stick, which passed all the tests required for a device to be a valid bootloader location, and thought 'hey, there's at least one valid place to put a bootloader', and moved straight along: it didn't see any need to alert you that you'd need a BIOS boot partition to boot from your hard disk, because that's not how the check is written to run.
That meant that when you got to the bootloader installation choice screen, anaconda correctly did not list your hard disk (at least, the 'mbr' of it) as a place you could put the bootloader - because it knew you *couldn't* put the bootloader there, it wouldn't work. there's no provision to 'go back' to the partitioning stage and put in a bios boot partition (and anyway, that might well not help, as you might already have partitioned up the entire disk by this point).
in a sense anaconda was never 'wrong', but it's clearly sub-optimal behaviour, because you're not likely to actually want to put the bootloader on the USB stick you're installing from. :)
there's several angles of attack for this. one that would fix your specific case of this bug is simply to extend the 'don't consider the USB stick we're installing from as a valid install target' code to also except it from consideration as a valid bootloader location; this was one way dave considered fixing this, but there are other cases of the bug which wouldn't be fixed by that. so in the end we decided that it's 'safest' - in the sense of being sure this bug is fixed - to just write a bios boot partition to any gpt-labelled disk we find, as long as there's space for one (and it doesn't have one already). that way, they'll all definitely be available as bootloader installation targets.
For F17, it'll likely be possible to make this more fine-grained, because the partitioning and bootloader installation steps will be ordered more sensibly. But it would be too disruptive to change that in F16.
are we likely to find other things like this that need rejigging in the Brave New World? well, probably. that's what betas are for. We're not *always* kidding when we say they can eat your babies.
In a larger sense, that's what *Fedora* is for: we do a lot of trying out the shiny new things when they're very shiny and very new.
well, I hope that explained things a bit :)
(In reply to comment #44)
> In a larger sense, that's what *Fedora* is for: we do a lot of trying out the
> shiny new things when they're very shiny and very new.
>
> well, I hope that explained things a bit :)
Thanks for the explanation, I take the Anaconda bugs part, but I still don't understand why my system wasn't bootable at all with GPT. Neither was another netbook I tried. Around about comment 22 I described my attempt to get it to work, and I tried several more variations, ensuring there was a BIOS boot partition. The BIOS just wouldn't boot from this.
I will keep testing GPT based installs to see if they start to work, but for now the only thing that seems reliable is the traditional disk layout.
cam: I think the options don't do what you think they do. 'use existing Linux partitions' does not mean 'try and install to the partitions that are present': it means 'use the space occupied by existing Linux partitions by destroying them and creating new ones in their place'. If you look at the log attached to comment #22 - search for 'clearpart' - you'll see anaconda deleting all those partitions you carefully prepared and creating new ones...not including a bios boot partition, due to this same bug. Right after the clearpart bit, you see it run its is_valid_stage1_device check again, find that sda fails but sdb passes, and skip creating a bios boot partition - "skipping unneeded stage1 biosboot request". Then it goes on to create its new partitions.
you can't really pre-create partitions and then have anaconda install to them by any means other than selecting 'custom layout' and then telling it to mount, but not format, the partitions you pre-created.
I would implore you to consider 4096 byte sector USB spindles when you're working through this BIOS/GPT/GRUB2 issue, as I've been trying to set up a new 3TB Seagate USB drive as a secondary boot disk (to plug in and boot my test distros in the same manner that I've been able to in the past with a 250GB WD USB "Book" drive with MBR partitioning on it). I've been unsuccessful with either F16pre-beta or Ubuntu Oneiric Ocelot (11.10) beta, despite having a 1MB bios_grub as the first partition on the drive. My laptop is an HP9000z (about 4 years old) with a Phoenix BIOS that doesn't recognize GPT/EFI at all, and limits me a choice of two spindles. Usually they're the two internal SATA hard drives, but when I plug in the 250GB WD drive, it sees it as the second drive and I can boot off of it. Not so with the 3TB Seagate with a GPT on it. (It's been very unclear if either F16 or Oneiric actually wrote a boot block to the Seagate spindle - I don't even get a GRUB> prompt as a teaser!)
Having gutted through SNTs such as PulseAudio and NetworkManager, I'm ready to test GPT/GRUB2 on a BIOS-based laptop.
New updates:
Created attachment 524263 [details]
traceback from updates.3.img
I got another crash while trying to use full disk autopart
Created attachment 524273 [details]
storage.log from successful install using .4 update
I was able to successfully install when 2 disks were present using the .4 updates image.
Note that while this isn't part of the originally reported issue, it was still showing the same symptoms.
Discussed during the 2011-09-21 Fedora 16 beta go/no-go meeting. Accepted as a blocker for Fedora 16 beta because it violates the following alpha release criterion [1] :
In most cases,.
Since this bug can cause problems with existing installations and result in non-bootable installations, it was judged common enough to take as a blocker.
[1]
If you would like to test the proposed fix, add the following to either your boot command line or as an argument to the liveinst command:
updates=
Created attachment 524471 [details]
traceback from raid setup using .4 update
I got a crash when I was trying to setup software raid in anaconda, tb is attached.
I ran a test of the two-hard-disk case.
Procedure:
1) create a VM with two hard disks, both VirtIO backed by image files on the host.
2) install Fedora 15 from the DVD to the first disk (/dev/vda), using 'use all space' and selecting only /dev/vda as an install target, leaving /dev/vdb out completely.
3) confirm the F15 install boots and works, using grub1.
4) install Fedora 16 from the Beta RC1 DVD to the second disk (/dev/vdb - note, I made the disks different sizes, so I could be sure which was which, despite any potential enumeration issues), using 'use all space' and selecting only /dev/vdb as an install target, leaving /dev/vda out completely. Click the radio button for /dev/vdb as the bootloader install location on the 'device selection' screen.
I performed this exact procedure twice, once using the F16 Beta RC1 DVD only, once using updates-738964.4.img. In the first case, the result was thus:
* grub2 on vda's MBR, loading its config and second stage from vdb, with only Fedora 16 entries in the menu
* no bootloader in vdb's MBR
upshot: neither drive could boot with the other drive disconnected, and it was impossible to access F15, though F16 would boot correctly from this configuration.
In the second case, the result was thus:
* grub-legacy remained on vda's MBR, loading its config and second stage from vda, with only Fedora 15 entries in the menu
* grub2 on vdb's MBR, loading its config and second stage from vdb, with only Fedora 16 entries in the menu
This is clearly a significant improvement, and I encountered no bugs in this test.
(It's worth noting as an aside that I actually could not boot the F16 disk in the second case; I couldn't seem to convince KVM to boot from it even by using the boot menu, it would always boot from the F15 disk. Disconnecting the F15 disk from the VM would cause it to try and boot from the F16 disk, confirming that the bootloader was present there, but it would fail to find the root device and boot to dracut's rescue mode. But I think that's beyond the scope of this bug; anaconda did its job correctly. I suspect that it would work in the case of real hardware - at least, you'd be able to make the BIOS boot from the second disk without disconnecting the first).
Ran into a trace when testing the updates.img on a VM with a USB stick attached: .
We're really going to need a build for this, whether it's the big hammer or a lighter touch, tomorrow (or Saturday), or else we're at risk of slipping the Beta again. Thanks!
as a fallback, if we're struggling, we could go with a build that tightens up the exclusion check for installer media and tries harder to honor the user's choice of bootloader location. If done right that should fix most problem paths except custom partitioning, and that one is not actually a Beta blocker.
The updates= patch allowed Anaconda to offer me a new additional partition (sdc8) that was a bios_boot partition and offered to format it for me and use it as my bios_boot partition. That was nice, but it kind of ignored the one that I tried to set up/reserve at sdc1, although it's possible that mine wasn't quite big enough. In any case, it did NOT allow me to specify a boot location of "sdc", only "sda" (my first internal hard drive) or "sda4" (my system partition). I chose the latter, and it (understandably) still won't boot. I'm in the process of adjusting my openSUSE 11.4 legacy GRUB 0.97 boot stanza to point to whatever the UUID for sdc4 is now.
(When it tried to boot off of the "wrong" one, Dracut came up on the black screen, but I didn't know how to coax it into starting a real system from there).
bayard: could you try simply allowing Fedora to format the disk as it chooses, or is that not practical?
can you please post the storage.log from the install?
thanks.
Created attachment 524530 [details]
storage.log from install on 3TB USB drive with GPT using 738964.4 patch
Given the way things are going, I just might allow Fedora/Anaconda to have at it, using David Lehman's .4 patch, and then I'll try to adjust the partitioning to suit my needs later.
sda, sdb and sdc all pass the is_valid_stage1 test, so I'm not sure why you weren't given the option to put the bootloader on sdc...
Only reason I can think of stems from reading the info file for GRUB2 which seems to imply that if there's already a boot block on the spindle, it won't write another one. However, as I said earlier, I couldn't prove that one way or the other. BTW, the disk was carved up as follows (but has since been overwritten): 2097kB 1049kB BIOS boot partition bios_grub
2 2097kB 539MB 537MB ext4 boot
3 539MB 4834MB 4295MB Linux swap
4 4834MB 112GB 107GB ext4 boot
5 112GB 220GB 107GB Linux filesystem
6 220GB 327GB 107GB Linux filesystem
7 327GB 434GB 107GB Ubuntu boot
8 434GB 434GB 1049kB bios_grub
I just did another installation, using David Lehman's patch and followed your suggestion that I let Anaconda have its way with the spindle. It didn't boot, and instead, as usual, the openSUSE 11.4 legacy GRUB 0.97 splash came up.
It now looks like this (as seen from openSUSE 11.4): 525MB 524MB ext4 boot
2 525MB 526MB 1049kB bios_grub
3 526MB 3001GB 3000GB lvm
I can't mount /dev/sdb3 (as it's an LVM member), but I did mount sdb1 and
sniffed around. There's a decent looking grub.cfg, and it wants to
set root='(hd2,gpt1)' which is all well and good, but my BIOS thinks that
spindle is 'hd1'. F16's device.map says:
# this device map was generated by anaconda
(hd0) /dev/sda
(hd1) /dev/sdb
(hd2) /dev/sdc
(hd2,1) /dev/sdc1
So, I'm thinking this is the classic case of needing to twiddle with that
to get the drives ordered properly. (Been there, been doing that for about
2-3 years with the other USB drive...). I'll look at it in the morning, but
it's heartening to see that the GPT is OK, and that Anaconda *did* offer to
write the bootloader to the 3TB drive. Whether it actually did so is TBD.
There were a couple of problems with the .4 image:
- the code to force stage1 onto the chosen boot drive wasn't
forceful enough
- there was a syntax error as reported in bug 740681
New image that should fix both problems:
Last image had that extra paren syntax error pop back up, so new image:
I just did a successful installation from LiveCD with the image. Thanks for turning it around so quickly.
Created attachment 524674 [details]
storage log showing "out of space" error using .7 update
While cleaning off the existing partitions to set up for testing, I got a dialog box with "Could not allocate requested partitions, not enough free space on disks".
7-nohammer does fix my two-hard-disk reproducer, where the first hard disk has a working F15 install, the second is blank, and the second is chosen as the install target and bootloader device: even without the hammer, a bios boot partition is created on the second disk and the bootloader written to the second disk's MBR. I'm able to boot the second disk by disconnecting the first (I didn't use LVM for the second disk this time).
didn't try and reproduce tflink's issue yet. will now test the 'random usb key' case, then go on to think of others.
Created attachment 524680 [details]
storage log showing "out of space" error using .7-nohammer update
I was able to hit the same error as c#67 using.
Setup:
Baremetal install, 1G RAM, i686 processor
• Beta RC1 i386 DVD
* updates=
* Disk 1 (160G IDE) - Fedora 15
* 500M /boot
* Remainder LVM PV (not encrypted)
* vg_testhost
* 2G swap
* 98G /home
* 50G /
* Disk 2 (160G IDE) Fedora 16
* 500M /boot
* Remainder LVM PV (not encrypted)
* vg_testhost00
* 2G swap
* 98G /home
* 50G /
Procedure:
* boot F16 beta RC1 i386 DVD
* updates=
* Choose custom partitioning
* Delete both existing VG
* Delete LVM PV on Disk 2 (/dev/sdb)
Error dialog title: "Error Partitioning"
Error dialog contents: Could not allocate requested partitions: not enough free space on disks.
New updates images have been released for testing
For details on what we're looking for regarding testing of these images, see
Created attachment 524682 [details]
error when reformating bios boot partition
I was also able to receive "Could not allocate requested partitions: not enough free space on disks." error. This happened when I selected existing BIOS Boot partition and selected to reformat it (to the same type). I used .7-nohammer.img. Attaching traceback log.
'random USB stick' test case is good with -nohammer: this is the one where I first reproduced the bug, doing an install in a VM from the live 'CD' to the VM's hard disk, with a USB stick attached during install. without the fix, anaconda puts the bootloader on the USB stick. With -nohammer, if I select the hard disk as the target device, it puts the bootloader on the hard disk.
so far the fixes in -nohammer are looking good, but the bug tflink and kparal hit needs to be fixed before we can go ahead, I think.
I tested both with the same setup as previously, but added an external USB hard
disk, so had:
Internal SSD with F16 installed
Bootable USB flash device
External USB hard disk
I used .7-nohammer and tried custom layout including a BIOS boot partition. The
closest option for installing a bootloader was /dev/sdc2 (the boot on the
external disk I think) which only booted as far as a GRUB string.
Second test was with .7, I used the whole disk and was given the option to
install to the MBR at last. Strangely I had the desktop trying to mount the
external disk, so had to click 'eject' (on the notification), then Anaconda
wouldn't recognise the external disk until I replugged it (it reappeared as
/dev/sdd). Anyway the installation went smoothly and, I'm pleased to say it
made the disk bootable, GPT and all.
I haven't checked to see if the internal SSD has been affected, I will try and
reinstall that next. It may be that I can get .7-nohammer to work if I try the same approach I used for .7
yes, please re-test with .7-nohammer using 'use entire disk'.
we're hitting various issues with the 'custom partitioning' path, but that's not actually beta-critical, and given how hard it seems to be to zap this damn bug, we might have to settle for shipping it as long as the non-custom paths seem to work well.
fwiw, I have a VM here which seems to act the same as cam; if you have a 'spare' USB stick attached and use custom partitioning, even though you ensure that there's a BIOS boot partition on the hard disk - and I checked via storage.log that is_valid_stage1_device returned true for vda - the bootloader location choice dialog from the custom partitioning path only offers the MBR of sda or the /boot partition of vda. It seems like the dialog just can't cope with two possible MBR locations being available, and only offers you one.
Created attachment 524691 [details]
traceback using .7-nohammer.img and fulldisk autopart with 2 disks
Using the same setup as comment 69, I tried using the "Use all space" option with BOTH 160GB disks.
I got a crash during partitioning, will attach tb and storage.log
Created attachment 524692 [details]
storage.log using .7-nohammer.img and fulldisk autopart with 2 disks
anaconda-16.19-1.fc16 has been submitted as an update for Fedora 16.
I hit the same tb as tflink with .7-nohammer.img, but via a different path: .
Well, we just discovered something that explains quite a lot. updates-738964.7-nohammer.img has the hammer; it is byte-identical to .7.img.
So all the tests we did with that image actually included the hammer. On the one hand, that likely explains the tb that tflink and I have been hitting, but on the other hand, it means we have no testing to ensure that the fixes without the hammer are enough to solve the bug.
anaconda 16.19 has been built without the hammer, and tflink is building a boot.iso for us to test with that version of anaconda in it. We can re-test our reproducers with that boot.iso and see how things stand.
I built an x86_64 netinstall iso with the new anaconda-16.19-1
-
-
This does NOT have the hammer-fix in it, so please re-test with these images. I will be building an i386 test image shortly, will re-post once that's done.
anaconda-16.19-1.fc16 has been pushed to the Fedora 16 stable repository. If problems still persist, please make note of it in this bug report.
Cam, I know that ironically your exact initial case of this bug has not been solved. I'm planning to file two new bugs about that, though, to keep things straight; this bug is a huge monster and it's probably best off closed.
Filed to suggest adding an advisory warning in the case where you do custom partitioning and don't create a BIOS boot partition, but there's some other disk which would be a valid bootloader location (currently anaconda doesn't give you any warning in this case).
I have hit upon this exact bug in Fedora 16 Beta and currently using my USB disk to load the bootloader which is installed in it. Is there some way to resolve this problem without a reinstall ?
just manually install the bootloader to the hard disk.
Trying to manually install grub2 to the harddisk using grub2-install /dev/sda gives me warnings "This GPT partition label has no BIOS Boot partition ..." , is it a good idea to force it ?
ah. no, you'll need a BIOS boot partition. so you reformatted the disk during install but didn't create one. did you leave any free space on the disk?
that is, _unpartitioned_ space.
I just resized my swap to create 2 MB ... My layout is as follows
Model: ATA ST9500420AS (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Number Start End Size File system Name Flags
1 1049kB 176GB 176GB ext4
2 176GB 337GB 161GB ext4
3 337GB 444GB 107GB hidden, legacy_boot
4 444GB 498GB 53.7GB ext4 ext4 boot
5 498GB 500GB 2145MB linux-swap(v1)
6 500GB 500GB 2097kB bios_grub
I ran grub-install but encountered errors as follows :
[root@Bigbang ~]# grub2-install /dev/sda6
/sbin/grub2-setup: error: unable to identify a filesystem in hd0; safety check can't be performed.
you don't install grub to the bios boot partition. you install it to the boot/root partition or to the MBR.
Aargh .. Thanks for the tip. I could successfully install grub2 to /dev/sda using grub2-install /dev/sda but the system is not booting up. I am using Lenovo T420 with UEFI BIOS and I tried all UEFI options -> UEFI only / Legacy only / Both. It just shows me the option to select the hard disk for booting up and then grub does not load. Its as if its not reading from the MBR.
did you create a config with grub2-mkconfig first?
Yeah, I had done that but no joy. I got Gentoo up and running on my system. Adam thanks a lot for your help.
vivek: ah. Just caught that you're on a Thinkpad. You're almost certainly hitting : some thinkpads appear not to be capable of booting via BIOS from a GPT-labelled disk.
For Final, we'll have a workaround available for this. | https://bugzilla.redhat.com/show_bug.cgi?id=738964 | CC-MAIN-2019-39 | refinedweb | 7,688 | 68.3 |
Ruby’s Top Self Object
Much of Ruby’s implementation of objects and classes is modeled after Smalltalk, one of the original object oriented languages first built in the late 1960s. Just like with Smalltalk, Ruby’s
Object class is the root of your program’s class hierarchy, and all Ruby classes are instances of the
Class class. Smalltalk blocks and Ruby blocks also both support using anonymous functions as closures.
But in one interesting way Ruby and Smalltalk differ. Ruby allows you to define simple functions at the top level scope. This enables Ruby to serve as a scripting language. Using Ruby, it’s very easy to combine a few functions together in a small script to accomplish some simple command line task. At the same time, Ruby’s has Smalltalk’s sophisticated OO design at the ready, waiting for you to use it. When your script gets a bit more complex, you can easily turn it into a more organized, object oriented program.
How does Ruby do this? Before your script starts to run, Ruby automatically creates a hidden object known as the top self object, an instance of the
Object class. This object serves as the default receiver for top level methods. Today we’ll see how this object – the object we didn’t even know we were using – allows us to write simple functions in an object oriented language.
Functions in Ruby
Using Ruby, you can write functions without creating classes for them. For example, here’s the recursive definition of the factorial function in Ruby.
We were able to write a simple function without thinking about methods, receivers, classes or instance variables. We didn’t need any of these concepts, because all we wanted to do was perform a simple calculation. (Advocates of functional programming, of course, would argue you never need OO concepts – that you can and should write your code exclusively with simple functions.)
In this example, Ruby is not a complex, object oriented language, but just a simple scripting language. For many of us, this is how we started using Ruby: At this level, Ruby’s syntax is very straightforward and easy to learn.
Functions Are Methods
However, under the hood Ruby uses a model similar to Smalltalk. There are no functions in Ruby, only methods. Every method belongs to a class.
But what about my factorial example above? Isn’t that a function? I didn’t declare a class or create an object. I just wrote a simple function. If we display the value of
self inside factorial, we’ll see that, in fact, it is a method.
Here you can see Ruby displays the string “main” for the value for
self. Because Ruby defines a value for
self inside
factorial, it must be a method.
self contains a reference to the current object, the receiver for the current method. Since
factorial has a receiver it must be a method, not a function.
Seeing Ruby’s Top Self Object
The string “main” is how Ruby represents the top self object as a string. Ruby creates it automatically before you program starts in order to serve as the receiver for functions in the top level scope, such as
factorial.
In fact, you don’t need to write a method to obtain a value for
self. For example:
Here we are running a one line Ruby script using the
-e option. You can see puts
self returns the string “main.” Another test reveals that the top self object is an instance of
Object, the root class of Ruby’s class hierarchy (aside from the internal
BasicObject class).
After creating the top self object, Ruby assigns a
to_s method to it which returns the string “main.” Ruby does this using C code internally, but it is equivalent to this Ruby snippet:
You can see self is an instance of
Object. Also notice Ruby defines this special version of the
to_s method only for the top self object. Technically speaking, Ruby creates a singleton class for
self and assigns the new
to_s method to it. (The default version of
to_s,
Object#to_s, displays the class name and encoded object id instead.)
Of course, you couldn’t write this code yourself, since
self is a reserved word and part of the Ruby language. If you run the code above you’ll get a syntax error “Can’t change the value of self.”
Which Class do Ruby Functions Belong To?
If all Ruby functions are methods, they must belong to some class. But which class? As you might guess, because the top self object is an instance of
Object, Ruby adds all top level functions as methods in the
Object class. Here’s an example.
Here you can see Ruby’s
def keyword saved
factorial as a method in the
Object class. All Ruby functions are actually private methods of
Object. We can prove this is the case by listing the private instance methods of the
Object class, like this.
Calling Ruby Functions
Saving functions as
Object methods isn’t only to preserve Ruby’s (or Smalltalk’s) elegant object oriented design. Internally, it allows Ruby to find functions when your program calls them. Here’s an example.
At the bottom of the diagram I’ve written a new class called
SomeOtherClass. As you can see it contains a single method
show_the_answer which calls the
factorial function.
When I call
factorial, Ruby first looks to see if
factorial is a method of
SomeOtherClass. Because it isn’t, Ruby then looks through the superclasses of
SomeOtherClass to find
factorial. Because Ruby added the
factorial function to
Object, the class of the top self object, Ruby will find it since
Object is a superclass of every other class.
Ruby’s Hidden Object
This might seem like a bit of syntactic sugar. Why does it matter which class Ruby uses to save functions? It fact, does it even matter that functions are methods? They work the same way. And why does the value of self in the top lexical scope matter?
The key point here is that this trick allows you to write simple functions in Ruby. If we weren’t able to write them, Ruby would be harder to learn and more awkward to use. You would have to understand object oriented programming ideas even to get started writing the simplest script using Ruby.
Because it’s hidden, because we don’t know we’re using it, the top self object allows us to use Ruby without object and classes as a simple scripting language. Ruby is much easier to learn than Smalltalk because of the top self object. To learn more about Ruby’s method lookup algorithm, how Ruby implements objects, classes, lexical scope and much more, look for the updated version of my book Ruby Under a Microscope, due out in November from No Starch Press. | https://www.sitepoint.com/rubys-top-self-object/?utm_source=sitepoint&utm_medium=articletile&utm_campaign=likes&utm_term=ruby | CC-MAIN-2018-39 | refinedweb | 1,149 | 64.2 |
cmd.exe
I change over to using StreamWriter. I have used it before, I wasn't thinking.
using System.IO;
using (StreamWriter list = new StreamWriter("C:\\Users\\Gene\\Desktop\\Test.scr", true)) {
list.WriteLine("Line " + cabinetx + "," + topy + " @" + cabinetWidth + ",0\n");
}
I changed from Console.WriteLine( ) to list.WriteLine( )
Works great. Beautiful thing. It doesn't print to screen but it does write to a text file.
I use progeCad. (similar to AutoCad)
I saw this online. Running script in Cad program
It draws a 1" square box. And it did it all in 1 line of code.
Line 0,0 @1,0 @0,1 @-1,0 close
Starts a line command. Space is like hitting the spacebar or Enter key.
Where do you want to start from? x,y coordinate 0,0. Space
What's the next point? @1,0. Space. and so forth
After that, I drew a cabinet, used it as a model to gather locations and sizes of Left end, right end, top, deck and measured for precise locations and sizes.
From those measurements I typed out these commands
Rectangle 0,4 @0.75,30.5
Rectangle 30,4 @-0.75,30.5
Rectangle 0.75,34.5 @28.5,-0.75
Rectangle 0.75,4 @28.5,0.75
Saved as a script file (.scr) and ran in progeCad as script file
It drew out in a split second what I had drawn previously for a model
After that, it was like candy. What other parts can I draw?
The program is two parts
First part gathers information- width, height, depth. Top drawer and 1 door, with 2 adjustable shelves. This is done thru user input, to change location, sizes and choice of parts.
Numerous windows display, allowing changes. Window is cleared and the next window is diplayed...
Second part is where all the commands code is generated. (similar to lines of code above)
I copy the command codes, paste in a text file, save as script file and run in progecad
Each line, represents one full command in progeCad. The first line runs and jumps to the next line until the end. It just drew several views of the cabinet.
Using StreamWriter, no more copy and pasting.
Thanks again.
using (StreamWriter list = new StreamWriter("C:\\Users\\Gene\\Desktop\\Test.scr", true)) {
string content = "Line " + cabinetx + "," + topy + " @" + cabinetWidth + ",0\n";
list.WriteLine(content);
Console.Write(content);
}
{
public enum Fruit
{
Apple, Orange
}
[Parameter("Fruit Type")]
public Fruit FruitType { get; set; }
public override void Calculate
{
var Apple = 5
var Orange = 1
bool MoreApples = Apple > Orange;
bool FewerApples = Apple < Orange;
if (FruitType == Fruit.Apple && MoreApples)
{
//do something
}
if (FruitType == Fruit.Orange && FewerApples)
{
//do something else
}
Quote:I want that enum to be the actual name of a var.
public override void Calculate(FruitType fruitType)
Dave Kreskowiak wrote:... values in an enum should not be thought of as variable names at all ... It may work in interpreted languages, but it doesn't work in compiled languages. The variable names no longer exist(*).
Dave Kreskowiak wrote: context of "beginner"
using System;
using System.Collections.Generic;
namespace YourNameSpace
{
public enum Fruit
{
NoFruit, Apple, Orange
}
public class FruitCalc
{
private Dictionary<Fruit, Func<int, int, Fruit>> CalcFruitDict
= new Dictionary<Fruit, Func<int, int, Fruit>>
{
// lambda notation used here
{Fruit.Apple, (int napples, int noranges) => napples > noranges ? Fruit.Apple : Fruit.NoFruit },
{Fruit.Orange, (int napples, int noranges) => napples < noranges ? Fruit.Orange : Fruit.NoFruit },
};
public Fruit Calculate(Fruit fruit, int napples, int noranges)
{
if (fruit == Fruit.NoFruit)
{
throw new InvalidOperationException("Sorry, no fruit means no fruit");
}
// check integer parameters for valid range ?
return CalcFruitDict[fruit](napples, noranges);
}
}
}
FruitCalc fcalc = new FruitCalc();
Fruit f1 = fcalc.Calculate(Fruit.Apple, 12, 4);
Fruit f2 = fcalc.Calculate(Fruit.Orange, 14, 24);
Fruit f3 = fcalc.Calculate(Fruit.Apple, 2, 4);
Fruit f4 = fcalc.Calculate(Fruit.Orange, 14, 2);
// force an error
Fruit f5 = fcalc.Calculate(Fruit.NoFruit, 12, 4);
public Fruit Calculate2(Fruit fruit, int napples, int noranges)
{
switch (fruit)
{
case Fruit.Apple:
return napples > noranges ? Fruit.Apple : Fruit.NoFruit;
case Fruit.Orange:
return napples < noranges ? Fruit.Orange : Fruit.NoFruit;
default:
throw new InvalidOperationException("Sorry, no fruit means no fruit");
}
}
public void DropDownSelectChanged(object sender, EventArgs args)
{
// assuming the sender is the drop down
var ddl = sender as DropDown; // whatever the actual control is in your GUI
Calculate(ddl.SelectedItem);
}
// These get set in your constructor.
public Action MoreApplesAction {get; set;}
public Action FewerApplesAction {get; set;}
public void Caclulate(Fruit selectedFruit)
{
// Of course, these should be properties somewhere
var Apple = 5
var Orange = 1
// It's OK to create guards like this to
// enhance readability, but don't be surprised
// when someone objects because of the memory
// allocation.
var MoreApples = Apple > Orange;
var FewerApples = Apple < Orange;
switch(selectedFruit)
{
case Apple:
if(MoreApplies) MoreApplesAction?.Invoke();
break;
case Orange:
if(FewerApples) FewerApplesAction?.Invoke();
break;
}
}
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://www.codeproject.com/Forums/1649/WebControls/?df=90&mpp=25&prof=True&sort=Position&view=Normal&spc=Relaxed&select=5634976&fr=276&fid=1649&display=PrintAll | CC-MAIN-2019-43 | refinedweb | 831 | 60.31 |
25 July 2018
Aliases: pcap_dispatch(3pcap), pcap_dispatch(3pcap), pcap_dispatch(3pcap)
NAME
pcap_loop, pcap_dispatch - process packets from a live capture or savefile
SYNOPSIS
#include <pcap/pcap.h>
typedef void (*pcap_handler)(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes);
int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user); int pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback, u_char *user);
DESCRIPTION
pcap_loop() processes packets from a live capture or ‘‘savefile’’ until cnt packets are processed, the end of the ‘‘savefile’’ is reached when reading from a ‘‘savefile’’, pcap_breakloop(3PCAP) is called, or an error occurs. It does not return when live packet buffer timeouts occur. A value of -1 or 0 for cnt is equivalent to infinity, so that packets are processed until another ending condition occurs.
pcap_dispatch() processes packets from a live capture or ‘‘savefile’’ until cnt packets are processed, the end of the current bufferful of packets is reached when doing a live capture, the end of the ‘‘savefile’’ is reached when reading from a ‘‘save ‘‘savefile’’.
Note that, when doing a live capture on some platforms, if the read timeout expires when there are no packets available, pcap_dispatch() will return 0, even when not in non-blocking mode, as there are no packets to process. Applications should be prepared for this to happen, but must not rely on it happening.
(In older versions of libpcap, the behavior when cnt was 0 was undefined; different platforms and devices behaved differently, so code that must work with older versions of libpcap should use -1, not 0, as the value of cnt.)
callback specifies a pcap_handler routine to be called with three arguments: a u_char pointer which is passed in the user argument to pcap_loop()(3P) is called; after a successful call to pcap_set_datalink(), all subsequent packets will have a link-layer header of the type specified by the link-layer header type value passed to pcap_set_datalink().
Do NOT assume that the packets for a given capture or ‘‘savefile‘‘_loop() returns 0 if cnt is exhausted or if, when reading from a ‘‘savefile’’, no more packets are available. It returns PCAP_ERROR if an error occurs or PCAP_ERROR_BREAK if the loop terminated due to a call to pcap_breakloop() before any packets were processed. It does not return when live packet buffer timeouts occur; instead, it attempts to read more packets.
pcap_dispatch() returns the number of packets processed on success; this can be 0 ‘‘savefile.’’ It returns PCAP_ERROR if an error occurs or PCAP_ERROR_BREAK if the loop terminated due to a call to pcap_breakloop() before any packets were processed. If your application uses pcap_breakloop(), make sure that you explicitly check for PCAP_ERROR and PCAP_ERROR_BREAK, rather than just checking for a return value < 0.
If PCAP_ERROR is returned, pcap_geterr(3PCAP) or pcap_perror(3PCAP) may be called with p as an argument to fetch or display the error text. | https://reposcope.com/man/en/3pcap/pcap_loop | CC-MAIN-2022-40 | refinedweb | 473 | 50.91 |
Adrian Brenton8,110 Points
Hello all I'm unsure how to solve this challenge. I've tried a function also - no luck, please advise, many thanks
I've tried defining a function for this, to no avail, and am a bit stuck with this challenge.
Not sure if my logic is flawed, or if I'm making a silly mistake with this one here.
Help would be very much appreciated!
Many Thanks
import sys start_movie = input("Do you want to start the movie? Y/n") if start_movie != "n" or "N": print("Enjoy the show! ") else: sys.exit()
1 Answer
Steve HunterTreehouse Moderator 57,561 Points
Hi Adrian,
You have to write the conditional tests in full; you can't use
or like that.
You'd need to have:
if start_movie != "n" or start_movie != "N":
However, working through your logic, you'd need both to be
!= so you should use
and. Alternatively, use
.lower() to simplify the tests:
if start_movie.lower() != "n":
I hope that helps,
Steve.
Adrian Brenton8,110 Points
Adrian Brenton8,110 Points
Many thanks Steve - much appreciated! | https://teamtreehouse.com/community/hello-all-im-unsure-how-to-solve-this-challenge-ive-tried-a-function-also-no-luck-please-advise-many-thanks | CC-MAIN-2020-05 | refinedweb | 179 | 77.33 |
.
The Linux Kernel already had an API called fbdev, used to manage the framebuffer of a graphics adapter,[2] but it couldn't be used to handle the needs of modern 3D accelerated GPU based video hardware. These devices usually require setting and managing a command queue in their own memory to dispatch commands to the GPU, and also require management of buffers and free space within that memory.[3] Initially, user-space programs (such as the X Server) directly managed these resources, but they usually acted as if they were the only ones with access to them. When two or more programs tried to control the same hardware at the same time, and set its resources each one in its own way, most times they ended catastrophically.[3]
The Direct Rendering Manager was created to allow multiple programs to use video hardware resources cooperatively.[4] The DRM gets exclusive access to the GPU, and it's responsible for initializing and maintaining the command queue, memory, and any other hardware resource. Programs wishing to use the GPU send requests to DRM, which acts as an arbitrator and takes care to avoid possible conflicts.
The scope of DRM has been expanded over the years to cover more functionality previously handled by user space programs, such as framebuffer managing and mode setting, memory sharing objects and memory synchronization.[5][6] Some of these expansions were given also needed to be solved at the DRM layer. In order to match the Nvidia Optimus technology, DRM was provided with GPU offloading abilities, called PRIME.[7].
/dev
/dev/dri/cardX].[8] When a specific DRM driver provides an enhanced API, user space libdrm is also extended by an extra library libdrm-driver that can be used by user space to interface with the additional ioctls..
KMS has been adopted to such an extent that certain drivers which lack 3D acceleration (or for which the hardware vendor doesn't want to expose or implement it) nevertheless implement the KMS API without the rest of the DRM API.
KMS models and manages the output devices as a series of abstract hardware blocks commonly found on the display output pipeline of a display controller. These blocks are:[47]]
/dev/dri/renderDX.
The Direct Rendering Manager is developed within the Linux kernel, and its source code resides in the /drivers/gpu/drm directory of the Linux source code. The subsystem maintainter is Dave Airlie, with other maintainers taking care of specific drivers.[100].
/drivers/gpu/drm
For historical reasons, the source code of the libdrm library is maintained under the umbrella of the Mesa project.[101]
In 1999, while developing DRI for XFree86, Precision Insight created the first version of DRM for the 3dfx video cards, as a Linux kernel patch included within the Mesa source code.[102] Later that year, the DRM code was mainlined in Linux kernel 2.3.18 under the /drivers/char/drm/ directory for character devices.[103],[104] and that list expanded during the 2.4.x series, with drivers for ATI Radeon cards, some SiS video cards and Intel 830M and subsequent integrated GPUs.
/drivers/char/drm/
The split of DRM into two components, DRM core and DRM driver, called DRM core/personality split was done during the second half of 2004,[11][105] and merged into kernel version 2.6.11.[106] This split allowed multiple DRM drivers for multiple devices to work simultaneously, opening the way to multi-GPU support.
The idea of putting all the video mode setting code in one place inside the kernel had been acknowledged for years,[107][108],[109].[110][111] Work on both the API and drivers continued during 2008, but got delayed by the necessity of a memory manager also in kernel space to handle the framebuffers.[112].[113]
/drivers/gpu/drm/
/include/drm.[114] Meanwhile, TTM had to wait until September 2009 to be finally merged into Linux 2.6.31 as a requirement of the new Radeon KMS DRM driver.[115]][116] along with KMS support for the i915 driver.[117] The KMS API have been exposed to user space programs since libdrm 2.4.3.[118] The userspace X.Org DDX driver for Intel graphics cards was also the first to use the new GEM and KMS APIs.[119] KMS support for the radeon DRM driver was added to Linux 2.6.31 release of September 2009.[120][121][122].[123][124][125] —only for the i915 driver, radeon and nouveau added it later during Linux 2.6.38 release.[126] The new page flip interface was added to libdrm 2.4.17.[127] In early 2011, during the Linux 2.6.39 release cycle, the so-called dumb buffers —a hardware-independent non-accelerated way to handle simple buffers suitable for use as framebuffers— were added to the KMS API.[128][129] The goal was to reduce the complexity of applications such as Plymouth that don't need to use special accelerated operations provided by driver-specific ioctls.[130] The feature was exposed by libdrm from version 2.4.25 onwards.[131] Later that year it also gained a new main type of objects, called planes. Planes were developed to represent hardware overlays supported by the scanout engine.[132][133] Plane support was merged into Linux 3.3.[134] and libdrm 2.4.30. Another concept added to the API —during Linux 3.5[135] and libdrm 2.4.36[136]][137] Since Airlie was trying to mimic the NVIDIA Optimus technology, he decided to name it "PRIME".[7] Airlie resumed his work on PRIME in late 2011, but based on the new DMA-BUF buffer sharing mechanism introduced by Linux kernel 3.3.[138] The basic DMA-BUF PRIME infrastructure was finished in March 2012[139] and merged into the Linux 3.4 release,[140][141][142] as well as into libdrm 2.4.34.[143] Later during the Linux 3.5 release, several DRM drivers implemented PRIME support, including i915 for Intel cards, radeon for AMD cards and nouveau for NVIDIA cards.[144][145]
In recent years, the DRM API has incrementally expanded with new and improved features. In 2013, as part of GSoC, David Herrmann developed the multiple render nodes feature.[53] His code was added to the Linux kernel version 3.12 as an experimental feature[146][147] supported by i915,[148] radeon[149] and nouveau[150] drivers, and enabled by default since Linux 3.17.[75] order to maintain the API backwards compatible, the feature is exposed by DRM core as an additional capability that a DRM driver can provide. Universal plane support debuted in Linux 3.15[152] and libdrm 2.4.55[153]. Several drivers, such as the Intel i915[154], have already implemented it.
The most recent DRM API enhancement is the atomic mode-setting API, which brings atomicity to the mode-setting and page flipping operations on a DRM device. The idea of an atomic API for mode-setting was first proposed in early 2012.[155] Ville Syrjälä (Intel) took over the task of designing and implementing such atomic API.[156] Based on his work, Rob Clark (Texas Instruments) took a similar approach aiming to implement atomic page flips.[157] Later in 2013 both proposed features were reunited in a single one using a single ioctl for both tasks.[158] Since it was a requirement, the feature had to wait for the support of universal planes to be merged in mid-2014.[154] During the second half of 2014 the atomic code was greatly enhanced by Daniel Vetter (Intel) and other DRM developers[159]:18 in order to facilitate the transition for the existing KMS drivers to the new atomic framework.[160] All of this work was finally merged into Linux 3.19[161] and Linux 4.0[162][163][164] releases, and enabled by default since Linux 4.2.[165] libdrm exposed the new atomic API since version 2.4.62.[166] Multiple drivers have already been converted to the new atomic API.[167].[168].[169]
nvidia-modeset.ko
nvidia.ko
GEM essentially deals with graphics buffer objects (which can contain textures, renderbuffers, shaders, or all kinds of other state objects and data used by the gpu)
GEM flink has lots of issues. The flink names are global, allowing anyone with access to the device to access the flink data contents.
gem-flink doesn't provide any private namespaces to applications and servers. Instead, only one global namespace is provided per DRM node. Malicious authenticated applications can attack other clients via brute-force "name-guessing" of gem buffers
Many modern high-end GPUs come with their own memory managers. They even include several different caches that need to be synchronized during access. [...] . Therefore, memory management on GPUs is highly driver- and hardware-dependent..
A more subtle limitation is that the driver couldn't handle interrupts, so there wasn't any hot-plug monitor support.
uses an onboard display chip that is integrated into the management chip Hi1710 and uses the IP core of the SM750.
right now there's 17 drivers supporting atomic modesetting merged into the DRM subsystem | http://enc.tfode.com/Direct_Rendering_Manager | CC-MAIN-2018-13 | refinedweb | 1,529 | 54.93 |
usleep(3) BSD Library Functions Manual usleep(3)
NAME
usleep -- suspend thread execution for an interval measured in microsec- onds
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <unistd.h> int usleep(useconds_t useconds);
DESCRIPTION
The usleep() function suspends execution of the calling thread until either useconds microseconds have elapsed or a signal is delivered to the thread whose action is to invoke a signal-catching function or to termi- nate the thread or process. The actual time slept may be longer, due to system latencies and possible limitations in the timer resolution of the hardware. This function is implemented, using nanosleep(2), by pausing for useconds microseconds or until a signal occurs. Consequently, in this implementa- tion, sleeping has no effect on the state of process timers and there is no special handling for SIGALRM.
RETURN VALUES
The usleep() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.
ERRORS
The usleep() function will fail if: [EINTR] A signal was delivered to the process and its action was to invoke a signal-catching function.
SEE ALSO
nanosleep(2), sleep(3)
HISTORY
The usleep() function appeared in 4.3BSD. BSD February 13, 1998 BSD
Mac OS X 10.8 - Generated Fri Aug 31 18:17:13 CDT 2012 | http://www.manpagez.com/man/3/usleep/ | CC-MAIN-2014-35 | refinedweb | 222 | 50.26 |
Stripping out email addresses
Discussion in 'Perl' started by Kelly, Apr 28, 2004.,490
- Joerg Jooss
- Sep 2, 2005
Stripping out punctuation marksdew, Feb 6, 2006, in forum: ASP .Net
- Replies:
- 1
- Views:
- 431
- Nathan Sokalski
- Feb 7, 2006
Program not Stripping Headers from Email though Working finedont bother, Mar 4, 2004, in forum: Python
- Replies:
- 1
- Views:
- 270
- Ben Finney
- Mar 4, 2004
using regex to pull out email addressesKun, Mar 25, 2006, in forum: Python
- Replies:
- 1
- Views:
- 349
- Arne Ludwig
- Mar 25, 2006
Physical Addresses VS. Logical Addressesnamespace1, Nov 29, 2006, in forum: C++
- Replies:
- 3
- Views:
- 926 | http://www.thecodingforums.com/threads/stripping-out-email-addresses.25003/ | CC-MAIN-2014-49 | refinedweb | 101 | 63.02 |
Operating systems, development tools, and professional services
for connected embedded systems
for connected embedded systems
lsearch()
Perform a linear search in an array
Synopsis:
#include <search.h> void * lsearch( const void * key, const void * base, unsigned * num, unsigned width, int ( * compare)( const void * element1, const void * element2 ) );
Arguments:
- key
- The object to search for.
- base
- A pointer to the first element in the table.
- num
- A pointer to an integer containing the current number of elements in the table.
- width
- The size of an element, in bytes.
- compare
- A pointer to a user-supplied function that lsearch() calls to compare an array element with the key. The arguments to the comparison function are:
- element1 -- the same pointer as key
- element2 -- a pointer to one of the array elements.
The comparison function must return 0 if element1 equals element2, or a nonzero value if the elements aren't equal.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The lsearch() function searches a linear table and returns a pointer into the table indicating where the entry was found.
Returns:
A pointer to the element that was found or created, or NULL if an error occurred.
Examples:
This program builds an array of pointers to the argv arguments by searching for them in an array of NULL pointers. Because none of the items will be found, they'll all be added to the array.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <search.h> int compare( const void *, const void * ); int main( int argc, const char **argv ) { int i; unsigned num = 0; char **array = (char **)calloc( argc, sizeof(char **) ); for( i = 1; i < argc; ++i ) { lsearch( &argv[i], array, &num, sizeof(char **), compare ); } for( i = 0; i < num; ++i ) { printf( "%s\n", array[i] ); } return EXIT_SUCCESS; } int compare( const void *op1, const void *op2 ) { const char **p1 = (const char **) op1; const char **p2 = (const char **) op2; return( strcmp( *p1, *p2 ) ); }
Using the program above, this input:
one two one three four
produces the output:
one two three four | http://www.qnx.com/developers/docs/6.3.2/neutrino/lib_ref/l/lsearch.html | crawl-003 | refinedweb | 350 | 60.95 |
#include <wefts_cleanup.h>
#include <wefts_cleanup.h>
Collaboration diagram for Wefts::CleanupItem:
[inline]
Empty constructor that leaves the fields uninitialized.
Basic Constructor.
Initializes only the handler. Faster and to be used if the handler handleCleanup routine does not needs its parameters.
Position constructor To be used when the handler does not use the object pointer referring the cleared object; usually, this happens when the object to be cleared is "this", so the handler's handleCleanup() routine can access "this" to get the object to clear.
This leaves caller member uninitialized, sparing time.
Complete constructor.
Fills all the three elements of the class.
Object of which cleanup is requested.
The pointer to the handler object of which handler->handleCleanup() must be called.
Position passed as first parameter to handler->handleCleanup(). | http://wefts.sourceforge.net/wefts-apidoc-0.99b/classWefts_1_1CleanupItem.html | CC-MAIN-2017-30 | refinedweb | 128 | 50.63 |
Hi everyone,
I join this community in the spirit that hopefully I can help (at least where I can) and learn. I feel a bit like a noob not knowing the actual formalities when joining a forum such as this but basically I started learning ruby this semester and I have found it strangely addictive.
Oh, with the tiny question...
I have a script that is basically as such:
#used to readjust dates when months are days are added to it
def function(x,y,z)
valid = false
until var == true
case z
when 1
#do something
when 2
#do something
else
var = true
end
end
The point I am really trying to get across is:
when the 'when' is satisfied, does it go to the next 'when' then 'else'
If it is appropriate I can post the code... it isn't excessive in length.
Any thoughts or input would be appreciated.
[edit] Apologies all, just my logic playing tricks on me | http://forums.devshed.com/ruby-programming-142/hello-tiny-question-statement-749951.html | CC-MAIN-2015-35 | refinedweb | 162 | 65.46 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.