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 |
|---|---|---|---|---|---|
Difference between revisions of "Code snippets"
Revision as of 14:08, 13",ScriptWorkbench())
A typical module file
This is an example of a main module file, containing everything your module does. It is the Scripts.py file invoked by the previous example. You can have all your custom commands here.
import FreeCAD, FreeCADGui class ScriptCmd: def Activated(self): # Here your write what your ScriptCmd does... FreeCAD.PrintMessage("Hello, World!\n") def GetResources(self): return {'Pixmap' : 'path_to_an_icon/myicon.png', 'MenuText': 'Short text', 'ToolTip': 'More detailed text'} FreeCADGui.AddCommand('Script_Cmd', ScriptCmd())
Import a new filetype
Making an importer for a new filetype in FreeCAD is easy. FreeCAD doesn't consider that you import data in an opened document, but rather that you simply can directly open the new filetype. So what you need to do is to add the new file extension to FreeCAD's list of known extensions, and write the code that will read the file and create the FreeCAD objects you want:
This line must be added to the InitGui.py file to add the new file extension to the list:
# Assumes Import_Ext.py is the file that has the code for opening and reading .ext files FreeC) doc.recompute()
Adding a polygon
A polygon is simply a set of connected line segments (a polyline in AutoCAD). It doesn't need to be closed.
import Part,PartGui doc=App.activeDocument() n=list() # create a 3D vector, set its coordinates and add it to the list v=App.Vector().Mesh() # build up box out of 12 facets m.addFacet(0.0,0.0,0.0, 0.0,0.0,1.0, 0.0,1.0,1.0) m.addFacet(0.0,0.0,0.0, 0.0,1.0,1.0, 0.0,1.0,0.0) m.addFacet(0.0,0.0,0.0, 1.0,0.0,0.0, 1.0,0.0,1.0) m.addFacet(0.0,0.0,0.0, 1.0,0.0,1.0, 0.0,0.0,1.0) m.addFacet(0.0,0.0,0.0, 0.0,1.0,0.0, 1.0,1.0,0.0) m.addFacet(0.0,0.0,0.0, 1.0,1.0,0.0, 1.0,0.0,0.0) m.addFacet(0.0,1.0,0.0, 0.0,1.0,1.0, 1.0,1.0,1.0) m.addFacet(0.0,1.0,0.0, 1.0,1.0,1.0, 1.0,1.0,0.0) m.addFacet(0.0,1.0,1.0, 0.0,0.0,1.0, 1.0,0.0,1.0) m.addFacet(0.0,1.0,1.0, 1.0,0.0,1.0, 1.0,1.0,1.0) m.addFacet(1.0,1.0,0.0, 1.0,1.0,1.0, 1.0,0.0,1.0) m.addFacet(1.0,1.0,0.0, 1.0,0.0,1.0, 1.0,0.0,0.0) # scale to a edge langth of 100 m.scale(100.0) # add the mesh to the active document me=doc.addObject("Mesh::Feature","Cube") me.Mesh=m property doc.recompute()
Accessing and changing representation of an object
Each object in a FreeCAD document has an associated view representation object that stores all the parameters that define how the object appear, like color, linewidth, etc...
gad=Gui.activeDocument() # access the active document containing all # view representations of the features in the # corresponding App document v=gad.getObject("Cube") # access the view representation to the Mesh feature 'Cube' v.ShapeColor # prints the color to the console v.ShapeColor=(1.0,1.0,1.0) # sets the shape color to white
Observing mouse events in the 3D viewer via Python
The Inventor framework allows to add one or more callback nodes to the scenegraph of the viewer. By default in FreeCAD() | https://wiki.freecadweb.org/index.php?title=Code_snippets&diff=prev&oldid=120 | CC-MAIN-2020-50 | refinedweb | 645 | 65.22 |
I'm trying ti use @RunAs("") annotation so as i can call a secured ejb from other one (TestEJBBean)
I've created an ejb and add this
@DeclareRoles("user")
@Stateless
@RunAs("user")
public class TestEJBBean implements ITestBean {
...
}
but i'm getting an exception The RunAs role "user" is not mapped to a principal. I tried to set the web.xml via setWebXML in my deployment method but it didnt work (i got another exception ).
(I'm running my tests under an embedded glassfish)
Any ideas !!
The problem was solved by definnig security-role-mapping in sun-web.xml and adding it in the deployment addAsWebInfResource("WEB-INF/sun-web.xml")
Retrieving data ... | https://developer.jboss.org/thread/230533 | CC-MAIN-2018-39 | refinedweb | 112 | 59.3 |
Stateless Session Bean Design Question. (1 messages)Hello, I am implementing a stateless session bean EJB 2.0 on WL 8.1. I am new to EJB, so my understanding is limited. This is more of a design question. I have a session bean, encapsulating a service. public class MySessionBean extends GenericSessionBean{ private MyService service = new MyService(); public Collection getRows(){ return service.getDao().getRows(); } } The service in this case MyService, initializes the DAO and queries the underlying table. The side effects that I am seeing here is that UI which initializes the Session Bean, is getting more rows than it should. By that I mean the first call to the method returns 1 row, 2nd call 2 rows and so on. The DAO was defined in the following fashion.. public class MyDao{ private List rows; public MyDao(){ rows = new ArrayList() } public List getRows(){ //Get connection. //Query. while(rs.hasNext()){ //populate the rows. } } } I have resolved the issue (or I think I did) by moving the "rows" attribute to the getRows() method. public List getRows(){ List rows = new ArrayList(); //Get connection. //Query. while(rs.hasNext()){ //populate the rows. } } However, I feel that the culprit here is the service declaration in the Stateless Session Bean. It looks like EJB is caching the service reference by the virtue of it's initialization. The service inturn is caching the DAO. Ideally this should be behaving stateless, i.e. every call should not know of the previous call. My question is - Is the service declaration correct? Should it be more an part of the EJB init? Or EJB constructor? Are there other alternative design approaches to this one? Thank you in advance for your response. RJ
Threaded Messages (1)
- Re: Stateless Session Bean Design Question. by Johnny Zetterstrom on March 11 2008 12:42 EDT
Re: Stateless Session Bean Design Question.[ Go to top ]
The most important thing about a stateless session bean is that it should not have state :) So don't declare any members. Instead handle everything within the method calls. The EJB container caches stateless session bean instances and re-uses them for subsequent requests. It is up to you to guarantee their stateless behavior. Johnny Webworks JEExplorer - file explorer for your Java web applications
- Posted by: Johnny Zetterstrom
- Posted on: March 11 2008 12:42 EDT
- in response to R J | http://www.theserverside.com/discussions/thread.tss?thread_id=48541 | CC-MAIN-2017-09 | refinedweb | 390 | 68.36 |
by Re Lai
Learn how to take advantage of new features in JSF 2.0 and integrate Flex and JavaFX into your JSF applications
Published March 2011
The JavaServer Faces (JSF) 2.0 specification builds on the success and lessons from the last six years of usage of the JSF 1.0 specification. It takes inspiration from Seam and other Web frameworks and incorporates popular agile practices, such as convention over configuration and annotation over XML. This results in a much streamlined framework. Highlights include standardized AJAX support, Facelets as the default view technology, and custom composite components, which finally make component authoring straightforward and even enjoyable. A good overview of JSF 2.0 can be found here.
This article explores how these new features can be utilized to facilitate embedding rich client applications. Adobe Flex has been a popular rich Internet application framework. JavaFX, while relatively new, builds on top of the Java platforms and has attracted much attention. There has been constant interest in integrating rich clients into Java Web applications. With JSF 2.0 and its focus on simplified development, integration has become easier than ever.
We start with a sample Flex pie chart application that displays the results of a survey about the popularity of ice cream flavors. A JSF composite component is used to encapsulate the embedding. Next, instead of hard-coding, the survey result is passed to the Flex application from a JSF managed bean. Then, we further enhance the sample by adding server round-trips that submit a user’s choice of the favorite flavor. Finally, we re-implement the chart in JavaFX and show how to embed it into the JSF application.
The source code for the sample application can be downloaded here.
The application is developed using Flex SKD 4.1, JSF Mojarra Implementation 2.0.2, and JavaFX SDK 1.3.1. NetBeans 6.9.1 is used as the IDE, which already bundles the latter two libraries. The three attached projects are SampleChartFlex, SampleChartFX, and SampleWeb.
To run the Web application inside NetBeans, open these projects using NetBeans, right-click project SampleWeb, and run.
To modify and compile the Flex project, you need to install Flex SKD 4 and modify SampleChartFlex/build.xml to point to the Flex SKD installation location:
<!-- Change me to your Flex SDK installation location --> <property name="FLEX_HOME" value="C:/Programs/Adobe/flex_sdk/4.1"/>
Afterward, you can invoke the Build command from NetBeans to build these projects. The ant build files of both the SampleChartFlex and SampleChartFX projects are customized so that the packaged swt or jar files are copied into project SampleWeb automatically during the building of these two projects by NetBeans.
First, we create a simple pie chart application in Flex to display the popularity of ice cream flavors, as shown in Figure 1. You click a chart item. The message label then displays your choice.
Figure 1 Simple Pie Chart Application
Flex source code (SampleChartFlex.mxml):
<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns: <mx:PieChart <mx:series> <mx:PieSeries </mx:series> </mx:PieChart> <s:Label <fx:Script> <![CDATA[ import mx.collections.ArrayCollection; import mx.charts.events.ChartItemEvent; private function getChartData() : ArrayCollection { return new ArrayCollection ([ {flavor: "Vanilla", rank: 60}, {flavor: "Chocolate", rank: 30}, {flavor: "Strawberry", rank: 10} ]); } private function onItemClick(event : ChartItemEvent) : void { var flavor : String = event.hitData.chartItem.item.flavor; message.text = "You chose " + flavor + "."; } ]]> </fx:Script> </s:Application>
The Flex application consists of a pie chart and a message label. The pie chart data is provided by function getChartData(). When a user clicks a chart item, onItemClick processes the event and updates the message label. The source file is compiled into SampleChartFlex.swf using mxmlc. The provided sample project SampleChartFlex has customized its ant build.xml file, which invokes mxmlc when you build the project.
To embed the Flash object into our JSF Web application, we first add SampleChartFlex.swf into folder resources/demochart of the Web content of our JSF application project SampleWeb.. The following is our custom component demo:chart.
JSF composite component source code (resources/demo/chart.xhtml):
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" xmlns: <!-- INTERFACE --> <cc:interface> <"; swfobject.embedSWF(swfUrl, replaceElementId, "500", "500", "10.0.0"); })(); </script> <div id="${cc.clientId}:chart" /> </cc:implementation> </html>
The open source SWFObject is used to embed the Flash content. The JavaScript file, swfobject.js, can be found under folder templates\swfobject of the Flex 4 SDK installation. Copy it into folder resources\demochart of our Web content.
Effort was made to mitigate name conflicts: Our local variables are defined in an anonymous function and the div HTML element ID is prefixed with the composite component client ID.
Now that we’ve created the custom component, we can use tag demo:chart just like any other JSF tags. It is transparent that Flex is used in the implementation. Here’s an example.
JSF page source code (index.xhtml):
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns="" xmlns: <h:head> <title>Spice up your JSF Pages</title> </h:head> <h:body> <f:view> <h1> Spice Up Your JSF Pages </h1> <demo:chart /> </f:view> </h:body> </html>.
JSF managed bean source code (IceCreamSurvey.java):
package demo.data; import java.util.HashMap; import java.util.Map; import javax.faces.bean.ManagedBean; @ManagedBean public class IceCreamSurvey { public Map<String, Integer> getResult() { Map<String, Integer> result = new HashMap<String, Integer>(); result.put("Vanilla", Integer.valueOf(60)); result.put("Chocolate", Integer.valueOf(30)); result.put("Strawberry", Integer.valueOf(10)); return result; } }.
JSF composite component source code snippet (resources/demo/chart.xhtml):
<!-- INTERFACE --> <cc:interface> <cc:attribute <"; var expressInstall = ""; var flashVars = {data: "${cc.attrs.data}"}; swfobject.embedSWF(swfUrl, replaceElementId, "500", "500", "10.0.0", expressInstall, flashVars); })(); </cc:implementation>
Now in the consuming JSF page, we just need to pass the ice cream flavor survey result to the demo:chart tag.
JSF page source code snippet (index.xhtml):
<demo:chart
On the Flex application side, we need to modify function getChartData to fetch the parameter.
Flex source code snippet (SampleChartFlex.mxml):
private function getChartData() : ArrayCollection { // Retrieve "data" from flashVars, // Formatted as Map.toString(), e.g., {Strawberry=10, Chocolate=30, // Vanilla=60} var input : String = Application.application.parameters.data; var data : Array = input ? input.split(/\W+/) : []; var source = []; for (var index : int = 1; index < data.length - 1; index += 2) { source.push( (flavor: data[index], rank: parseInt(data[index+1])} ); } return new ArrayCollection(source); }
In this example, the data format is simple. We, therefore, just parse it using regular expressions. In more complicated cases, formal encoding such as JavaScript Object Notation (JSON) can be considered.
In this section, we move on to a more complicated scenario: round-trip communications between Flex and JSF server sessions. This section presents a novel, yet practical, approach to integrating the best of Flex and JSF using the JSF 2.0 AJAX feature.
There are a number of ways Flex applications can communicate with servers.
LiveCyle Data Service is the data solution provided by Adobe that umbrellas several technologies, including the Java server-based BlazeDS and Action Message Format (AMF). The service would be particularly appealing if it were possible to devote both the client and server sides to a complete Adobe solution, although open sourcing of BlazeDS and AMF makes it possible to work with other technologies. Noticeably, recent development in Spring Flex and Grails Flex integration is basically built on top of BlazeDS and AMF.
Flex also provides generic data access components to communicate with servers, including HTTP and Web services. This allows Flex to interoperate with various server technologies, including JSF.
In addition, Flex has good integration with JavaScript, enabling us to integrate at the browser side, relaying to the AJAX application to communicate with servers.
Realistically, these approaches all can be used with JSF, each with its pros and cons. Exadel Fiji, for example, offers support for integration of Flex/JavaFX with JSF using all of the approaches above.
With the arrival of JSF 2.0, one interesting aspect is that the AJAX API has been standardized. In this section, we will exploit the feature to integrate Flex applications with JSF. It is in essence integration at the browser side. We’ll rely on the JSF AJAX framework to handle session and view state tracking. Because the JSF AJAX API is part of the 2.0 specification, it is guaranteed to be supported by all implementations. On the server side, it is fairly transparent that a Flex client is used. This approach is, therefore, easy to plug in to an existing JSF application.
The additional JSF AJAX layer conceivably would add performance overhead. This should not be an issue when the data exchange is small, which should be true for the majority of AJAX cases. However, if a large amount of data is exchanged, direct server access, such as with the first two approaches we mentioned above, should be considered.
We’ll modify our sample by submitting the selection when a user clicks on a flavor in the pie chart. A JSF managed bean would process the selection and reply with a message, which is in turn displayed in the Flex application. On the Flex application side, we’ll modify function onItemClick to use ExternalInterface to invoke JavaScript function demo.ajax.submit inside the embedding Web page, which we will define shortly.
Flex source code snippets (SampleChartFlex.mxml):
private function onItemClick(event : ChartItemEvent) : void { var flavor : String = event.hitData.chartItem.item.flavor; ExternalInterface.call("demo.ajax.submit", flavor); }
Add a callback function named refresh to update the message label. The function is exposed to JavaScript via ExternalInterface.addCallback during the initialization of the Flex application, as follows:
<s:Application xmlns: ... private function init() : void { ExternalInterface.addCallback("refresh", refresh); } private function refresh(feedback : String): void { message.text = feedback; }
For our JSF composite component, we’ll add one more attribute, response, in the interface section, which is mapped to the server response to our asynchronous submit.
JSF composite component source code snippets (resources/demo/chart.xhtml):
<cc:interface> <cc:attribute <cc:attribute </cc:interface>
Next, inside the implementation section, define a hidden form to submit to and receive response from the server:
<h:form <h:outputText </h:form>
Add the following JavaScript to handle the asynchronous submission and reply:
// namespace: demo if (!demo) var demo = {}; // namespace: demo.ajax if (!demo.ajax) demo.ajax = {}; demo.ajax.submit = function(arg) { var options = { input: arg, render: "${cc.clientId}:form:out", onevent: demo.ajax.onevent }; jsf.ajax.request("${cc.clientId}:form", null, options); }; demo.ajax.onevent = function(event) { if (event.status == "success") { var node = document.getElementById("${cc.clientId}:form:out"); var response = node.textContent || node.innerText; var chart = document.getElementById("${cc.clientId}:chart"); chart.refresh(response); } };
The function demo.ajax.submit is invoked by Flex function onItemClick to submit the request to the server. It uses the JSF 2.0 JavaScript function jsf.ajax.request to submit an asynchronous request using the hidden form with the following options:
The payload is sent as the pass-through request parameter named input.
It instructs the server to render the child outputText named out inside the form.
The server response would be processed by event handler demo.ajax.onevent.
The demo.ajax.onevent handles the AJAX submit events. Upon success, it fetches the response from the outputText node, and calls the refresh method exposed by Flash. It works around browser differences by trying to fetch the node text in different ways.
On the JSF server side, add the following to the JSF managed bean to process the submission.
JSF managed bean source code snippets (IceCreamSurvey.java):
private String selection; public String getSelection() { return selection; } public void setSelection(String selection) { this.selection = selection; } public String getSelectionResponse() { return reply(selection); } public String reply(String flavor) { return "Good choice! Many people also like " + flavor + "!"; }
In the consuming JSF page, we first add jsf.js to the page head to enable JSF JavaScript inside the page.
JSF page source code snippets (index.xhtml):
<h:outputScript
We need to further map the request parameter input as well as the response attribute exposed by our custom chart tag. There are several options to do this. One way is to utilize a JSF 2.0 enhancement that allows EL action binding to take variables, as follows:
<demo:chart
Another way is to leverage view parameters. You can map a request parameter to an EL expression via view parameters, as follows:
<f:metadata> <f:viewParam </f:metadata> <demo:chart
Each approach is interesting in its own right. The first one appears straightforward and involves fewer configurations. The second one relies on the view parameter, which is an editable value holder and can, therefore, take converters and validators. For cases where complicated encoding is needed, the second approach can be more appropriate.
We can similarly implement the chart application in JavaFX.
Figure 2 Implementing the Chart Application in JavaFX
JavaFX source code (demo.piechart.Main.FX):
package demo.piechart; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.chart.PieChart; import javafx.scene.chart.PieChart3D; import javafx.stage.AppletStageExtension; def piechart = PieChart3D { layoutX: 0.0 layoutY: 11.0 data: getChartData() } def message = javafx.scene.control.Label { layoutX: 189.0 layoutY: 340.0 text: "Click to choose your favorite flavor" } function getChartData() : PieChart.Data[] { // Retrieve "data" from the FX argument // Formatted as Map.toString(), e.g., {Strawberry=10, Chocolate=30, // Vanilla=60} var input = FX.getArgument("data") as String; var data = input.split("\\W+"); for (flavor in data where indexof flavor mod 2 == 1) { PieChart.Data { label: flavor value: Integer.parseInt(data[indexof flavor + 1]) action: function() {AppletStageExtension.eval("demo.ajax.submit('{flavor}')") } } } } function run(): Void { Stage { scene: Scene { height: 500 width: 500 content: [piechart, message] } } } // Call-back function to update the message label with the server response public function refresh (response : String) : Void { message.text = response; }
The code is intentionally made similar to our Flex application. The chart is populated by a run-time argument named data. We use AppletStageExtension to invoke the container page’s JavaScript function demo.ajax.submit. For JavaFX, it is easy to expose the callback function refresh. All script-level public functions are automatically visible to JavaScript in JavaFX.
To embed the JavaFX applet, copy SampleChartFX.jar and SampleChartFX_browser.jnlp into the resources/demochart folder of our Web content. Note the generated jnlp file by NetBeans points, by default, to a local codebase. Because we will specify the jar file location in our Web page anyway, simply remove the codebase attributes from the jnlp file.
Afterwards, we just need to make minor changes to our JSF composite component to embed the JavaFX applet.
JSF composite component source code snippets (resources/demo/chart.xhtml):
<script type="text/javascript" src="" target="head"/> <script type="text/javascript"> javafx( { archive: "${facesContext.externalContext.requestContextPath} + /resources/demochart/SampleChartFX.jar", draggable: true, width: 500, height: 500, code: "demo.piechart.Main", name: "${cc.clientId}:chart", id: "${cc.clientId}:chart" }, { data: "${cc.attrs.data}" } ); ...
Most of the JavaScript code would continue to work for our JavaFX applet. The only change is how JavaScript calls back into JavaFX. Inside the demo.ajax.onevent function, instead of chart.refresh(response), it should be chart.script.refresh(response). To allow the code work for both situations, use the following:
chart.refresh? chart.refresh(response) : chart.script.refresh(response)
That’s it. There is no need to change the consuming JSF page. Whether JSF or JavaFX is used to provide the chart is an implementation detail and is totally transparent to the consuming page.
In this article, we took advantage of new features in JSF 2.0 to integrate Flex and JavaFX into our JSF applications. These new capabilities in JSF free us from the need to take care of plumbing on encoding, decoding, view state tracking, and so on. In particular, we used the composite component feature to create a custom component to encapsulate the embedding of Flex and JavaFX.
See Also:
JavaFX download:
NetBeans IDE download:
Adobe Flex download:
Flex SDK download:
JavaServer Faces 2.0 download:
Re Lai works as a Senior Manager for Fusion CRM Application development at Oracle. He is a Sun Certified Enterprise Architect (SCEA) with more than 10 years of experience in the software industry. His current interest is building enterprise solutions using Java, scripting languages, and SOA. | http://www.oracle.com/technetwork/java/lai-flex-javafx-jsf-301278.html | CC-MAIN-2014-49 | refinedweb | 2,738 | 51.75 |
Basics of "stdio.h" in C
Get FREE domain for 1st year and build your brand new site
We all know that C is a general-purpose and Procedural programming language. And for most of us, It is the entry point or basic to learn other programming languages. In this article we'll discuss a bit about the Standard Header Library "stdio.h". Firstly we'll start by explaining about the structure of C program. Secondly, we discuss up on the Introduction to Header file(as we stick specific to "stdio.h"). Later, we look into specific attributes of Header file like - Built-in functions, Library Variables and Macro.
In short, stdio.h stands for standard input and output and is used to provide utilities supporting input and output features in C Programming Language.
Following are the sections of this article:-
1. Structure of C Program
We'll discuss the Structure of C program with a small example code. Let us consider the following example,
// Structure of C Program #include <stdio.h> // Header Files Inclusion int main(void) // Main Method Declaration { // Begin of Scope/Body of Function main() printf("OpenGenus is Awesome!"); // Printing the value to console // return's value depending upon the return type of the function return 0; } // End of Scope/Body of Function main() /* We can view the output at console as, OpenGenus is Awesome! */
From the above example, Generally Header Files consists many features so that, by including or importing the Header Files(
"stdio.h") we can consume the functionality. Basically these functions are called as "inbuilt" or "built-in" functions in C programming.
The prototype or signature and data definitions of these functions are present in their respective header files. And these Header files may also contain macros and variables specific to the library. In C program, the program execution starts from
main() and its signature is having a return type of integer(from our example). It also consists of body of the function inside which we include our custom logic.
In this article we are discussing in brief up on the "Header Files Inclusion" section for
"stdio. h".
2. Introduction to "stdio.h"
A header file in C is the one in which it contains function declarations/ definitions, variables and macro definitions to be shared between several source files and has a filename with extension ".h". Header file are of two types,
- Built-In
- User defined
Syntax to include any Header file, irrespective of its type
#include <filename.h>
Here
#include is a preprocessing directive(which informs the C compiler to include those specific files for the program). And
<filename.h> - a Header filename can be different as per the requirement for the specific functionality.
In many programming language, they have their own convention for getting the input from the user or sending the processed output to the user at the console. Similarly in C language we have this header file - "stdio.h".
Lets split the keyword into a small individual, So that we can bring a meaning to it later. The name of header file is
"stdio. h", i.e -
-
std- Standard
-
io- Input / Output
Hence, Its clear that this header file in C program is used for performing Basic or Standard Input/Output operations.
In other words, when we require Input/Output functionality in our program it can be achieved by including this header file at the beginning of the program.
3. Built-In Functions
As discussed in the previous section (section 1), Header files do have many functions. Built-in C functions in respect of
"stdio. h" file are as follows.
- Formatted Input / Output Functions
- printf(): To print the values onto the output screen.
- scanf(): To read a character, string, numeric data from keyboard.
- sprint(): Writes formatted output to string.
- sscanf(): Reads formatted input from a string.
- fprintf(): To Write formatted data to a file.
- fscanf(): To Read formatted data from a file.
- File Operation Functions
- fopen(): To Open a file.
- fclose(): Closes an opened file.
- remove(): To Delete a file.
- fflush(): To Flush a File Buffer.
- Character Input / Output Functions
- getc(): It reads character from a file.
- gets(): It reads line of string from keyboard.
- getchar(): It reads character from keyboard.
- puts(): It writes line of string to output console.
- putchar(): It writes a character to console.
- putc(): Writes a character to a file.
There are couple of more Functions that are available in this Header file. Above mentioned are the common Built-In Functions for the same.
4. Library Variables
Under this Header we have few specific variables, which we can define them for the ease of programming in our implementing code. A variable that is specific to the library are called as "Library Variables".
- Following are the variables defined in the header "stdio.h",
- size_t: This variable is result of the
sizeofkeyword and data type - unsigned integral type.
- FILE: An object type, which is suitable for storing information for a file stream.
- fpos_t: An object type, which is suitable for storing any position in a file.
5. Macros
A macro is a small snippet of code that is given a name and an expression which performs a tiny task.
Syntax to define a macro is as follows,
#define name expression
Here
#define - is a preprocessor directive.
name - can be any descriptive name.
expression - can be any small operation, that performs a repetitive calculation and returns result.
- Following are the Macros defined in the header "stdio.h",
- NULL: It contains the value of a null pointer constant.
- BUFSIZ: It is an integer, That represents the size of the buffer used by the setbuf function.
- EOF: It is a negative integer, That represents that the end-of-file has been reached.
- FILENAME_MAX: It is an integer, That represents the longest length of a char array suitable for holding the longest possible filename.
- TMP_MAX: It is the maximum number of unique filenames that the function tmpnam can generate.
Above are the common macros which are used, If we include
"stdio.h" in the implemented program.
6. Conclusion
Finally we are at the end of this article up on the discussion of Basic of "stdio.h". Further more we can think of exploring each and every Built-in function, Library variable and the Macro of the header file(
"stdio.h"). Similarly, we have more Header files in C programming language and they serve different functionality, feature and purpose
Hope it was an informative post. Thanks! | https://iq.opengenus.org/basics-of-stdio-h/ | CC-MAIN-2021-43 | refinedweb | 1,073 | 65.93 |
Vuebersicht
Inspired by Üebersicht, built with Vue, Electron, & TypeScript.
Add custom widgets to your desktop background, built as Vue single-file components, either in TypeScript or JavaScript.
Comes with an Üebersicht-like menu
...and Chromium / Vue Dev Tools
Widgets
Widgets are automatically imported from the
./src/widgets directory, each widget should follow the file naming convention of
<foo>.widget.vue. You may construct widgets using multiple Vue components, just make sure the root component of the widget has a filename ending in
.widget.vue, and child components do not.
Utilities
run - Run a shell command and return a promise.
import { run } from '@/utils' ... try { const stdout = await run('ls -la') } catch(e) { throw e }
Limitations
This is still just experimental. Because of the nature of nature of the current build tooling, I haven't yet found a way to enable some important features of the original Üebersicht application, hot-reloading in production builds, for instance. For now, it is recommended to run this experimental application in development mode.
Project setup
yarn install # or npm install
API keys
Vuebersicht currently ships with a Weather widget that uses 2 APIs, Google Geocoder API (for getting your approximate location), and Darksky API (to get local weather data for that location). You'll need to create these API keys and add them to an untracked file called
.env.local, in the root directory of the project.
GOOGLE_API_KEY = "<google geocoder api key>" DARKSKY_API_KEY = "<darksky api key>"
Note: Since Apple's aquisition of DarkSky, they are no longer allowing creation of API keys. An alternative API will most likely be required here.
Start the application
yarn serve # or npm run serve
Lints and fixes files
yarn lint # or npm run lint | https://vuejsexamples.com/a-reimagining-of-ubersicht-built-with-vue/ | CC-MAIN-2021-10 | refinedweb | 285 | 56.15 |
SPIlib is a thin wrapper to interact with SPI devices using the Linux “SPIdev” interface [1]
See the accelerometer example in the examples directory.
Usage is quite simple. First you have to build a Transfer:
from spi import spi_transfer, SPIDev transfer, buf, _ = spi_transfer(chr(0x1b), readlen=0)
This prepares a transfer which sends one byte (first parameter) and reads none (second parameter). It returns binary data which is then passed to SPIDev (the transfer buffer, the write buffer and the read buffer, the last ignored in the example). It is possible to change the write and read buffer beetween transfers (without altering their lenght of course!).
To actually do the transfer use do_transfer:
myspidev = SPIDev('/dev/spidev0.0') myspidev.do_transfers([transfer])
do_transfers takes a list of transfers to do in a single “session”, maintaining the device selected. For examples by using three transfers you can write one byte, read and write one at the same time, read one byte. Note that it is not possible to interact with data during a single “session” because of a limit of the Linux SPIDev interface (and thus of this. | https://pypi.org/project/SPIlib/ | CC-MAIN-2017-09 | refinedweb | 187 | 51.28 |
Release 0.5.7 Support for Retina view tests Fix issue #105 Using CACurrentMediaTime for GHRunForInterval so as to not interfere with swizzled NSDate methods. Release 0.4.29 to 0.5.6 TODO Release 0.4.29 Changing paths to use iOS instead of iPhone Rebuilding iOS project using XCode 4 Release 0.4.28 Building as GHUnitIOS.framework for iOS. Fix issue #37 Fix issue #38 Fix issue #39 Fix issue #36 Fix issue #19 Release 0.4.27 Added in GHUnitIOSAppDelegate for subclassing test app delegate Release 0.4.26 Fixing LLVM/clang warnings (Whitney Young, nolanw) GHAssertNotEqualStrings will allow for nils (Rusty Zarse) Build warnings under 10.6 (MacOSX); (zykloid) Better error handling on JUnit XML results writing (zykloid) GHAsyncTestCase#runForInterval (Adapted from Robert Palmer, pauseForTimeout) Release 0.4.25 Set DEPLOYMENT_POSTPROCESSING (MacOSX); So breakpointing doesn't warn about missing symbols Release 0.4.24 Moved build settings into xcconfig (MacOSX) Striping linked build Release 0.4.21 Moved build settings into xcconfig (iPhone) Flexible layouts; Works in iPad as universal app Release 0.4.20 Fix armv6/armv7 device build setting Release 0.4.19 Fix autorun env on iPhone Added re-run test (experimental!) Test log viewer (iPhone) Showing time in tests vs time running Release 0.4.18 Fixing test stats on parallel running Adding reraiseException options (MacOSX) Adding env var support for reraise and autorun (see README) Smaller font size for test view (iPhone) Show filename/line number in trace on failure Show link to exception filename on failure (MacOSX) Fix bug where test trace/log doesn't update if selected before running Release 0.4.17 Fixing disabled on new test bug Fixing bugs with All/Failed/Edit views not showing tests properly (MacOSX) Release 0.4.16 Fixing hidden tests bug Release 0.4.15 Text filter (MacOSX) Text filter now searches test case and test names (prefix) Failed filter (MacOSX/iPhone) Copy text in text view (MacOSX) Remember test state Release 0.4.14 Fix window resizing when showing details Adding test for 0 found test cases Release 0.4.13 Fixing framework build: Header error and 32/64 bit universal (MacOSX) Fixing SenTest macros not failing correctly Fixing persist of test enabled/disabled state Fixing SenTest macros Release 0.4.12 Fixing compile warning in main (iPhone) Release 0.4.11 Added value formatter (from); For better Assert error messages. Fixed deprecation warning (iPhone) Added default exception handler to give stack trace if triggered outside of GHUnit run Release 0.4.10 Added Search Bar Added GHTestSuite#suiteWithPrefix:options Release 0.4.9 Fix compile warning Release 0.4.8 Fix bug with turning Parallel off not working Building 32/64 bit universal Release 0.4.7 Removing redirect, was a bad idea; Test output goes to stderr, you can redirect stdout yourself Release 0.4.6 Redirecting test output to file Test output does OK/FAIL Disabled tests appear gray (MacOSX) UI fixes Release 0.4.5 (2008-07-21) Including GHUnitIOSAppDelegate so you can subclass and interact with UIApplication delegate in tests Release 0.4.4 (2008-07-20) Ignore disable/cancelled tests in scroll (iPhone) Only start group test (notify) if we have tests to run Release 0.4.3 (2008-07-20) When running test on main thread should wait until finished Auto scrolls to middle instead of bottom (iPhone) Release 0.4.2 (2008-07-19) Fixing run warning Release 0.4.1 (2008-07-18) Option to use NSOperationQueue to manage tests runs Updated how test groups run Handling failure in setUpClass/tearDownClass Updated how shouldRunOnMainThread works Added Edit UI for Mac OSX tests Bug fixes and other refactoring Release 0.3.19 (2008-06-15) Fixed bug in Edit->Save crash (iPhone) Tweaking test text color (iPhone) Re-run crash Added reset to GHTest protocol Added testDidUpdate: to GHTestDelegate protocol On Edit->Save, triggers reset Added cancel to GHTest protocol Added cancelling, cancelled enums to test status Changed testDidFinish to testDidEnd (since test may be cancelled) Release 0.3.18 (2008-06-15) Adding Run button; By default tests do not automatically run on start Added AutoRun setting Release 0.3.17 (2008-06-09) Updating RunTests.sh Release 0.3.16 (2008-06-09) Rebuilding from 3.0 GM Setting debug variables in main directly instead of from setenv (which doesn't seem to work) Release 0.3.14 (2008-06-08) Creating separate iPhone 3.0 builds Release 0.3.12 (2008-05-25) Creating iPhone static library with device and simulator platforms Release 0.3.11 (2008-05-20) Fixing version number Creating separate version with CoreLocation linked Release 0.3.10 (2008-05-20) Fix namespace issue Release 0.3.9 (2008-05-19) 2008-05-19 3.0 compatibility fixes Added GHUITestCase Added shouldRunOnMainThread to test case, and if present and YES will run the tests on the main thread 2008-05-05 (iPhone) Added select/deselect to iPhone test UI (iPhone) Fixed auto-scroll if you manually scroll (will stop auto-scrolling) Release 0.3.8 (2008-04-28) 2008-04-28 Removed button enabled cell from Mac OS X view; Makes NSOutlineView really slow; Need to figure out how to do it right Release 0.3.7 (2008-04-26) 2008-04-20 CLLocationManager mock Fixed afterDelay not using delay value Select/unselect (ignore) tests in Mac OSX view Added initWithTestSuite to GHTestApp for custom suites from test main 2008-04-16 Adding ability to set run loops in async test case Adding more methods to NSURLConnection mock Release 0.3.6 (2008-04-13) 2008-04-13 Adding swizzle methods for mocking Adding NSLocale mock Adding NSURLConnection, NSHTTPURLResponse mocks Fix bug with setUpClass/tearDownClass not working for single command line tests Setting Installation Directory to @rpath (Thanks chapados), so you can embed the framework with your app Sorting tests by class name (as well as method name) Release 0.3.4 (2009-04-11) 2008-04-11 Added Doxygen support 2008-04-08 Added GHAsyncTestCase for asynchronous tests (seems really complex :/, might have gone mental on it) Supporting streaming logging with GHTestLog(...) GHUNIT_VERSION from xcconfig in Info plists and shown in test GUI Mocks for NSURLConnection and NSHTTPURLResponse Added setUpClass/tearDownClass for GHTestCase Added currentSelector property for GHTestCase Release 0.3.3 (2009-04-08) 2009-04-08 Removed GTMLogger and GHLogger; Not used in Release and potentially can conflict with project logging with iPhone static library Release 0.3.2 (2009-04-05) 2009-04-05 Building as static library for iPhone Adding in support for running single test case or test Release 0.3.1 2009-03-22 Renamed TEST_CLI to GHUNIT_CLI Removing main from target; Projects should specify their own test target main. Added test for special registered test case classes 2009-03-21 Renamed Examples/MyTestable to MyTestable-IPhone 2009-03-19 Commented a bunch of the code Renamed GHTestUtils to GHTesting | https://cocoapods.org/pods/GHUnitOSX/changelog | CC-MAIN-2018-09 | refinedweb | 1,163 | 54.22 |
Closed Bug 463417 Opened 13 years ago Closed 12 years ago
import win32 nsinstall source into mozilla-central, build by default on win32
Categories
(Firefox Build System :: General, defect)
Tracking
(Not tracked)
mozilla1.9.2a1
People
(Reporter: ted, Assigned: benjamin)
Details
Attachments
(2 files)
We currently ship nsinstall.exe with MozillaBuild, and the win32 version isn't in mozilla-central. This is probably just for historical reasons. The down side is that if we find a bug in nsinstall, like bug 463411, it's very hard to fix. I don't see any reason we shouldn't just import the source and build it by default on win32. We will obviously have to account for the mingw cross-compile case, since the host won't be able to compile the native nsinstall there. cls: do you know of any other pitfalls we might hit here?
The host would be able to compile the unixy nsinstall.c, though, wouldn't it?
Yes, and Neil says we already do in that case.
Assignee: nobody → benjamin
Status: NEW → ASSIGNED
Attachment #387684 - Flags: review?
Comment on attachment 387684 [details] [diff] [review] Build nsinstall.exe as part of the builds, rev. 1 btw, i'm perfectly fine with you checking in a patch series (in fact, i think it's a good idea), the original and the one for review comments. That way someone can more easily compare with the original. Among other things, nsinstall's code style /generally/ includes a space between function and ( arguments ) ( and inside parens too ), which isn't typical for modern Gecko style. >diff --git a/config/nsinstall_win.c b/config/nsinstall_win.c >+ * The nsinstall command for Win32 most of this block is legacy, and could go for a good spring cleaning :) >+/* changes all forward slashes in token to back slashes */ google: did you mean backslashes :) >+void changeForwardSlashesTpBackSlashes ( wchar_t *arg ) >+int wmain(int argc, wchar_t *argv[ ]) over-indented: >+ return shellNsinstall ( argv + 1 ); >+shellNsinstall (wchar_t **pArgv) tabs :( >+ int retVal = 0; /* exit status */ >+ int retVal = 0; /* assume valid return */ please fix the spelling :) >+ /* check if directory alreay exists */
Attachment #387684 - Flags: review?(timeless) → review+
Status: ASSIGNED → RESOLVED
Closed: 12 years ago
Resolution: --- → FIXED
Comment on attachment 387684 [details] [diff] [review] Build nsinstall.exe as part of the builds, rev. 1 >-MOZ_PATH_PROGS(NSINSTALL_BIN, nsinstall ) Fortunately comm-central's configure.in still autodetects my custom nsinstall in the path... if I didn't have that luxury would it still be possible for me to use my custom version?
Ah, I figured it out, it will pick it up from the $NSINSTALL_BIN env variable.
Target Milestone: mozilla1.9.2b1 → mozilla1.9.2a1
Fwiw, (I assume it was from a repository sync') mozilla1.9.3a1: import the nsinstall.exe source from CVS buildtools repository: make it capable of copying files with very long names, build it by default on Windows hosts, and stop using the moztools version
Comment on attachment 428638 [details] [diff] [review] (Bv1-CC) Copy (the useful part of) it to comm-central, Copy bug 505574 too [Checkin: Comment 10]
Attachment #428638 - Attachment description: (Bv1-CC) Copy (the useful part of) it to comm-central, Copy bug 505574 too → (Bv1-CC) Copy (the useful part of) it to comm-central, Copy bug 505574 too [Checkin: Comment 10]
Product: Core → Firefox Build System | https://bugzilla.mozilla.org/show_bug.cgi?id=463417 | CC-MAIN-2021-25 | refinedweb | 548 | 62.38 |
Summary: in this tutorial, you’ll learn how to use Pandas fillna() function to fill in NaN value positions with custom value.
Replace NaN with custom value
While you can filter out NaN values out of Pandas data structures, values that could be relevant can also be discarded along with the process.
Rather than get rid of al the NaN values, you can replace them with other numbers that make a better sense using
fillna() function.
Suppose we have a simple DataFrame.
import pandas as pd import numpy as np df = pd.DataFrame({"name": ['Alfred', 'Batman', 'Catwoman'], "toy": [np.NaN, 'Batmobile', 'Bullwhip'], "reputation": [np.NaN, "Gotham", np.NaN], "movie": [np.NaN, 3, np.NaN], }) df
You can use
df.fillna() with a single argument to replace any NaNs with the value passed. In the example below, we replace NaN with 0.
df.fillna(0)
Please note that
fillna() returns a new Series or DataFrame with the NaNs replaced.
If you want to modify the existing data structure, you have to reassign the name to the returned result, or pass
inplace=True option.
df = df.fillna(0) #assign the old name to the new result # OR df.fillna(0, inplace=True)
Replace NaN with empty string
In order to replace NaN values with empty/blank strings, you can pass an empty string to
fillna().
df.fillna('')
Replace NaN with different value in each column
Passing a dictionary to
fillna() will cause it to look up NaN values in each column and replace it with the value specified in the dictionary (if it’s found).
Suppose we want to replace NaN in column
toy with
notoy and in column
reputation with
noreputation. We will pass
{"toy":"notoy", "reputation“
:"noreputation"} to fillna().
df.fillna({"toy":"notoy", "reputation":"noreputation"})
Replace NaN with median value
With fillna you can do lots of other things with a little creativity.
Having known that
series.mean() returns the average of all values in a Series, you might replace NaN with that value.
import pandas as pd from numpy import nan s = pd.Series([1, nan, 6, 9, nan, 14]) s.fillna(s.mean())
0 1.0 1 7.5 2 6.0 3 9.0 4 7.5 5 14.0 dtype: float64
Similarly, we can replace NaNs in a DataFrame, each NaN value will be replaced by the median value of the column it belongs to.
import pandas as pd from numpy import nan df = pd.DataFrame({'A' : [ 0, 10, nan, 5], 'B' : [2, 5, nan, 5], 'C' : [3, 6, 10, 6]}) df.fillna(df.mean())
You can chain two
mean() calls if you want the NaN values to be filled with the median of all values in the DataFrame.
import pandas as pd from numpy import nan df = pd.DataFrame({'A' : [ 0, 10, nan, 5], 'B' : [2, 5, nan, 5], 'C' : [3, 6, 10, 6]}) mean = df.mean().mean() df.fillna(mean)
Explanation : the first
mean() returns a Series of median values of each column and the second one calculates the average of them all.
Summary
fills NaNs with custom specified values.
fillna()
fillna()returns a new data structure by default, can be changed by passing
inplace=Trueoption.
fillna()can take in scalar (values), dict, Series, and even DataFrame.
| https://monkeybeanonline.com/pandas-fillna/ | CC-MAIN-2022-27 | refinedweb | 543 | 67.76 |
Using Swift Scripts with Xcode
Learn how to run Swift scripts as part of the Xcode build phase, giving you control to configure or validate your app while building your project.
Version
- Swift 5.5, iOS 15, Xcode 13
Building apps with Swift is a lot of fun — and it’s also fun to use it in the build process itself.
Xcode lets you run your own scripts as part of the build phases, but instead of limiting yourself to shell scripts only, you can leverage your knowledge and expertise in Swift and do more with less effort.
In this tutorial, you’ll learn how to create build scripts in Swift and create operations for your build process. You’ll create four different scripts that cover a wide variety of operations you can perform on your projects. For example:
- Creating a basic script and executing it as you build the project
- Configuring input and output files for scripts
- Reading the project’s settings and adding custom values yourself
- Altering project resources during build time
- Executing command-line operations from your code
Getting Started
Download the starter project by clicking the Download Materials button at the top or bottom of the tutorial. Unzip it and open HelloXcode.xcodeproj in the starter folder.
The app itself doesn’t do much. Build and run. You’ll see a view controller with some text:
For this tutorial, you’ll work in the Scripts folder.
Writing Hello Xcode
Create a new Swift file under Scripts and name it HelloXcode.swift. Add the following code:
import Foundation @main enum MyScript { static func main() { print("Hello Xcode") } }
The code above prints “Hello Xcode” in the console.
Then, open the terminal, navigate to the Scripts folder and execute this command:
xcrun swiftc -parse-as-library HelloXcode.swift
cdfollowed by the path you want to reach. For example
cd /Users/your_user_name/SwiftBuildPhase/Starter/Scripts/
This will compile your Swift file and create an executable binary with the same name.
Next, run this command:
./HelloXcode
This will print Hello Xcode in your terminal window.
You just created a very basic application that does nothing except print the text Hello Xcode. You compiled this application and executed it. If you double-click the compiled file, it’ll open a new terminal window with some more messages before and after Hello Xcode.
........Scripts/HelloXcode ; exit; Hello Xcode logout Saving session... ...copying shared history... ...saving history...truncating history files... ...completed. [Process completed]
xcrun can take several parameters one of them is
-parse-as-librarywhich specifies to treat this file as a library otherwise, it’ll complain about the
@main attribute.
You can also specify what kind of SDK you want to compile the code against. Ideally, since you’re going to execute them from Xcode, it makes sense to use the macOS SDK. You can also rename the output file to something specific using the
-o attribute.
Your build command should be:
xcrun --sdk macosx swiftc -parse-as-library HelloXcode.swift -o CompiledScript
This command compiles HelloXcode.swift using the macOS SDK. The output file will be named CompiledScript.
Understanding Build Phases
Compiling your Swift file and executing it from Xcode is as easy as doing it from the terminal. All you need to do is define a New Run Script Phase and add the commands you executed on the terminal into it.
From the Project navigator, select the project file. Then in Build Phases add a new phase and select New Run Script Phase from the drop-down menu.
The Build Phases tab is the central point for Xcode’s build operation. When you build any project, Xcode does a number of steps in order:
- Identifies the dependencies and compiles them.
- Compiles the source files.
- Links the compiled files with their compiled dependencies.
- Copies resources to the bundle.
However, you may want to add your own operations at specific moments. For this tutorial, you’ll add new operations to the beginning — so when you add a new run script phase, drag it to the top of the list.
Going back to the new phase you added a moment ago, delete the commented line and add these commands:
xcrun --sdk macosx swiftc -parse-as-library Scripts/HelloXcode.swift \ -o CompiledScript ./CompiledScript
The difference between this and what you did before on the terminal is that Xcode executes these scripts on the path of the project file — that’s why adding Scripts/ is important.
Build the project to try out the new script and build phase you just added, then open the build log when it finishes. You’ll see the message you printed logged directly in Xcode’s log.
Exploring Input and Output Files
Xcode’s run phase allows you to specify files as configuration instead of having them explicit in the script. Think of it as sending a file as a parameter to a function. This way, your scripts can be more dynamic and portable to use.
In the run phase you added, add to the Input Files list $(SRCROOT)/Scripts/HelloXcode.swift and update the script to:
xcrun --sdk macosx swiftc -parse-as-library $SCRIPT_INPUT_FILE_0 \ -o CompiledScript ./CompiledScript
This doesn’t cause any changes to the execution of the scripts, but it makes Xcode more aware of the files you will change or use in your scripts. It will validate the existence of the input files and will make sure that files that are an output of a script then an input of another are used in the correct order.
Accessing Environment Variables
Sending file paths as parameters can be useful, but it’s not enough. Sometimes you’ll need to read information related to the project itself — like, is this a release or debug build? What is the version of the project? Or the name of the project?
When Xcode executes any run script phase, it shares all its build settings through environment variables. Think of environment variables as global variables. You can still read them from your Swift code. In HelloXcode.swift, add the following in
main():
if let value = ProcessInfo.processInfo.environment["PRODUCT_NAME"] { print("Product Name is: \(value)") } if let value = ProcessInfo.processInfo.environment["CONFIGURATION"] { print("Configuration is: \(value)") }
The code above reads the values for the environment variables “PRODUCT_NAME” and “CONFIGURATION” and prints them to Xcode’s log.
Build and open the build log. You’ll see the two values printed in the log:
When you open the details of the run script phase from the log, you’ll see all the build settings exported. You can read any of those values the same way you did with PRODUCT_NAME and CONFIGURATION. You can also read more to understand what each stands for in Apple’s Build Settings Reference.
In some cases, you’ll want to add your own custom settings for the project. This won’t make any difference for Xcode or its build process, but it could make a huge difference for your own custom scripts. Select the project file and go to Build Settings. Click on the + at the top, select Add User-Defined Setting and name the setting CUSTOM_VALUE. Enter This is a test value! as its value.
To read the new value you just added, add the following to HelloXcode.swift:
if let value = ProcessInfo.processInfo.environment["CUSTOM_VALUE"] { print("Custom Value is: \(value)") }
Build and you’ll see the new value you wrote printed in the log.
Incrementing the App Version
The next script you’ll create is designed to increment the version number of your app with each build. While you probably won’t ever have cause to increment the version number so frequently, this demonstrates how you could do it.
There are two values in the project’s Info.plist that represent the version:
- Bundle version: Represented by a number
- Bundle version string (short): Represented by two or three numbers like 1.12 (Major.Minor) or 1.3.16 (Major.Minor.Patch)
In this script, you’ll increment the bundle version with every build and the short string only when the build is a release build.
Create a new Swift file under the Scripts folder named IncBuildNumber.swift. Add the following to it:
import Foundation @main enum IncBuildNumber { static func main() { // 1 guard let infoFile = ProcessInfo.processInfo .environment["INFOPLIST_FILE"] else { return } guard let projectDir = ProcessInfo.processInfo.environment["SRCROOT"] else { return } // 2 if var dict = NSDictionary(contentsOfFile: projectDir + "/" + infoFile) as? [String: Any] { guard let currentVersionString = dict["CFBundleShortVersionString"] as? String, let currentBuildNumberString = dict["CFBundleVersion"] as? String, let currentBuildNumber = Int(currentBuildNumberString) else { return } // 3 dict["CFBundleVersion"] = "\(currentBuildNumber + 1)" // 4 if ProcessInfo.processInfo.environment["CONFIGURATION"] == "Release" { var versionComponents = currentVersionString .components(separatedBy: ".") let lastComponent = (Int(versionComponents.last ?? "1") ?? 1) versionComponents[versionComponents.endIndex - 1] = "\(lastComponent + 1)" dict["CFBundleShortVersionString"] = versionComponents .joined(separator: ".") } // 5 (dict as NSDictionary).write( toFile: projectDir + "/" + infoFile, atomically: true) } } }
- First, you need the location of the Info.plist file for the current project, which Xcode stored in the environment variable INFOPLIST_FILE, and the path of the project from SRCROOT.
- Next, with those values, you have the path of the .plist file. Read the file as a dictionary and fetch the two version values currently stored in it.
- Increment the build number.
- If the current build configuration is Release, break down the short version string and increment the last digit in it.
- Overwrite the .plist file with the dictionary after all the changes.
Go to the project’s Build Phases and add a new run script phase. You can copy the contents of the previous build script tab, but remember to add the new IncBuildNumber.swift file to the Input Files list.
Build the project a few times and check Info.plist with each build. You’ll see the Bundle version value change.
Change the Build Configuration of the project’s scheme to Release instead of Debug and build the project again.
You’ll see the two values updated in the .plist file.
Changing the App Icon
The third script you’ll implement changes the AppIcon based on your current build configuration. In most projects, you’d have a different icon set for each configuration, but for this one, you’ll do something a little more sophisticated. You’ll alter the images directly and rewrite them.
In the current Scripts folder, ImageOverlay.swift provides
addOverlay(imagePath:text:), which is a function for macOS using AppKit to add a text overlay in the bottom left corner on an existing image file. You’ll use it in this script.
Also, there is Shell.swift. It allows you to execute shell commands from Swift. You’ll learn about this in more detail in the next script.
Create a new Swift file in the same folder named AppIconOverlay.swift and add the following:
import Foundation @main enum AppIconOverlay { static func main() { // 1 guard let srcRoot = ProcessInfo.processInfo.environment["SRCROOT"], let appIconName = ProcessInfo.processInfo .environment["ASSETCATALOG_COMPILER_APPICON_NAME"], let targetName = ProcessInfo.processInfo.environment["TARGET_NAME"] else { return } // 2 let appIconsPath = "\(srcRoot)/\(targetName)/Assets.xcassets/\(appIconName).appiconset" let assetsPath = "\(srcRoot)/\(targetName)/Assets.xcassets/" let sourcePath = "\(srcRoot)/Scripts/AppIcon.appiconset" // 3 _ = shell("rm -r \(appIconsPath)") _ = shell("cp -r \(sourcePath) \(assetsPath)") // 4 guard let images = try? FileManager.default.contentsOfDirectory(atPath: appIconsPath) else { return } // 5 let config = ProcessInfo.processInfo.environment["CONFIGURATION"] ?? "" // 6 for imageFile in images { if imageFile.hasSuffix(".png") { let fileURL = URL(fileURLWithPath: appIconsPath + "/" + imageFile) addOverlay(imagePath: fileURL, text: "\(config.prefix(1))") } } } }
- As with the previous script, you read the environment variables. Here, you need the path of the project file, the target name and the name of the AppIcon assets.
- Then, you define the paths you’ll use: the path to the AppIcon assets, the path to the assets folder as a whole and the path of the original unmodified assets present in the scripts folder.
- Delete the icon assets from the project and copy the unmodified ones from Scripts through shell commands. This is like a reset to the images so you don’t keep adding overlays on top of each other.
- Load the list of files present in the AppIcons assets folder so you can modify them one by one.
- Fetch the current build configuration.
- Loop over the files and, if the file is a PNG image, add an overlay of the first letter of the current configuration on top of it.
Add a new script to the build phases like the previous two and move it to the top — but this time, you want to include the three Swift files, Shell.swift, OverlayLabel.swift and ImageOverlay.swift, directly in the script and the AppIconOverlay.swift file as part of the Input Files. The shell script in the new run phase should be:
xcrun --sdk macosx swiftc \ -parse-as-library $SCRIPT_INPUT_FILE_0 Scripts/Shell.swift \ Scripts/OverlayLabel.swift Scripts/ImageOverlay.swift -o CompiledScript ./CompiledScript
Along with your input file, you’re passing all the needed Swift files for your code to compile successfully. This means you’re not limited to writing one file, and you can create your own reusable code for your scripts.
Build the project once on Debug and once on Release. Observe the changes on the AppIcon.
Linting Your Project
In your previous scripts, you automated some operations on the resources used by the project. In this script, you’ll run a validation on the project itself using SwiftLint and interrupt the build process as a whole based on a remote configuration.
If you’re not familiar with SwiftLint, it’s a command-line tool that allows you to validate your Swift code against a set of rules to make sure it’s organized properly. It helps developers to quickly spot any formatting issues in their code and always keep the code organized and visually clean.
You’ll need to install SwiftLint on your machine before you start working on this script. The GitHub page provides different ways to install it. It’s best not to install it as a pod in the project, but instead to install it directly on the machine.
Once you finish installing it, open a terminal window and navigate through the command line to the project’s folder. Then, run the following command:
swiftlint --config com.raywenderlich.swiftlint.yml
You’ll see the result on the terminal with this message:
......ContentView.swift:42:1: warning: Line Length Violation: Line should be 120 characters or less: currently 185 characters (line_length) Done linting! Found 1 violation, 0 serious in 2 files.
documentation to learn more how to configure it.
This lint violation is intentional. Your script will run the same operation directly in the build process and check the number of violations found. If it doesn’t pass a certain threshold, your build process will continue. If it’s exceeded, the build will stop with an error.
Create a new Swift file in the Scripts folder and name it LintingWithConfig.swift. Add the following in the new file:
import Foundation import Combine @main enum LintingWithConfig { static func main() { startLinting(allowedWarnings: 1) } static func startLinting(allowedWarnings: Int = 0) { } }
The code adds the standard
main() that you saw in all the previous scripts and is only calling
startLinting(allowedWarnings:). You’ll do the first set of work on this method.
Utilizing the Shell
As mentioned earlier, Shell.swift provides a function to execute shell commands from Swift and returns the result of this command as a string.
So, to run the same command you just executed in a shell, all you need to do is add the following line in
startLinting(allowedWarnings:):
let lintResult = shell("swiftlint --config com.raywenderlich.swiftlint.yml") print(lintResult)
Add this new script to your build phases in a new run script phase and reorder it to the top. Remember to add the Swift file to the input files list, or you could hard code the file directly. You also need to compile Shell.swift with it.
xcrun --sdk macosx swiftc \ -parse-as-library $SCRIPT_INPUT_FILE_0 Scripts/Shell.swift -o CompiledScript ./CompiledScript
Build and open the log to see its output.
Controlling the Exit
You received the result of the command as a string. Add the following to the end of
startLinting(allowedWarnings:):
var logResult = lintResult .components(separatedBy: "Done linting!").last ?? "Found 0" logResult = logResult.trimmingCharacters(in: CharacterSet(charactersIn: " ")) .components(separatedBy: " ")[1] let foundViolations = Int(logResult) ?? 0
The first line separates the result by the text “Done linting!”, since you’re only interested in the part after you only take the last part of the array. To get the number of violations, the code separates the last part into single words and takes only the second word, which contains the number of violations found.
Next, you want to compare the found violations against the allowed number.
Add the following:
if foundViolations > allowedWarnings { print(""" Error: Violations allowed exceed limit. Limit is \(allowedWarnings) \ violations, Found \(foundViolations)! """) exit(1) } exit(0)
If the number exceeds the allowed, you print an informative message then exit the execution with an error.
exit(_:) allows you to terminate an execution. Passing any value other than zero means that there was an error and that is why the execution was terminated. Passing zero means that the operation finished everything required and the execution ended normally. In situations when you’re using scripts within scripts, you’ll use those numbers to identify one error from the other.
In
main(), change the value sent to
startLinting(allowedWarnings:) to 0 and build.
As expected, your build process stopped with an error.
You don’t want to hard code the allowed violations in your script. Ideally, you never want to have any violations and the ideal number should be zero. SwiftLint also provides that. But in larger projects that have a large team and a complex CI/CD pipeline, keeping this number as a strict zero would be inefficient. Allowing yourself and your team some flexibility would be very nice. A simple example for this is when you want to apply a new linting rule that would execute on thousands of lines of old code and you don’t want to update all of it in one go. You’ll want to take it one step at a time while keeping everything else under control.
For the next part, you’ll load the allowed violations limit from an external file in an asynchronous request before you execute the SwiftLint command.
At the end of the file, add this structure:
struct LintConfig: Codable { let allowedWarnings: Int }
Replace the content of
main() with the following:
var cancelHandler: AnyCancellable? let group = DispatchGroup() // 1 guard let projectDir = ProcessInfo.processInfo.environment["SRCROOT"] else { return } let configURL = URL(fileURLWithPath: "\(projectDir)/AllowedWarnings.json") // 2 let publisher = URLSession.shared.dataTaskPublisher(for: configURL) let configPublisher = publisher .map(\.data) .decode(type: LintConfig.self, decoder: JSONDecoder()) .eraseToAnyPublisher() // 3 group.enter() cancelHandler = configPublisher.sink { completion in // 4 switch completion { case .failure(let error): print("\(error)") group.leave() exit(1) case .finished: print("Linting Config Loaded") } } receiveValue: { value in // 5 startLinting(allowedWarnings: value.allowedWarnings) } // 6 group.wait() cancelHandler?.cancel()
Here’s what this does:
- Fetch the path of the project to build the path of the file that has the allowed violations limit. Normally, you’d want to have this file on a remote server, but for this tutorial, you’ll treat this file as the remote location.
- Create a combine publisher to load the contents of the file and map this publisher to the
LintConfigstructure you defined in the previous step.
- Call
enter()on the DispatchGroup object you defined, then fetch the value from the publisher.
- If the publisher failed to provide the value for any reason, exit the execution with an error to interrupt the build process.
- Use the value received by the publisher to call
startLinting(allowedWarnings:).
- Call
wait()on the DispatchGroup object to force the execution to wait.
Using DispatchGroup is very important here since combine is calling the request asynchronously. Without it, your script will not wait for the publisher to receive any value and will just finish execution before running your SwiftLint step. Calling
group.leave() when the publisher receives the data isn’t needed since
startLinting(allowedWarnings:) calls
exit(0) at the end.
Build and open the log. Your build will succeed and will show the same info as when you hard-coded the limit through code.
From Finder, open the file AllowedWarnings.json and change its contents to:
{"allowedWarnings":0}
Build again. As expected, the build will fail because the config file doesn’t allow any violations.
Where to Go From Here?
The sky is the limit for what you can do in the build phases with Swift. You can download resources used by the project from a remote server, you can validate more things in your project directly from Xcode or you can automate configuration changes or even upload the compiled binary yourself. You can literally program your own CI/CD if you want to. :]
To learn more about the command-line tool you were using to compile the Swift files, check Swift’s GitHub docs.
Also, you should refer to Apple’s Reference for all the Environment variables.
We hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below! | https://www.raywenderlich.com/25816315-using-swift-scripts-with-xcode?utm_campaign=Mobile%20Developers%20Cafe%27s%20weekly%20newsletter&utm_medium=email&utm_source=Revue%20newsletter | CC-MAIN-2022-21 | refinedweb | 3,517 | 57.77 |
1
Hi everyone I have a issue where I have written the entire program but couple little tweaks are needed for me to get the program done.
I have my super class here "Pet". I have created couple objects in Main, "myRobin" , "myCow", "myBlackMamba" and passed some arguments to them. Im now trying to send those parameters and have them printed to the output via the toString method I have. Im learning my way around Java ..so Im wondering what am I missing that could make this possible....
Thanks everyone.
public class Pet { //office wants to store info regarding the animal it treats /* * Done */ ///variables /*Diet * Nocturnal * poisionous * ability to fly */ /* * Done */ //Classes /*SuperClass pet * subClass: * robin, cow, black mamaba */ /* * Done */ ///Characteristics /*Num. of Legs * wings or no * feathers , skin or fur * nocturnal */ private int numOfLegs; private String wings; private String skin; private String fur; private String nocturnal; private String diet; private String poison; public Pet(int l , String w , String s, String n, String d, String p) { numOfLegs = l; wings = w; skin = s; nocturnal = n; diet = d; poison = p; } //will allow me to create subclasses public Pet() { } //main start public static void Main(String[] args) { //return what each different class does Robin myRobin = new Robin(2, "Two Wings" , "feathers" , "No I sleep" , "berries" , "I am not poisonous!" ); myRobin.toString(); Cow myCow = new Cow(4,"No Wings", "little fur" , "I sleep, moo!", "I love to eat hay and grass", "Im not poisionous :("); myCow.toString(); BlackMamba myBlackMamba = new BlackMamba(0, "No Wings","skin","awake at night","I love eating rodents","Of course Im poisonous"); myBlackMamba.toString(); Pet p = new Pet(); } //might delete this public void Report() { System.out.println("This is the information for the pet."); } ///Generate getters and setters to access private data fields public String getWings() { return wings; } public void setWings(String wings) { this.wings = wings; } public String getSkin() { return skin; } public void setSkin(String skin) { this.skin = skin; } public String getFur() { return fur; } public void setFur(String fur) { this.fur = fur; } public String getNocturnal() { return nocturnal; } public void setNocturnal(String nocturnal) { this.nocturnal = nocturnal; } public String getDiet() { return diet; } public void setDiet(String diet) { this.diet = diet; } public String getPoison() { return poison; } public void setPoison(String poison) { this.poison = poison; } public void setNumOfLegs(int numOfLegs) { this.numOfLegs = numOfLegs; } public int getNumOfLegs() { return numOfLegs; } ////end getters and setters public String toString() { return("Robin:" + wings ); } ///Test all subclasses. //start with }
and then my other three classes "Robin, Cow, BlackMamba" . Since these three subclasses are pretty much similar except for the names I will post the Robin class here:
package com.Java.CS300; public class Robin extends Pet { ///Determine whether this constructor is needed public Robin(int l , String w , String s, String n, String d, String p) { } //myPet is of type "Pet" public Pet myPet; ///list the characteristics here and return a message which concludes what the animal does //these are the methods supplied to the animal public void Legs(Pet p) { myPet = p; } public Pet doIFly() { return myPet; } public Pet mySkin() { return myPet; } public Pet poison() { return myPet; } public Pet nocturnal() { return myPet; } public Pet diet() { return myPet; } //method for animal to report its characteristics ////might delete this public void infoRobin(int l , String w , String f, String s, String n, String d, String p) { //call from main Robin object } // end of report on Robin } | https://www.daniweb.com/programming/software-development/threads/446528/attempting-to-print-object-to-the-tostring-method-and-send-all-the-argument | CC-MAIN-2018-30 | refinedweb | 556 | 57.91 |
Vrije Universiteit Brussel Faculteit Wetenschappen Departement Informatica en Toegepaste Informatica
- Joella Stevens
- 1 years ago
- Views:
Transcription
1 Vrije Universiteit Brussel Faculteit Wetenschappen Departement Informatica en Toegepaste Informatica The use of Semantic Mappings and Ontologies to enrich Virtual Environments Thesis submitted in partial forfilment of the requirements of the degree of Master in Applied Computer Scienes. By: Barry Nauta Promotor: Prof. Dr. Olga De Troyer Supervisor: Dr. Frederic Kleinermann
2 Patience is a virtue: possess it if you can, seldom found in women, never found in men. A mes trois femmes préférées: Geneviève, Elizan et Rosalie Merci pour toute votre patience!
3 Abstract The web is continuously evolving, web 3.0 is on our doorstep. While the predictions differ, most definitions agree about the next evolution in the web. It will include the semantic web. Where the current web is for human consumption only, the next evolution of the web will allow machine-to-machine communication, enabling better processing of the enormous amount of data that is available. Web 3D is also gaining momentum, with native support (removing the need for plugins) in webpages on the way, leading to virtual worlds, either realistic or game oriented. This thesis looks at the possibilities to combine these two technologies. We describe how we use the semantic web, via the use of ontologies, as base to construct the virtual world, which means that the information on virtual objects which we would like to display come from our ontology. Via a semantic mapping, we link this information to a 3-dimensional representation, in other words: we know what we are displaying. Afterwards we show how we can modify this virtual world, in real-time, with external information. External information is often available in legacy formats, so we use translators. This way we can access the external information in the same way as we access our primary ontology. Finally, we will not only use the ontology to provide us with information on virtual objects to display in the virtual world, we will also use it as a dedicated search engine and let it guide us from starting point to our destination, using a graph and graph search-algorithms to guide us from starting point to our destination, based on the query towards the ontology. i
4 ii ABSTRACT
5 Samenvatting (in Dutch) Het web evolueert constant, web 3.0 staat voor de deur. Alhoewel veel definities verschillen zijn de meeste defitities het erover eens dat het semantische web onderdeel is van de volgende evolutie van het web. Het huidige web is gemaakt voor menselijke consumptie, de volgende evolutie van het web zal machine-naarmachine communicatie mogelijk maken en hiermee ook betere verwerking van de enorme hoeveelheid data dat momenteel beschikbaar is. Web 3D wint ook momentum met in-browser ondersteuning zodat er geen plugins meer nodig zijn. Dit eindwerk bekijkt de mogelijkheden om deze technologiën te combineren. We beschrijven hoe we, door middel van ontologiën, het semantisch web gebruiken als basis om onze virtuele wereld te bouwen. Dit houdt in dat de informatie over de virtuele objecten die we tonen van onze ontologie komt. Gebruik makend van een semantische mapping linken we de betreffende informatie aan zijn 3-dimensionale representatie. Ofwel, we weten wat we aan de gebruiker tonen. Daarna tonen we hoe we deze virtuele wereld in real-time aan kunnen passen met externe informatie. Deze informatie is vaak beschikbaar in een oud formaat, zodat deze eerst vertaald moet worden. Op deze manier kunnen we deze informatie op dezelfde manier gebruiken als onze ontologie. Als laatste gebruiken we de ontologie niet alleen om informatie te verkrijgen over de virtuele objecten die we tonen, we gebruiken dezelfde ontologie om ons de weg te tonen in de virtuele wereld. Gebasseerd op het antwoord van de vraag aan de ontologie maken we gebruik van een zoek-algoritme dat ons van het begin-punt naar het eind-punt leidt. iii
6 iv SAMENVATTING (IN DUTCH)
7 Acknowledgements A while ago, I decided to pick up studies again, to correct opportunities I missed in the past. I have often asked myself the question why, but the choice was made, the path was taken. Combining a full-time job, family and studies have been very challenging, and I could not have done this without the support of my wife, Geneviève and my two daughters, Elizan and Rosalie. The countless hours I spent in books and behind my computer has weighed on them. Finishing my studies could not have been possible without their continuous support and love. I would like to take the opportunity to thank Prof. Dr. Olga De Troyer, for giving me the opportunity to realize this thesis. Furthermore, my gratitude goes to Dr. Frederic Kleinermann who has supported, advised me and proof-read my work several times. It is thanks to his guidance that I have been able to write this document. The end of this path is near, I m coming home. v
8 vi ACKNOWLEDGEMENTS
9 Glossary This chapter contains a glossary of terms and abbreviations that are used throughout this document Agent An Agent is just something that acts. But computer agents are expected to have other attributes that distinguish them from mere programs, such as operating under autonomous control, perceiving their environment, persisting over a prolonged time period, adapting to change and being capable of taking on another s goal. [45] AJAX AJAX stands for Asynchronous Javascript And XML. It is a group of related technologies that enable interactive webapplications. Using AJAX, web-applications can retrieve data from a server in an asynchronous, non-blocking manner, and update only a part of the webpage afterwards. API API stands for Application Programming Interface, an API is an interface implemented by an application, enabling other applications to interact with it. AR AR stands for Augmented Reality and describes the technology to view a realworld environment whose elements are augmented by virtual computer-generated imagery. It is used to enhance a users perception of reality. Avatar An avatar is digital representation, often in the form of a one-dimensional username, a 2-dimensional image or 3-dimensional model. vii
10 viii GLOSSARY Collada Collada stands for COLLAborative Design Activity and establishes an interchange file format for interactive 3-dimensional applications. CSS CSS stands for Cascading StyleSheet and is a stylesheet language primarily used to style web-pages that are written in HTML. CTT CTT stands for Concurrent Task Trees, a notation used for task modeling. It is designed to overcome limitations of other notations that are used to design interactive applications. DTD DTD stands for Data Type Definition, it defines the legal structure of an XML document, by listing its legal elements and attributes. Flash Adobe Flash is a multimedia platform used for adding interactivity, video and animations to web-pages. Adobe Flex, a platform to develop Rich Internet Applications is based on Adobe Flex. Flex Adobe Flex is a Software Development Kit (SDK), release by Adobe Systems for development of Rich Internet Applications (RIAs), based on the Adobe Flash platform. Folksonomy A Folksonomy is a collaborative classification, typically established by letting users add tags to resources. Another term for folksonomies is collaborative tagging. HTML HTML stands for HyperText Markup Language, it describes a markup language, a structured way of creating documents, for web-pages. HTTP HTTP stands for HyperText Transfer Protocol, it is a protocol used to distribute information using the internet. It is typically used for, but not limited to, distributing web-pages, videos, images etc from a server to a client.
11 HUD HUD stands for Head-Up Display HUDs provide a 2d component with data on a semi-transparent canvas so it doesn t obstruct the users view. IRI IRI stands for Internationalized Resource Identifier. IRIs are a complement to URIs, using unicode. Java Java is a name for a number of products, it is the name of an object-oriented programming language, but it is also often used as name for the enterprise platform which is also known under the name JEE (Java Enterprise Edition) Javascript Javascript is a scripting language, often used in webpages (client-side Javascript), providing enhanced user-interfaces and dynamic websites. Javascript is unrelated to Java. JavaFX JavaFX is a Java platform for delivering Rich Internet Applications (RIAs) that are cross-platform. Jena Jena is a Java framework for building semantic web applications. Joseki Joseki is an HTTP engine, that supports SPARQL queries. It is based on Jena. JSON JSON stands for JavaScript Object Notation, it is a standard for data interchange, derived from the Javascript language. Although it is derived from Javascript, it is language independant. Landmark A Landmark is a position, typically in a Virtual Environment, that besides a position, also has an orientation, making them useful for navigation. Mashups A Mashup is basically a webpage or an application that combines information from mulitple sources to create a new service. ix
12 x GLOSSARY Metadata Metadata is data about data, often used to indicate what data it is. O3D O3D stands for Open 3D, it is an opensource standard, created by Google, for interactive 3D applications. Ontology An ontology is a formal representation of knowledge, it is used to reason this knowledge. OWL OWL stands for Web Ontology Language, it is a family of languages used to query ontologies. POC POC stands for Proof of Concept, a short (and often incomplete) realization of a certain method of idea, used to demonstrate the principle. POI POI stands for Point Of Interest, it indicates an interesting location, in 3d worlds, they are often attached to viewpoints. RDF RDF stands for Resource Description Framework. It is a family of W3C specifications, designed as a metadata data-model. RIA RIA stands for Rich Internet Application, the term describes webpages that have characteristics of desktop applications. Adobe Flex (Flash), JavaFX and Microsoft Silverlight are the biggest players in this area. RIF RIF stands for Rule Interchange Format, an XML language for expressing rules which computers can execute SAI SAI stands for Scene Authoring Interface, a Javascript API that allows the user to interact with the embedded x3d scene in a web-page.
13 Semantic Web The semantic web represents an evolution of the web in which the semantics of data are defined, making it possible for machines to properly process it. Silverlight Microsoft Silverlight is a web application framework, enabling the creation of Rich Internet Applications (RIAs),,similar to Adobe Flash and JavaFX. SPARQL SPARQL stands for SPARQL Protocol and RDF Query Language It is an RDF query language. Taxonomy A Taxonomy is a classification of objects/things in a hierarchical way (typically a tree-like structure). URI URI stands for Uniform Resource Identifier (RFC2396), a string of characters used for identifying a resource. A URI can either be a URL (Uniform Resource Locator) or a URN (Unified Resource Name). URL URL stands for Uniform Resource Locator, a URL is, like a URN, a URI (Unified Resource Indicator). In this case, it is a URI that specifies where the resource can be located. It is typically used as locator of a web-address. URN URN stands for Uniform Resource Name, and is, like URL, a URI (Unified Resource Indicator). It does not imply the availability of the identified resource. The functional requirements for URNs are described in RFC VE VE stands for Virtual Environment, a computer simulated environment. The term is closely related to Virtual World (VW) and Virtual Reality (VR). VR VR stands for Virtual Reality, it is a term that applies to computer simulated environments that mimic either real-life or imaginary places. xi
14 xii GLOSSARY VRML VRML stands for Virtual Reality Modeling Language and is a standard file format for representing 3D objects, especially designed for the World Wide Web. It has been superseded by X3D. VW VW stands for Virtual World, it is a computer simulated environment, through which users can interact and create objects, the term has become a synonym for 3D Virtual Environments. Some, but not all VWs allow multiple users. W3C W3C stands for World Wide Web Consortium, it is the principle international standards organization for the World Wide Web (WWW). Web 2.0 Web 2.0 is a term that is often used to indicate web-applications that allow information sharing, user-centric design, collaboration and more. Web 3.0 Web 3.0 represents the future of the web as we currently know it. Many definitions of web 3.0 currently exist, but the most common include the semantic web, some others also include web 3d. WWW WWW stands for World Wide Web, commonly known as the web. It represents a system of interlinked hypertext documents, accessible via the Internet. X3D X3D stands for extensible 3D, an open standards file format and runtime architecture to represent and communicate 3D scenes and objects using XML. It is the successor of VRML. X3D is an ISO standard. XHTML XHTML is XML based language, it is an extension to HTML, used to write webpages.
15 xiii XML XML stands for extensible Markup Language and is a language that describes data/documents in a form of elements and attributes. When comparing to HTML, we could say that XML is the language that describes what the data is, where HTML describes how the data looks. XMLSchema XML Schema, much like DTDs, describe the structure of an XML document. XQuery XQuery is an XML Query language. XQuery can be used to query (finding and extracting) XML files for its data (elements and attributes), it is built on top of XPath expression. XPath XPath stands for XML Path Language and is a language that is used by XSLT to access (or refer to) specific parts in an XML document. 1 XSLT XSLT stands for extensible Stylesheet Language Transformation; an XML based stylesheet that defines the transformation from one XML document to another document (which can be another XML document, but it can also be CSV-based, PDF etc). 1 XPath is also used by XLink ( XML Linking ), which is a specification that allows elements to be inserted into XML documents in order to describe links between resources.
16 xiv GLOSSARY
17 Contents Abstract i Samenvatting (in Dutch) iii Acknowledgements v Glossary vii List of Figures xix List of Tables xxii 1 Introduction Aim of this thesis Structure of this thesis Related work - Setting the Scene Technology The World Wide Web xv
18 xvi CONTENTS Web Web Web The Semantic web Ontology Ontology Reasoning and Ontology Inference Web resources XML RDF, RDFS Directed edge labeled graphs OWL SPARQL Web3d Scene VRML X3D WebGL O3D Collada HTML XHTML HTML
19 CONTENTS xvii 2.2 Scientific and industrial works Overview of the approach Approach Ontology, Virtual World and Semantic Mapping Towards ontology mashups Navigation Resulting overview RDF Data Bus Why use semantic web technologies? Discussion PathManager Semantic mapping extended Navigation by query Constructing the navigation paths Approach implementation - a case study The technical building blocks The ontology Web Ontology Language SPARQL Other university ontologies
20 xviii CONTENTS External information The Virtual World - The campus in 3D extensible 3D Scene Access Interface Google Sketchup Vivaty Studio Semantic mapping External information PathManager The User Interface The result Guided tour - Esplanada Query based navigation Considered approaches Existing similar paraverses Overall limitations Semantic mapping Adding new objects Changing the queries PathManager Conclusion 69
21 CONTENTS xix 7.1 Future work A Model simplification 73 B Source code - Embedding binary X3D 75 C Utilities 77 C.1 Ontology C.2 3D modeling C.3 Application D METAR information 79 D.1 Input D.2 Result Bibliografie 81
22 xx CONTENTS
23 List of Figures 2.1 Tim Berners Lee - The Semantic Web, layered cake A RDF graph containing information on Persons A table containing relational information on Persons OWL 1 Profiles - the onion OWL 2 Profiles Susan Kish - Three separate kinds of Virtual Worlds Microvision Heads-Up Display, HUDs in vehicles A Java 3D Scene Graph is a DAG (Directed Acylclic Graph) X3D Profiles Moving from a loose plugin-based Scene-Access-Interface (SAI) to the tightly integrated X3DOM model O3D Software Stack - plugin and future version Application design - high level overview Tim Berners-Lee - The RDF Data Bus The map represented as graph xxi
24 xxii LIST OF FIGURES 5.1 Application design - high level overview X3D System Architecture The map represented as graph Concurrent Task Tree of the user interface Screenshot of the application in action A.1 Google sketchup - single building, original Sketchup version A.2 Google sketchup - single building, simplified A.3 Google sketchup - single building, simplified, textures applied.. 74
25 List of Tables 2.1 Browser plugin statistics Compression differences between VRML, X3D and X3D compressed
26 2 LIST OF TABLES
27 Chapter 1 Introduction The web is a big resource of information, ranging from text, videos, 2-dimensional images to 3-dimensional virtual worlds. It has come from a static web, where a lot of textual information was available, to a dynamic web. People used to browse the information, now they are contributing and increase the information that is available. With the web becoming more dynamic, people started building social networks for both pleasure and professional activities. When we take into account that the number of users on the web is still increasing, it becomes clear that the amount of information of the web increases rapidly. The increasing information leads to new challenges. How do we sort this information, how do we visualize it? What can we do to help the users finding information, other than keyword matching which is the base for most search-engines at the moment. To answer to these challenges, new techniques and approaches have been developed and researched. In fact, a lot of research is still being done. These techniques and approaches are grouped under the label of semantic web technology, techniques that help to classify and interpret information that is available on the web, so that machines can understand the meaning and reason on this information. Besides this, we are also assisting to the possibility to have Virtual Environments (VEs) over the web, due to new technologies. Virtual Environments are 3-dimensional virtual worlds, containing 3d objects in which users can navigate and interact with objects or other users. The most famous VE is Second Life. Second Life is an exceptional case, since most VEs have never been very success- 1
28 2 CHAPTER 1. INTRODUCTION ful and even Second Life is no longer as successful as it used to be. Some state that the failure of success of VEs is related to the fact that they are visually not as attractive as video games. While this might be partially true, the visual quality has improved a lot, we can now have attractive VEs. VEs are also very expensive to develop and are therefor not accessible to web authors, this might be another reason for the lack of success. The fact remains that the web is broadcasting information continuously, and a lot of this information is about social networks. This implies that VEs must incorporate this information into their environments in order to have a chance to be used over the web. Besides the ability to use this information, VEs must also adapt to what the user does. In other words, some kind of real-time customization should exist. This will facilitate the way users use the VE. A general view should be that VEs should be developed in the spirit of mashups, where users can combine the different types of information and use it to customize VEs and to display information that is relevant to potential users. The aim of this thesis is to explore how semantic web technologies can be used to provide this facility to webbased VEs. This exploration is done by implementing a concrete scenario, based on the campus of the Vrije Universiteit Brussel. 1.1 Aim of this thesis The aim of this thesis is to explore how we can enrich VEs with information so we can have more user specific VEs, with information coming from webresources and how we can help users to find his way through this information in a 3-dimensional environment. This is a challenging task, for several reasons. The first challenge is related to the fact that 3-dimensional information contains information on shapes only. This information tells the computer how to display the information from a geometrical and material point of view. The computer cannot provide any meaning to what it displays and therefor it is up to the user to derive this based on shapes and context. The second challenge is to have a VE having a virtual world that adapts to both the user and the external information, which can be obtained in real-time and typically changes rapidly. We can create a new source of information by combining different sources, the question remains how we can use and visualize this information inside the VE without completely rewriting it. With this increasing amount
29 1.2. STRUCTURE OF THIS THESIS 3 of information, the third challenge is how users can navigate in a convenient way. This thesis will introduce an approach that addresses some of these challenges using semantic web technologies with the aim of having VEs that can adapt quickly to new information to be used. 1.2 Structure of this thesis This thesis is structured as follows: 1. Chapter 1 provides an introduction to the context in which the research work is being conducted. 2. Chapter 2 provides related work where enabling technologies and research results are discussed. 3. Chapter 3 describes an approach to have dynamic Virtual Environments, based on ontologies. 4. Chapter 4 explains a way we use the ontology to improve navigational issues. 5. Chapter 5 provides a case study, based on the campus of the Vrije Universiteit Brussel. 6. Chapter 6 discusses the overall limitations of our approach. 7. Chapter 7 provides a conclusion and provides some ideas for future work.
30 4 CHAPTER 1. INTRODUCTION
31 Chapter 2 Related work - Setting the Scene This chapter provides related work, it is split into two parts. The first part explains existing technologies that are used in this thesis, the second part of this chapter discusses related work, both scientific and industrial, to the contents of this thesis. 2.1 Technology This section highlights some of the technologies that play a role ranging from an Internet point-of-view to more specific web-related technologies and 3d technologies. Besides discussing the current technologies, this section also mentiones previous technologies that have led to the current state of technology. Furthermore, it describes the emerging technologies which are used in this thesis in more detail. 5
32 6 CHAPTER 2. RELATED WORK - SETTING THE SCENE The World Wide Web The Internet, or the world wide web, or the web 1 as we often refer to it, has come a long way. Web 1.0 When the World Wide Web emerged (the first proposal for HyperText was released on November, 12th in 1990 [50]), it contained a lot of hyperlinked, informative pages. These pages were all static in content, there was a lot of information available on the web but understandable only by humans. We now sometimes call this version of the Internet Web 1.0. The rise of Java, and more specifically: Java applets, showed that some interaction with web-pages was possible. Starting with small games, dynamic navigation afterwards and even smaller application within pages later on. These technology changes can be seen as the evolution of the web, creating a broader platform to work with. Slowly, programming languages leveraged the ability to create dynamic pages in a relatively easy way, based on content coming from other sources, like databases, but also coming from user input and more. Dedicated web-frameworks accelerated web-development and at the same time, client-side Javascript, a scripting language often embedded in web-pages which became more and more popular for basic web-page interaction. Internet slowly became a commodity; people started interacting, expressing themselves on the web using forums, taking a web-identity. These were the first indications that something was about to happen. Web 2.0 was on the horizon. The term Web 2.0, was first used by Darcy DuNucci in 1999 [23]: 1 We often see the Internet and The web or The World Wide Web (WWW) as the same thing. It is important to realize that what we call The web refers to only a subset of what we call the Internet. The web refers to web-pages, or from a more technical point of view, namely information in the form of web-pages, shared via the HTTP protocol. The Internet embodies a family of network related protocols like HTTP (principal protocol to send web-pages - displayable information across the Internet), FTP (File Transfer Protocol - principle protocol to send files over the net), SMTP (Simple Mail Transfer Protocol - sending mail) etc.
33 2.1. TECHNOLOGY. The term web 2.0 became popular after Tim O Reilly [39], hosted the Web 2.0 conference for the first time in 2004 Web 2.0 Web 2.0 does not relate to a new version of specifications; instead it can be seen as a combination of several evolutions from a technical point of view. From a business point-of view however, it can be seen as a revolution. The web is no longer about information only, it is now also about collaboration, the web as a platform, rich user experience and more. Tim Berners-Lee calls the term a piece of jargon. He argues that the web was designed to do exactly those things that now are called web 2.0 and that nobody even knows what web 2.0 means [17] Web 2.0 is about collaboration, information sharing, user-centric design, allowing its users to be active; interact with each other as contributors to websites, where before, users could only passively view information on web-pages. Prashant Sharma [48] describes 7 features of web 2.0: User-centered design Customizable pages, fitted to the need of the user. One of the typical examples is igoogle, offering a personalized Google page, where users can add news, weather information, photos and more. Crowd-sourcing Millions of contributions give a website a higher relevance. Typical exam-
34 8 CHAPTER 2. RELATED WORK - SETTING THE SCENE ples include blogging platforms, like Blogger 2 and Wordpress 3 that beat conventional media company by producing extremely frequent and relevant content. Web as platform Web-applications replace more and more desktop functionality. Those webapplications are platform-independent and don t require specific client-side downloads. Google Maps is an excellent example of this aspect. Collaboration One of the most often indicated features of web 2.0 is collaboration. Collaborative information outpaces traditional information sources. A typical example is Wikipedia that provide better and more content than traditional encyclopedia. Power decentralization Web 2.0 follows a self-service model instead of an administrator dependant model. A typical example is Google Adsense where users setup their own advertisement platform without administrator interventions needed. Dynamic content Web 2.0 is also about highly dynamic content. The user-provided information that was listed in crowd-sourcing can be used to lift a site s prestige, it can also help to influence the content. SaaS Cloud application services or Software as a Service deliver software available as webservices without any platform dependencies. As example, we will refer to Google again. Their mail application and on-line office package are excellent examples of software as a service. The following question is easy to foresee: Will there be a next revolution and if so, what will it look like? Web 3.0 Where web 2.0 introduced the first revolution of the web, at least from a business perspective, people are already discussing its successor, web What will And, of course, lots of speculations on web 4.0 already exist.
35 2.1. TECHNOLOGY 9 web 3.0 look like? Regardless of the many definitions that exist, most definitions agree that the semantic web is part of web The Semantic web Tim Berners-Lee mentions [15] that there are two types of information available; Human Readable Information and Machine Readable Information. The Human Readable Information is presented by web-pages, it is the Internet as we currently know it. The Machine Readable Information is data that is explicitly prepared for machine reasoning; part of the semantic web. The semantic web is about linked data on the web, it is about distributed knowledge. It is seen as a future evolution of the web, where the information that is available can be understood by machines and not necessarily humans. The purpose of the semantic web is to enable computers to more easily find information, combining it and act upon it, without the need for human intervention. Figure 2.1 shows the web-standards that enable the semantic web. It shows a picture, also known as the layered cake, were each layer is built on top of the technologies that are referred in the layer underneath. Each layer is general than the layer underneath it. [14] The different building blocks that are shown in this image, often referred to as the semantic web layered cake, require some basic explanations. The technologies that are explicitly used in this thesis will be explained in more detail afterwards: URI/IRI Make sure we use an international characterset (IRI is an abbreviation for Internationalized Resource Identifier ), and provide a way of uniquely identifying resources on the web. In other words: unambiguous names. XML The combination of XML and XML namespaces, as well as XML Schema,
36 10 CHAPTER 2. RELATED WORK - SETTING THE SCENE Figure 2.1: Tim Berners Lee - The Semantic Web, layered cake provide self descriptive documents in a standard way. XML Schema is a layer that restricts the structure of XML documents and additionally extends XML with datatypes. This layer makes sure that we can integrate the definitions with the other XML based standards. This layer is all about syntax. RDF A standard for describing resources on the web, a datamodel for resources and their relationships. RDF is used to describe Metadata, this layer is all about data interchange. RDF Schema (RDFS) A vocabulary for describing properties and classes of RDF resources. With RDF and RDFS it is possible to make statements about objects with URIs and define vocabularies that can be referred to by URIs. This layer is about
37 2.1. TECHNOLOGY 11 taxonomies. 5 SPARQL The language that is used to query ontologies, similar to the way that SQL is used to query relational databases. Ontology: OWL OWL stands for Web Ontology Language 6. This layer supports the evolution of vocabularies, it can define relationships between different concepts. It extends RDF and RDFS, by defining relationships between classes, cardinality etc. Rules: RIF RIF stands for Rule Interchange Format. Rules are basically statements in the form of IF <condition> THEN <conclusion>, RIF provides a family of languages to encapsulate these statements, so computers can execute them. At this moment. the standard is not yet complete. Logic The logic layer enables the writing of rules, currently under active research. Proof The proof layer executes rules, currently under active research. Trust Evaluate whether to trust the given proof. Currently under active research. Crypto Also called the digital signature layer, used for detecting alterations to documents. The layered cake of the semantic web illustrates the fact that standards are built upon other standards, going from syntax through structure, semantics towards proof and trust. Each layer builds upon the previous layer. 5 A taxonomy is a hierarchical way of classifying objects, RDFS allows the notion of hierarchy by introducing inheritance 6 A correct abbreviation of Web Ontology Language would be WOL. Guus Schreiber asks the question: Why not be inconsistent in at least one aspect of a language which is all about consistency It might refer to the Owl of Winie the Pooh, who misspells his name as WOL, or it might be a reference to an Artificial Intelligence project called One World Language [28].
38 12 CHAPTER 2. RELATED WORK - SETTING THE SCENE Ontology The web was originally built to display information in the form of hyperlinked pages. This information is understandable by humans, but although the enormous amount of information is readable by machines, it is not machine-understandable, making it difficult to automate any form of information processing. By adding a layer of additional information that describes the contained data, we can describe the contents that we are actually dealing with. This layer of additional data, also referred to as data about data, is called Metadata. By adding this extra layer of data, we add knowledge to our system. We describe concepts in a certain domain as well as the relationship between those concepts. It is this combination, when properly expressed, that can be understood by machines, it is exactly what entails an ontology. An ontology consists of types, properties and relationship types representing ideas, entities, events along with their properties and relations according to a system of categories. In computer science terms, an ontology refers to an explicit specification of a conceptualization, where a conceptualization is an abstract, simplified view of the world that we wish to represent for some purpose. [26] While it is possible to define any type of ontology, there is a general expectation that ontologies resemble a part of real-life information. [25] So far, it seems that ontologies are a special form of databases, they do not only contain data, but also a description on what exactly is stored. Where databases contain raw data, and have no knowledge on what is stored in its tables, ontologies have this extra layer of data that make the information meaningful. Ontologies are said to be more scalable, since they are built on top of RDF, and RDF is distributed by nature since they use URIs as their foundation, which makes them different from classical databases. The true power of ontologies however, lies in the methods they borrow from Artificial Intelligence, called Reasoning and Inference.
39 2.1. TECHNOLOGY 13 Ontology Reasoning and Ontology Inference Reasoning means that we can draw conclusions by the use of reason. Inference means deriving new facts from existing ones 7. Ontologies contain facts. Facts consists of types, properties and relationship types. Since ontologies are based on facts, we can apply inference to them, although the complexity of inference mechanisms may differ, related to the expressive power of the language that is used [44]. Web resources The URI, or Universal Resource Identifier is one of the most fundamental specifications of Web architecture [15]. The specification basically indicates that anything on the web should be globally and uniquely identifiable, by a string of characters, the URI. The URI is based on the idea by Douglas Englebart [24] called Every Object Addressable, stating that every object should have an unambiguous address, capable of being portrayed in a manner as to be human readable and interpretable. URIs are used to uniquely identify names or resources on the web, using either URNs, Universal Resource Names or URLs, Universal Resource Locators. URNs uses names to uniquely identify resources, a good example is using ISBN to indentify a specific book, URLs uses locations to uniquely identify resources, we can think of a street address, but of course, URLs are typically used to address web-resources. Boht URLs and URNs are specialized cases of a URI, but sometimes it is difficult to categorize a specific schema as either a URL or a URN, since we can use all URIs as names, a URN is a URI that identifies a resource by its name, or we can use URNs to talk about resources by their names, without specifying their location. IRIs, Internationalized Resource Identifiers are a generalization of URIs, since URIs are based on ASCII, a limited characterset allowing only the English alpha- 7 A famous example is the following: Socrates is a man, All men are mortal from which we can derive Socrates is mortal. This form of reasoning is called deductive reasoning
40 14 CHAPTER 2. RELATED WORK - SETTING THE SCENE bet, IRIs are based on the Universal Character Set, Unicode, allowing many more characters, including Arabic, Chinese etc. XML XML, or extensible Markup Language is a markup language that is used for encoding documents, in a structured way. It is most often used to present text and data in a way that is can easily be processed, without the need of human or machine intelligence. A key-point in XML is that it separates form and content. HTML, the language behind webpages, for instance, consists mostly of tags defining the layout of text, in XML tags define the structure and the content of data. A second important point is that XML is extensible, meaning that it is not a fixed format, like HTML for example is. DTDs or Document Type Definitions is a set of markup declarations. They define exactly which kind of element may appear where in a document and what the elements content and attributes are. DTDs are superseded by XML Schema, which also is used to put constraints on XML documents, using a set of rules, with a big difference that XML Schema is written using XML, DTDs are not. RDF, RDFS RDF stands for Resource Description Framework and is a W3C (World Wide Web Consortium) approved specification. It is part of the semantic web layered cake shown in Figure 2.1 RDF is a datamodel used to make statements about resources in the form of socalled triples, a combination of a subject which identifies what object the triple is describing, a predicate, also known as property, which defines the data we are going to give a value to, and an object, the actual value we will give. It is a decomposition of knowledge into smaller pieces. In fact, the goal of RDF is to be as simple as possible, so we can express any fact. On the other hand, it must be very structured, so it is easy for computers to process. The example below contains an informal triple, where the subject is a person, the predicate points to this persons first name and the object, the actual value, is a
41 2.1. TECHNOLOGY 15 literal; it contains the text Geneviève. Person, has firstname, Geneviève Note that each RDF statement should be complete and unique, therefore the subject must use a unique 8 URI. 9, we call this a named resource. Since URIs can become long and unreadable, we often abbreviate them using the concepts of XML namespaces. 10 RDF itself is an abstract datamodel, it comes in two formats, called serializations ; XML (extensible Markup Language) and N3 (Notation 3) for a non-xml representation. The informal example above could be written in RDF/XML format as follows: <?xml version="1.0"?> <rdf:rdf xmlns: <rdf:description rdf: <example:has_firstname>genevieve</example:has_firstname>... </rdf:description>... </rdf:rdf> In a few words; RDF is used to model information that is implemented in web resources. It is a datamodel, making the semantic web that uses RDF, a decentralized platform for distributed knowledge. This in contrast to the current web which is a decentralized platform for distributed information visualization. RDF Schema, or RDFS for short, adds additional semantics to RDF. These semantics are a type system of classes, including inheritance and properties 8 The subject can also be a anonymous node or blank node (also known as bnode) 9 This is a HTTP URI. HTTP stands for HyperText Transfer Protocol, one of the protocols that is used to transfer data over the Internet. Resources that can be accessed via the HTTP protocol are identified by a set of characters, also known as a Universal Resource Identifier (URI). URLs (Universal Resource Locators), often called a web-addresses, are a subset of URIs 10 Namespaces have no significance in RDF, they are a tool to abbreviate long URIs.
42 16 CHAPTER 2. RELATED WORK - SETTING THE SCENE Class (type of resource), property Subclasses and subproperties Domain and range Comments and labels Directed edge labeled graphs The triples of RDF actually construct graphs 11. Figure 2.2 shows a partial RDF graph of a family. Figure 2.2: A RDF graph containing information on Persons In general, the nodes in RDF graphs are things, arcs are relationship between things. 11 A graph refers to a collections of nodes, or vertices, that may be connected. The connections between nodes are called edges. Edges may be directed, from one vertex to another, or undirected. We can also give a weight to edges, for instance the distance or a payload for travelling over the edge. Search-algorithms for the different type of graphs are different.
43 2.1. TECHNOLOGY 17 The notion of graphs is used, because in graph isomorphism theory [20], a lot of research has been done to the problem whether two (sub-)graphs are the same and how they can be merged. The research often deals with unlabeled, undirected graphs. In RDF graphs, this problem becomes relatively easy, since most vertices are labeled with the URI of the resource and most edges have distinct labels from the URI of the property of the triple. RDF compared to a relational database If RDF is actually nothing more than a simple datamodel, why not use a relational database? If RDF is about information on web-resources, aren t we building a web-database? When we look at relational databases, we see that they contain tables. Each table consists of rows (the things we are storing information about) and columns with represent the attributes/properties of those things. The combination of a row and a column gives us the value of a specific attribute of a thing stored in the database. If we look at database containing person information, we can imagine the situation as described in Image 2.3. Figure 2.3: A table containing relational information on Persons
44 18 CHAPTER 2. RELATED WORK - SETTING THE SCENE The rows in the first table represent a Person, the columns represent the attributes we know, and are interested in, of this Person. In the case of the image, the highlighted person has an attribute Firstname with value Geneviève. We can easily see that it is not hard to translate this information into an RDF graph. In fact, Figure 2.3 maps to Image 2.2. The nodes in RDF graphs are things, arcs are relationship between things. Foreign keys simply become a relationship to another entity. This is demonstrated by looking at the second table. The power of using RDF graphs is that the things are identified by URIs, making them web-enabled and additionally, we can uniquely identify them. Nodes with the same URL are considered identical and this can be used to merge graphs. Merging of RDF graphs has no limitations, any RDF graph can be merged with any other RDF graph. Formally, it is said that RDF is monotonic, merging graphs means merging triples of identical nodes. Adding triples never changes the meaning of a graph, which basically means that you cannot invalidate earlier conclusions nor can you unsay statements by adding triples. To answer the question if we are building a web-database, the reply is more-orless. RDF uses URIs as unique identifiers, we use graphs so we can easily merge information. The information is available on the web, which means that it is not centralized. Therefore we can easily modify information and we can modify in parallel, which means that this is a very scalable solution. We could build a webdatabase. The problem lies in the fact that representing information in RDF is often considered a major overhead [18], therefore it is not often applied, so little information is available since people chose not to make their information available via RDF. OWL Web Ontology Language (also known as OWL ) is a language that is built on top of RDF and RDFS. It includes a standard vocabulary for describing properties and classes, like datatypes, relations, cardinality, characteristics of properties etc. There are currently two versions of OWL; OWL 1 released in 2004 [9] and OWL 2 which was released at the end of the year 2009 [8], the latter being backwards compatible, but is still a working draft.
45 2.1. TECHNOLOGY 19 OWL 1 OWL comes in three different sublanguages: OWL Lite OWL Lite supports basic classification hierarchies and constraints. OWL DL OWL DL extends OWL Lite, DL stands for description Logic, OWL DL supports all language constructs, but there are some limitations on transitive properties. OWL Full OWL Full extends OWL Lite and OWL DL Each variant has an increased expressiveness, starting by OWL Lite, through OWL DL and finishing by OWL Full. The language become more expressive, by syntactic extensions of its predecessor. This means that each legal OWL Lite ontology is a legal OWL DL ontology, and each legal OWL DL ontology is a legal OWL Full ontology. [9] The different profiles of OWL 1 are listed in Figure 2.4 Figure 2.4: OWL 1 Profiles - the onion OWL 2 OWL 2 is a revision and an extension of the first version of OWL. The following major features are added to OWL 2: Improved syntax, making relations easier to express More forms of expressiveness
46 20 CHAPTER 2. RELATED WORK - SETTING THE SCENE More datatypes and ranges Metamodeling Annotations OWL 2 supports, just like OWL 1, several profiles. There are three profiles in the new specification: OWL 2 EL OWL 2 EL is targeted to applications employing large ontologies that use a simple format. It keeps expressiveness power and consistency, while providing polynomial reasoning time. OWL 2 QL OWL 2 QL is based on OWL DL (and therefore also OWL Lite) and provides an intersection of RDFS and OWL 2.0 DL. It is targeted to data querying and storage. OWL QL also provides ways to express conceptual models. OWL 2 RL OWL 2 RL uses a syntactic subset of OWL 2 and part of its RDF based axiom semantics. This profile is targeted for applications that favor scalability and performance over expressive power. The different profiles of OWL 2 are listed in Figure 2.5 SPARQL SPARQL stands for SPARQL Protocol and RDF Query Language and is an RDF query language. Like said before, RDF can be seen as the web-database, provided that all information evolves to known ontologies. SPARQL can be seen as the web s query language. Every identifier in SPARQL is a URI, which is a global unique identifier. Using SPARQL, we can query in an unambiguous way, unlike in databases where we typically use a combination of firstname and surname to indicate a person, which is clearly not a unique combination. To avoid this, IDs are often applied as key for the record, making the ID in combination with its table unique in the database only.
47 2.1. TECHNOLOGY 21 Figure 2.5: OWL 2 Profiles When using the same example as earlier; we could imagine the following code query for a persons firstname. PREFIX nauta: <> PREFIX example: <> SELECT?firstName WHERE { nauta:gc example:has_firstname?firstname } Web3d We have discussed the future of the web, which is often called web 3.0. We have stated that most definitions of web 3.0 include the semantic web, but some definitions also include web3d in their definition. Web3d refers to interactive 3d content in web-pages. At this moment, they typically require plugins to display the content, although work is on the way to replace 3d content by Javascript, which is currently the case for O3D, or embed it natively in the web-page. In fact, this is one of the main goals of HTML5, removing the need for plugins. Although web3d refers to any type of 3d content, we will limit this in this paper
48 22 CHAPTER 2. RELATED WORK - SETTING THE SCENE to virtual worlds; 3d worlds that resemble our world, displayable in a browser. Virtual Worlds are not limited to a world as we currently imagine it. We can extend the notion of world to any sort of containing environment, grouping related objects, but we will use the notion of a paraverse throughout this chapter. A Paraverse is a virtual representation of the world, or a part of it, as we know it. In other words, in this document, we will use the term Virtual World and paraverse for the same thing; to describe a simulated environment that resembles a realworld environment. Susan Kish [33] identifies three major emerging types of universes: Massive Multiplayer Online Role Playing Games (MMORPGs) Massive Multi-learner Online Learning Environments (MMOLEs). Virtual environments that are focused on learning platforms, virtual training world, elearning etc. Metaverses are typically virtual worlds that are both social and game oriented. Second Life, a Virtual World allowing users to explore the world, interact, participate in activities and socialize, is the classic example of a Metaverse. Additionally, she mentions two types that are related to the aforementioned: Intraverses, a Virtual World on a corporate Intranet. Paraverse, a Virtual World that tries to resemble a (part of) real-life environment. Paraverses are also called mirror worlds. Google Earth is the classical example in this case. Virtual Worlds (VWs), from a more technical perspective, are computer based environments, typically containing users and virtual objects. Some VWs allow users to interact with other users, some VWs allow users to manipulate objects, some VWs allow a combination of those. Virtual Worlds are not only something we see, we can also participate in it and often people do that in form of Avatars, a digital representation of their presence.
49 2.1. TECHNOLOGY 23 Figure 2.6: Susan Kish - Three separate kinds of Virtual Worlds Avatars It signifies the incarnation or reap- The word Avatar comes from Sanscrite. pearance of a god in the living world. When people are visiting a Virtual World, they are often represented by an avatar, digital representation, often in the form of a one-dimensional username, a 2- dimensional image or 3-dimensional model. Head-Up Displays When using a Virtual World, there is a lot of information available. Often, it is not desirable to display all information in 3d form and for this, Head-Up Displays are often used. Head-Up Displays are used to provide additional means of showing information. HUDs provide a 2d component with data on a semi-transparent canvas so it doesn t obstruct the users view. Initially developed for military purposes, HUDs
50 24 CHAPTER 2. RELATED WORK - SETTING THE SCENE are now also available in commercial aircrafts, cars etc. Figure 2.7: Microvision Heads-Up Display, HUDs in vehicles HUDs are also often available in Virtual Worlds, providing additional information, without cluttering the 3d structures. Scene Anything you would like to represent in 3D is a scene. A scene contains the structure (wireframes, mesh), textures, cameras (viewpoints in the virtual world) etc. that are needed to display the 3d content. Most of the 3d engines share a data structure known as a scene graph, containing all scene information. A scene graph is a hierarchical (tree) structure in which a specific node can have many children, but a child can only have one parent. 12 Nodes in a scene graph are typically one of the following: Group nodes Group nodes are nodes that can contain children. These nodes are typically not visual. Effects that are applied to group nodes are also applied to all its children. Leaf nodes Leaf nodes are nodes that can actually be seen (or for audio; heard) 12 Some scene graphs are implemented as directed acyclic graphs in which children can have multiple parents.
51 2.1. TECHNOLOGY 25 Figure 2.8: A Java 3D Scene Graph is a DAG (Directed Acylclic Graph) VRML VRML stands for Virtual Reality Modeling Language and is a standard file format that is used for describing 3D interactive graphics. VRML is a textbased format that describes edges, polygons, textures, transparency parameters, etc [10]. It also specifies the ability to add sound, animations and more. Special nodes like the Timer node can be used to interact with the scene, likewise, script nodes allows a piece of program code, typically ECMAScript, to be added to the VRML file, which can be executed when certain events are triggered. These events can be timer events, but can also come from user-interaction. VRML was designed to be used in web-pages, it has been superseded by X3D.
52 26 CHAPTER 2. RELATED WORK - SETTING THE SCENE X3D X3D is an acronym of extensible 3D and is an ISO standard specifying the file format for 3D content. It is the successor of VRML, adding extensions to VRML as well as the ability to encode scenes using XML syntax. X3D defines several profiles, each adding some more capabilities to the less rich profiles: 1. X3D Interchange Providing basic features like grouping of objects. 2. X3D Interactive Extending X3D Interchange and adding features that enable interactivity like touchsensors, inline nodes etc. 3. X3D Immersive Adds scripts, audio and more. 4. X3D Full Adds Geospatial, NURBS (Non-uniform rational basis spline, a mathematical model for generating curves and surfaces), H-ANIM (Humanoid Animation) Figure 2.9: X3D Profiles The traditional way of viewing X3D in a browser is by installing a x3d plugin, like Vivaty 13, Octaga or BS Contact. Most of these plugins use a standard called SAI 13 On the 31st of March 2010, Vivaty announced that it was shutting down, their products are currently no longer available.
53 2.1. TECHNOLOGY 27 which is a Javascript API used to communicate with the plugin. It allows external parties to call predefined functions on the X3D plugin. BS Contact does not offer the SAI, but has a proprietary solution instead. X3DOM X3DOM is an open source framework and runtime to integrate X3D natively (meaning; without the need for plugins) in HTML5 by trying to fulfill the HTML 5 declaration for declarative 3d content. 14 The idea is to include X3D elements in the HTML 5 DOM 15 tree, which would enable us to manipulate the 3d scene by modifying DOM elements, without the need for plugins (which are controlled via the SAI). The idea is illustrated in Figure 2.10 [1]. Figure 2.10: Moving from a loose plugin-based Scene-Access-Interface (SAI) to the tightly integrated X3DOM model. WebGL WebGL is a standard (a low-level API) to provide 3d content in webbrowsers, without the need for a plugin. WebGL runs in the HTML5 canvas, which means that it has full access to the DOM (Document Object Model) interfaces. The fact that WebGL it is based on OpenGL has the advantage that OpenGL is cross-platform 16 and cross-browser. All major browser vendors already implement it in their current beta versions of the browser. The disadvantage on the 14 The draft on HTML 5 at the following location: no.html#declarative-3d-scenes specifies the following: 13.2 Declarative 3D scenes Embedding 3D imagery into XHTML documents is the domain of X3D, or technologies based on X3D that are namespace-aware. 15 DOM is an abbreviation for Document Object Model, it is a hierarchical structure for representing and interacting with objects in a HTML page. Interaction with objects in the DOM is typically done via client-side Javascript. 16 cross-platform should not be confused with platform independent. WebGL is cross-platform,
54 28 CHAPTER 2. RELATED WORK - SETTING THE SCENE other hand is that it is tightly coupled to hardware-accelerated graphics which makes portability to other infrastructural platforms (like mobile devices) difficult or sometimes even impossible. O3D O3D is being developed by Google, and is one of the more popular 3DWeb formats. It is an open source Javascript API for creating interactive 3D applications. It started out as a browser plugin, but has been replaced by a javascript library using WebGL. The differences between the two versions are shown in Figure 2.11 Figure 2.11: O3D Software Stack - plugin and future version The previous version shows the O3D core software, the plugin that needed to be downloaded and installed in your browser, the new version shows that there is no longer a need for a dedicated plugin, the rendering will be handled by a Javascript API. indicating that it runs on a variety of platforms, but not necessarily all. X3D, as example, is platform independent which means that it should be possible to implement render engines on any platform.
55 2.1. TECHNOLOGY 29 The reason why Google intialially built a plugin was that they did not expect that Javascript could meet the performance expectations. Recent development in Javascript engines shows that Javascript becomes more and more performant. 17 Collada Collada is an abbreviation for COLLAborative Design Activity and is the intermediate file format for 3d applications. Most 3D render applications (like Blender, 3dStudio), but also tools like Adobe Illustrator, Google Sketchup have facilities to export to this format. Digital Assets in collada files are described in XML format, the files have the extension.dae which is an abbreviation for Digital Asset Exchange, emphasizing the fact that collada provides an intermediate format HTML HyperText Markup Language, also known as HTML is the markup language that is used on the Internet. The language defines ways to structure documents, by using tags to indicate page elements. Browsers are applications that interpret this text and display it according to a well-defined standard. HTML defines a way of describing layout of information, by using well-defined elements suchs as headings, lists, paragraphs and other items. In short; HTML describes the layout of webpages. The current version of HTML is HTML 4.01 CSS, or Cascading StyleSheets is a standard that defines the appearance of the HTML elements in web-pages. 17 Not all JavaScript engines are created equal. Google Chrome has V8, Firefox is working on TraceMonkey, and Apple has SquirrelFish. Conspicuously absent is Microsoft, which has opted to invest more broadly in realistic scenarios when developing Internet Explorerwith the result that one of the most popular browsers has, by most accounts, one of the slowest JavaScript engines. The good news is that O3D includes Google s V8 JavaScript engine, which ensures consistent performance across all browsers. [21] 18 Google Earth standard export format is actually a.kmz file, which is a zip archive containing.dae files
56 30 CHAPTER 2. RELATED WORK - SETTING THE SCENE The current version of CSS is CSS Level 2. XHTML XHTML is a XML based version that extends versions of HTML. Up to HTML 4, HTML was defined as an application of Standard Generalized Markup Language (SGML), a very flexible markup language framework, XHTML is defined as an application of XML. The difference between XHTML and HTML is that XHTML must be a wellformed XML document. The current version of XHTML is XHTML version 1.1 HTML 5 HTML 5 is the proposed successor of HTML and has reached Draft status in March 2010 (which is 8 months behind schedule). The specification should become a W3C standard by the end of the year One of the main goals of HTML 5 is to remove the need for plugins, like Adobe Flash, Microsoft Silverlight or Java FX. Most of those platforms require some sort of Virtual Machine (available as plugin) to run. The power of the use of these frameworks is related to the percentage of install base of the plugins (Javabased frameworks are an exception to this, since Javascript is provided natively is most of the browsers). StatOwl 20 provides the following plugin market share, average percentage in the year The browser penetration of Flash and Java is relatively stable, the penetration of Silverlight is strongly increasing, starting at 21.31% in January 2009, ending at 37.38% in November Work is on the way to provide a native (i.e. no plugins) integration of X3D in 19 Actually, HTML 5 is the proposed successor for the combination of HTML 4.01, XHTML 1.0 and DOM Level 2 HTML 20 overview.php
57 2.2. SCIENTIFIC AND INDUSTRIAL WORKS 31 Plugin Avg 2009 Jan 2009 Nov 2009 Flash 96.52% 97.40% 96.71% Java 80.74% 81.51% 81.68% Silverlight 29.58% 21.31% 37.38% Table 2.1: Browser plugin statistics HTML. [2] [12] 2.2 Scientific and industrial works This section describes related work, either scientific or from an industrial point of view. SecondLife [3] is probably the most famous Virtual World that exists. It allows users, via avatars, to interact, socialize, participate in activities and more. Second Life also offers trade options and virtual property. ExitReality 21 creates an instant virtual place from every web page that is available on the internet. ExitReality is based on the internet itself and not a closed environment like Second Life. Once the plugin is installed, the application allows you to interact and socialize with other users through their avatars and chat boxes. The application turns webpages into virtual rooms, adapting the room to the users interest. This is done for social network sites like Facebook or MySpace but they aim to transform every webpage into a 3-dimensional website. Navigation in these virtual rooms is not easy. In Detroyer et al. [51], they have developed an approach to make VE adaptable to learners. It is based on the concept of virtual reality adaptation state where the virtual world adapts according to the learner. However, it does not used any kind of way to search and navigate easily in the 3-dimensional space. It is primary done in the context of adaptable E-learning applications. H. Mansouri [35] used an ontology, in combination with the VR-WISE approach, to create a search engine. Their work is based on the assumption that, while the virtual world is constructed, semantic data can be added via annotations. This se- 21
58 32 CHAPTER 2. RELATED WORK - SETTING THE SCENE mantic data can afterwards be used for a search engine and navigation in the VW. This approach is limited to static VWs meaning that the VW cannot be adapted. Van Ballegooij & Eliens [52] state that in a web-based 3d virtual environment, users often encounter the problems of being lost-in-cyberspace. Besides the notion of disorientation, users have the problem that it is hard to discover all that a VW has to offer, without spending a lot of time exploring it. They propose navigation by query to overcome these burdens. Navigation by query augments the possibility for users to navigate by allowing the user to query for content. Peng et al. [42] discuss improvements in VR performance in 3D building navigation. They tackle performance problems of large scale VWs by dynamically loading models based on cell segmentation. They investigate route optimizations based on path planning to ease navigation. K.H. Sharkawi et al. [47] discuss the combination of Geographical Information Systems (GIS) with 3d game engines. They explore virtual navigation, using real spatial information (colors and shapes), landmarks and other features in 3D geoinformation, leading to a significantly enhanced navigation system, compared to 2d maps that are typically used in GISs. M. Haringer and S. Beckhaus [27] explore extensions to Virtual Reality systems to manipulate objects of a scene, primarily by applying effects at runtime. They implemented a system which provides a user-interface allowing moderators, authors, or automated systems to modify the scene online using the available effects. J. Ibáñez [29] provides a querying model that allows users to find objects and scenes in virtual environments based on their size as well as their associated metainformation. This model is based on fuzzy logic and is even able to solve queries expressing vagueness. They did not look at the possibilities of applying queries in a VW that changes. Denise Peters and Kai-Florian Richter [43] discuss the problems people have when trying to orient in large-scale environments. They propose to apply concepts and methods of schematization to focus on the relevant information in representing virtual cities. They do so by investigating processes which play a role in forming mental representations of city environments and use a cognitive agent for evaluating different schematization principles applied to a virtual city by simulating wayfinding tasks. Xiaolong Zhang [56] takes a look at navigation in a virtual world using a multi-
59 2.2. SCIENTIFIC AND INDUSTRIAL WORKS 33 scale progressive model. He examines the use of scaling in virtual environment to improve the integration of spatial knowledge and spatial action. Jia et al. [31] implement a dedicated search algorithm that can be used for navigation in large scale 3-dimensional environments. They use a browser based approach, implementing the algorithm in Javascript, so it can be embedded in the scene itself. The search algorithm is executed in the clients browser. Yuhana et al. [55] use inference on buildings to determine relative locations of buildings with regards to others. By using distance-ranges, they determine connectivity, build a graph and use a search-algorithm afterwards to calculate shortest paths. This is a very interesting approach, but it is not useful for natural navigation, since the paths are considered as straight lines, while in real-life this is most often not the case. F. Kleinermann et al. [34] explore navigational issues in Virtual Environments by using semantic information. They discuss the possibility of annotating Virtual Objects, allowing the creation of navigation paths and virtual tour guides. Their annotations are not limited to text but can are multimedia objects. This approach is not useable for our case, since we would like to use external data, that is typically subject to change and additionally, we might want to change appearance based on the external information. Issues that are difficult to annotate.
60 34 CHAPTER 2. RELATED WORK - SETTING THE SCENE
61 Chapter 3 Overview of the approach We have explained in the introduction that the aim of this thesis is to address three challenges. The first challenge is to add meaning to the Virtual Environment, more precisely its Virtual World (VW). We want to relate the internal structure of the VW, the virtual 3-dimensional objects, to human-understandable information. The second challenge is to be able to adapt the VW with new information. We would like to be able to display this information, but we would also like to be able to use it, reason on it and use the result to adapt the VW. The third challenge is to improve navigation inside the VW. This chapter will explain step by step how we have designed an approach that addresses these challenges. We will first introduce the approach and then discuss it. 3.1 Approach As explained in the introduction, we aim at using semantic web technologies to tackle these three challenges. We will first explain how we can add some humanunderstandable meaning to a virtual world by the use of ontologies. This will be the first building block of our approach. From there, we will explain how the approach can be extended to allow, on one hand, to visualize new types of information coming from the web inside the virtual world, and on the other hand how we 35
62 36 CHAPTER 3. OVERVIEW OF THE APPROACH can reason on such information to adapt the virtual world consequently. Finally we will introduce how our approach can be extended to facilitate the navigation inside adaptable virtual worlds Ontology, Virtual World and Semantic Mapping As explained in the previous chapter; Virtual Worlds display (composite) structures, apply effects and more, making the scene look like a part of the world we know. The scene graph tells the 3d engine how to display information, but the world has no idea what it is actually displaying. There are several formats that can be used for 3-dimensional information and although it might be possible to store other information in those files as well, it is not a generic nor elegant way. We need to store this information elsewhere. Having different types of information at different locations implies that we need to have some sort of mapping between the information and its 3-dimensional representation We will start by using the ontology as a way to relate information from the ontology to the virtual world Towards ontology mashups The approach should allow an author to use the information coming from external information, like webservices or RSS feeds, to be visualized inside the virtual world. Since RDF is XML based, we should be able to easily combine multiple sources, using stylesheets. This goes towards the concept of mashups that are used nowadays in web 2.0. Instead of having different information sources, we can combine them and use them as one new information source. Although this seems to be obvious, since RDF is an XML based language, numerous sources mention [54] [11] [7] that it is actually very difficult and frustrating to combine RDF and XSLT. 1 1 We could use XHTML in combination with XSLT to convert web-pages into RDF, but we cannot use XLST in combination with RDF/XML with complete certainty, since RDF is nondeterministic.
63 3.1. APPROACH 37 If we are able to push changes in the external information towards the Virtual World, in a near real-time manner, the virtual world can then be seen as a template where dynamic information can be visualized. Similar techniques already exist in ExitReality and SecondLife where information on 3-dimensional panels changes. Changing display information is one thing, but we want to go one step further by adapting the virtual world. As example, instead of changing the information on panels in a 3-dimensional world, like the sun and clouds that are often seen in weatherforecasts, we could think of adapting the world by changing the sky, adding fog etc. Another example would be where we have a virtual lecture theatre that changes color, based on the number of students that are following a specific course. There are many datasources available, and lots of different dataformats like Yahoo Weather vs. METAR for weather information, Yahoo Stock vs. MetaStock for stock information, etc. Regardless of the format of information, it needs to be translated into a format that we can understand, and the logical choice for the resulting format is RDF. This implies that for each resource, we potentially need a dedicated translator. These are typically programmed, thus adding new resources means that code needs to be adapted. (unless translators can be reused, of course) and this also applies to changed dataformats. These translators are small stand-alone programs, that take external information, and translate it to RDF. So, we have one or more external information sources. They need to be translated, so we need to write a dedicated application for this. This information needs to be added to the Virtual World, so we need to adapt the VW to handle this new information, if no means exist yet. In between, we need to map the information with the virtual world, which we call semantic mapping. Gregory Sherman [49] researched the use of XSLT and large XML databases and concludes that, since XSLT has a tendency towards quadratic complexity, it should only be used on small- to medium-sized XML database.
64 38 CHAPTER 3. OVERVIEW OF THE APPROACH Navigation The third aim of the thesis is to facilitate navigation inside an adaptable virtual environment. Before explaining our approach of navigation, we will introduce some terms and background information on navigation in 3d worlds. Navigational awareness is defined as having complete navigational knowledge of an environment. [46] Glenna A. Satalich defines two distinct types of navigational knowledge: Procedural knowledge, or route knowledge. This type of navigational knowledge is ego-referenced and is gained by exploring the area. This type of knowledge is characterized by the fact that the user can go from one point to another, but has no knowledge of alternate routes. Survey knowledge is world referenced, typically attained by multiple explorations of the environment. This is similar to having a mental representation of a physical map, also called a cognitive map. The characteristics of this type of knowledge is that distances and landmarks are known and routes can be inferred, even if they have not been travelled before. Applying navigational knowledge to Virtual Worlds gives us the definition of wayfinding. Wayfinding is a dynamic process of using our spatial ability and navigational awareness of an environment to navigate in a Virtual World. The problem with wayfinding in Virtual Worlds is that, from a human perspective, it is very difficult. [22] [53] [43]. It is very easy to lose orientation, to get lost-incyberspace [52] [19] [32]. One of the ways to overcome this feeling is to use a 2-dimensional map next to the 3-dimensional world. This map would typically be placed in a Head-Up Display, the users location is indicated on both maps. This is an improvement, although this often leads to another issue called the alignment problem [36] 2. Another approach can be that we do not let the user navigate, but we have let the system guide us. This approach is based on Navigation by query [52]. 2 A map is called aligned when the upward direction of the map corresponds to the current direction of gaze in real space.
65 3.1. APPROACH 39 Our approach allows two types of navigation. The first type of navigation is done by querying and jumping to a place inside the virtual world. The query is based on SPARQL, we can build rich queries so we can use the full power of ontologies to get a result, The other way of navigation is by following a tourguide where a path manager can build a path according to the query. The next chapter will explain this in more details Resulting overview Putting these three challenges together, we get the following overview: Figure 3.1: Application design - high level overview Figure 5.1 shows a big ontology icon, with the text main ontology written next to it. This is our ontology, the main-ontology containing the principal information
66 40 CHAPTER 3. OVERVIEW OF THE APPROACH we want to display. The image also shows external information, with a small execution icon and an ontology icon next to it. With this, we would like to indicate that, usually due to legacy reasons, there are many different information types available on the Web 3, there is no single way of providing information. to be able to use this information, we must translate it to a common form we know, we use a small application that transforms/translates the information to RDF. The image also shows that we potentially need a translator for each different type of information resource we would like to use. Even a bit stronger, we can say that is unlikely that we do not need a dedicated translator for each type of information. When questioning what common format we should translate to, the answer is obvious. We, as humans, know what information we are retrieving, we know what it means, so we can translate this into RDF. We supply the data, with an additional layer of data on top of it, the meta-data telling us what information we are actually processing. RDF Data Bus Tim Berners-Lee mentions the The RDF Data Bus [16] [13], making legacy information available in RDF format, providing one uniform way of accessing it. 3.2 Why use semantic web technologies? When displaying information, it seems logical to think in terms of relational databases. They have been forming the backend of many applications for many years. We have chosen a different approach however, we base our approach on ontologies. Ontologies are meant to facilitate either human-to-human or machine-to-machine communication, but there are many advantages, that can basically be grouped in 3 A good example of representation differences is how weather information is provided. Dating from 1968, METAR is a raw format, publicly available, which is mainly used by pilots to retrieve weather information around airports. Yahoo weather provides weather information in the form of webservices. The two types of information are clearly incompatible.
67 3.2. WHY USE SEMANTIC WEB TECHNOLOGIES? 41 Figure 3.2: Tim Berners-Lee - The RDF Data Bus three areas [30] of which the most important ones are [41]: Communication between people. An unambiguous but informal ontology is sufficient Interoperability among computer systems. The machine-to-machine communication, the ontology is used as an interchange format. System engineering, in particular: Reusability, ontologies can be used and reused as a kind of component between software systems. Search, using inference we can use the metadata of the ontology Reliability, since ontologies are formal by nature, we can check for consistencies, up to some degree, leading to more reliable systems. Specification, ontologies are expressed using the terminology of the domain and thus facilitate the process of identifying requirements.
68 42 CHAPTER 3. OVERVIEW OF THE APPROACH 3.3 Discussion Recently, Tim O Reilly reflected on what the web was and where it is going now. He states the following [40] Web 3.0. Is it the semantic web? The sentient web? Is it the social web? The mobile web? Is it some form of virtual reality? It is all of those, and more. He argues that the Web has become the world and that everyone participating in this world casts a digital shadow containing a wealth of information, which he gave the name Collective Intelligence. This thesis discusses a combination of emerging web technologies; the semantic web combined with a 3-dimensional representation. We will create a Virtual World based on information coming from an ontology. We add meaning to the virtual objects we display in the VW. We will adapt the VW with external information, we show that our VW is able to deal with changing external information, and finally we will use the ontology to overcome navigational problems, we let the ontology guide us to our destination.
69 Chapter 4 PathManager Like discussed previously, it is difficult to navigate in 3d worlds. A lot of research has been put into improving navigation, avoiding getting lost in cyberspace. Using 2d maps in combination with 3d maps, typically via the use of Heads- Up-Displays (HUDs), are also often applied, although this leads to misalignment problems. 4.1 Semantic mapping extended We already use the ontology to query for the virtual objects that build up our initial Virtual World, this has been shown in the previous chapter and we use semantic mappings to relate the virtual object to their visual representation. We now extend this mapping by applying point-of-interest (POIs) to each virtual object. For each Virtual Object, we had already retrieved its 3-dimensional representation, we use the same method to retrieve a viewpoint for this object. If, in real life, we go from one place to another, we follow a certain path. Since paths are seldom straight, we cannot use a starting point and an ending point alone, we need intermediate points that indicate angles, places in real life where the direction changes. POIs with a certain orientation are also known as viewpoints 1. 1 It is important to understand that there is a differerence between Points-of-interests and viewpoints. A Point-of-interest is simply a location, it has coordinates. A viewpoint also has orientation. A viewpoint in 3-dimensional worlds is also called a camera. In 3-dimensional worlds, we use viewpoints. Therefor the semantic mapping provides a binding 43
70 44 CHAPTER 4. PATHMANAGER These POIs will be retrieved from the ontology and we apply the semantic mapping, in the same way as we did for the Vrtual Objects, only this time we map the Virtual Objects to viewpoints. After having re-applied the semantic mapping, we have an in-memory map of all virtual objects, and we have attached viewpoints to them. We want to connect Virtual Objects so we can derive paths between them. We can connect Virtual Objects by indicating their relative positions, for instance Object A is above Object B. We could also define a less restrictive connection pattern, indicating that virtual object A is connected to virtual object B. Since the ontology provides us with the virtual objects to display, it must also provide us with the connectivity between the virtual objects. In other words; the ontology must provide us with the cognitive map we will use to navigate. Our path manager is now aware of the different virtual objects and their corresponding viewpoints and the connectivity between the objects. We have constructed a graph. 4.2 Navigation by query As we have explained in our previous chapter, our primary means of navigation will not be user-initiated, using mouse-gestures or arrow controls to go forward, turn etc. We will use a query-based navigation. We let the user ask a question to the system, the system will guide the user to the destination, based on the result of the query. For our cognitive map, the representation of the map in the Virtual World, we will use a graph, connecting different landmarks. Intermediate landmarks will indicate places where the direction of the path changes. The map, represented by a graph, can now be used to guide us from our starting point to our destination. Depending on the type of graph (directed, weighted, etc), different shortest-path search-algorithms, like breadth-first or Dijkstra, can be used. Based on the destination, mapped to a viewpoint in the graph, the pathmanager will return the path to follow when travelling from A to B. to viewpoints and not POIs.
71 4.3. CONSTRUCTING THE NAVIGATION PATHS 45 So, instead of letting the user navigate through the world itself, we propose a system in which a user queries some sort of engine, and the result is used to move the navigator from viewpoint to viewpoint, imitating a natural path as if we were walking in the Virtual World. 4.3 Constructing the navigation paths Once we have a cognitive map, we can use a search algorithm to get from a certain starting point to our destination. Since we use viewpoints, each POI has an orientation, we can implement a navigation path that looks natural. The question is how we get the initial viewpoints, that make up our path, to start with. Kleinermann et al. [34] use semantic annotations by letting users position a POI on an object or around it. They use two different ways for positioning POIs: grid positioning, where the designer can position POIs according to predefined positions for the POI, and freehand positioning, where the designer can position an object and add a viewpoint anywhere on (or inside) an object. Their definition of navigation paths follow the same approach, linking different landmarks, where a landmark is a POI with an orientation. All their annotations, landmarks etc. are uploaded into a reasoner. Our approach is a bit different, we used a map on which we placed navigation paths. The intersections and end-points can be used as landmarks. As example, we will look ahead to the situation we also use in our proof of concept, later on in this document. We take a map of the campus of the Vrije Universiteit Brussel (VUB) as indicated in the following image: We overlay the map with a graph, each end-point and each intersection point becomes a point of interested. We have numbered the points for reference. This implies that we use the ontology to store connections between Virtual Objects, not their relative locations! This graph can be easily stored in the ontology. All we need to say is that a point A is connected to point B. For bidirectional graphs we also encode the link between point B and point A. The graph is ready, we know the different POIs and the connections between them. How do we relate these POIs to viewpoints, points with an orientation, useable in
72 46 CHAPTER 4. PATHMANAGER Figure 4.1: The map represented as graph Virtual Environments? The POIs that are stored in the ontology are names of points and their connectivity. These POIs have no orientation. For example; when looking at the intersection in the lower-left corner of the image, we see that POI number 2 is connected to POI 1, 3, 4 and 6. This implies that for POI number 2, we have to define 4 viewpoints, since viewpoints have an orientation as well. We defined a viewpoint for the path from viewpoint 2 to viewpoint 1, from viewpoint 2 to viewpoint 3, from viewpoint 2 to viewpoint 4 and from viewpoint 2 to viewpoint 6. Using Google Sketchup, we navigated to the POIs that we indicated in the previous step. We orientate ourselves in such a way that our current camera/viewpoint is looking to the next viewpoint. This position, including orientation, is saved, so we can convert them to useable viewpoints afterwards, in the format we will use to construct our Virtual Environment (X3D, O3D,...).
73 Chapter 5 Approach implementation - a case study This chapter describes the application built on the ideas that we highlighted in the previous chapters. As described earlier, our application shows a paraverse, a real-life kind of Virtual World (VW), that is driven by an ontology. With this we mean that the information we show in the VW comes from the ontology and additionally, we use the ontology to help us with navigation. The application we built uses the campus of the Vrije Universiteit Brussel (VUB) as its paraverse. The ontology therefore contains notions of the buildings on the campus and any additional information that can help us for our query-based navigation. For example; we use names, telephone numbers and roomnumbers of employees of the university, building a minimal telephone-book. 5.1 The technical building blocks When implementing a proof-of-concept (POC), some technological choices need to be made. These choices are related to 3d engines, application environments, related utilities etc. Which one do we use and why? To build our POC, we will use the following technologies. Most of them have 47
74 48 CHAPTER 5. APPROACH IMPLEMENTATION - A CASE STUDY already been explained in the previous chapters, in this section we will provide a justification why we chose these specific technologies over alternatives. X3D The choice for X3D is made because it is an open standard, supported by W3C. Additionally, it is proposed as part of the new version of HTML (HTML5), which means that, if implemented by browser vendors, no additional plugins will be needed. O3D, Google s API, is open-source, so it would have been a very good alternative. O3D is much tighter coupled to the platform on which is runs (WebGL), where X3D is platform independent. The first beta versions of all major browsers currently support HTML5. Adobe Flex Arbitrary choice, but again the choice is driven by the fact that the platform is open source and it is browser independent. Flex has an object-oriented language embedded, called ActionScript and additionally has a lot of strong widgets, making web-development easy. Silverlight (Microsoft) would have been an alternative platform. It has C# as backing language (in fact, any of the languages running on the Microsoft runtime environment can be used), which is an object-oriented language. It also has a strong widget set. The platform is closed and not free, making this a less obvious choice. jquery It is a Javascript library and framework which is very strong in handling asynchronous requests with the webserver and DOM manipulation. This is also an arbitrary choice, any framework could have been used. OWL OWL stands for Web Ontology Language and is a family of languages used to write ontologies. SPARQL The SPARQL Protocol and RDF Query Language (SPARQL) is a query language and protocol for RDF. Joseki Joseki is an open-source HTTP engine, that supports SPARQL queries. It is based on Jena, a Java framework for building semantic web applications. This is an aribitrary choice, it was the first one we found and it serves our purposes.
75 5.1. THE TECHNICAL BUILDING BLOCKS 49 Let s map these technologies to the design we have already highlighted in our approach: Figure 5.1: Application design - high level overview When we look at the image, we can split it into three parts; the ontologies (webresources) that are accessible via http and connected via the bus, our server-side application containing the semantic mapping and the path-manager and the client side, containing the browser for the virtual environment. We will now position the different technologies in these three blocks: Ontology related Joseki - The HTTP engine that responds to SPARQL queries. We can access this engine from our application (server side) and query it via SPARQL. Joseki can be seen as the implementation of the bus in the image.
76 50 CHAPTER 5. APPROACH IMPLEMENTATION - A CASE STUDY OWL - The ontologies themselves are written in OWL. OWL is one of the languages that can be used to write ontologies, OWL, on its turn, is based on RDF. Server side application Adobe Flex - The server side of the application, including the Semantic Mapping and the Path Manager are written using Adobe Flex, a Flash based application framework that uses an Object Oriented language called ActionScript. Client side application X3D - The language used to build up our Virtual Environments. jquery - a javascript engine that is very good in handling asynchrounous callbacks. Adobe Flex - The controls of the client side of the application are also written in Adobe Flex. In fact, a Flex application often provides a server- and a client-side part, where the client side is built with widgets that interact with the server side The ontology The ontology we have used for the proof of concept is based on an existing ontology by Patrick Murray-John [37] It describes a Campus consisting of CampusPlaces, Courses, Organizational units, Persons extending foaf:persons 1. We have extended this ontology by adding the following objects: Staff, extending the Person class from our base ontology. AcademicStaff, extending Staff Professor, extending AcademicStaff Assistent, extending AcademicStaff 1 FOAF stands for Friend of a Friend and is on ontology describing persons, activities and relationships.
77 5.1. THE TECHNICAL BUILDING BLOCKS 51 Researcher, extending Assistent AdministrativeAndTechnicalStaff, extending Staff Building, extending the CampusPlace class from our base ontology Floor, extending the CampusPlace class from our base ontology Room, extending the CampusPlace class from our base ontology In our ontology, each Staff-member has a room. Rooms are logically assigned to Floors, floors on their turn to buildings. It is clear that this is a very limited setup, but the goal was not to design a university ontology. We wanted to have information available which we could relate to campusplaces, which are mapped to points-of-interest in our application. We use the ontology to query for a person s name, for instance, and as a result we get the building in which this person has a room. The ontology stores triples, that are basically relationships between two nodes. We use the Web Ontology Language (OWL) to build our ontology. Web Ontology Language As a small example; the definition of a Professor Class in OWL: <owl:class rdf: <rdfs:subclassof rdf: <owl:disjointwith rdf: </owl:class> We define that a professor is part of academic staff, and a professor is not a researcher. When creating an object (an instantiation of a class), we might have something like this: <Professor rdf: <hasfirstname>olga</hasfirstname> <hassurname>de Troyer</hasSurName> <hastelephonenumber> </hastelephonenumber> <hasfaxnumber> </hasfaxnumber>
78 52 CHAPTER 5. APPROACH IMPLEMENTATION - A CASE STUDY <worksforunit rdf: <hasroom rdf: </Professor> The relationships between nodes in the example above are, for example has- Room that connects a professor with a room. The room refers to another ontology, that is defined in the header of this specific ontology. SPARQL We use OWL as language to define our ontology, we also need a way to retrieve the information from it. SPARQL is a standardized RDF query language, we use it to query our ontology. Based on the example previously given, we also provide a small SPARQL query, an example to query for a roomnumber. PREFIX vub: <> PREFIX rdfs: <> SELECT?professor?roomNumber FROM <Data/staff.owl> WHERE {?professor a vub:professor.?professor vub:hassurname "De Troyer".?professor vub:hasroom?room.?room vub:hasnumber?roomnumber } Other university ontologies Some other projects (other than the base of our ontology) have also explored the possibilities to model a campus. Benjamin Nowack proposes Semantic Campus - a FOAF extension 2 that describes campus-related resources such as universities, departments, lecturers and students. It has no notion of physical, geographical locations. Jeff Heflin defined a university ontology 3, but has a strong focus on documents that are published and has no location information. 2 pp/semantic campus/ 3
79 5.1. THE TECHNICAL BUILDING BLOCKS 53 While the concept has not been finalized yet, Patrick Murray-John is thinking [38] about a giant edu-graph that combines ideas, subjects, people and the resources used in teaching and learning. This project is interesting, since it combines several ontologies; FOAF (Friend Of A Friend), the Bibliographic Ontology, GeoNames, SIOC (Semantically Interlinked Online Communities) to name a few External information We have a ontology that defines buildings, employees of the university etc. But we also mentioned that we use external information to enrich our virtual world. For our proof of concept, we used METAR information, weather information often used by pilots. This is an old format, dating from 1968, obviously not available in RDF. We wrote a small application that parsed the METAR string and returned it in RDF. The input string and the resulting RDF information are added in the appendix The Virtual World - The campus in 3D Sye Nam Heirbaut has developed a 3D version of the campus using Google Sketchup, a tool that can be used for 3d modeling. His work is used as base for our 3d world. This work was done as a student job, unrelated to any university project. The result of his work is used in this project however, since it provided a complete model of the campus, and we could export the models to VRML. Using VRML and Vivaty Studion we could translate it to X3D. This section describes the steps involved in creating a Virtual World in X3D based on the Google Sketchup models. We will start by a small explanation on X3D. extensible 3D We have chosen extensible 3D (X3D) for the fact that it is an open standard, supported by W3C and it is designed in such a way that it is platform independant. Scenes are not tied to underlying hardware specifications, screen resolutions etc. X3D files are read and parsed by X3D browsers. An X3D Browser is responsible for the interpretation, execution and presentation of the X3D Scene Graph. It is
80 54 CHAPTER 5. APPROACH IMPLEMENTATION - A CASE STUDY the browser that understand the contents and know how to render its information, resulting in the display of virtual objects. We call the representation of an X3D Scene graph a Virtual World. Browsers can be desktop application or plugins in web-browsers. Before going into more detail, we will provide a small example of an X3D file, based on an example by Don Brutzman [19]: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE X3D PUBLIC "" "/"> <X3D> <head> <meta name= filename content= geometryexample.x3d /> <meta name= author content= Don Brutzman /> <meta name= created content= 8 July 2000 /> <meta name= revised content= 5 January 2001 /> <meta name= url content= examples/course/geometryexample.x3d /> <meta name= description content= User-modifiable example to examine the role of the geometry tag. See what nodes can be replaced: geometry (no) and Cylinder (yes). /> <meta name= generator content= X3D-Edit, translation/readme.x3d-edit.html /> </head> <Scene> <Shape> <Appearance> <Material diffusecolor= /> </Appearance> <Cylinder/> </Shape> </Scene> </X3D> This example demonstrates a simple cylinder. While in this specific case, the metadata may seem heavy, in larger files, this will be less an issue. Each X3D application [4]: 1. implicitly establishes a world coordinate space for all objects defined, as well as all objects included by the application; 2. explicitly defines and composes a set of 3D and multimedia objects; 3. can specify hyperlinks to other files and applications; 4. can define programmatic or data-driven object behaviours;
81 5.1. THE TECHNICAL BUILDING BLOCKS can connect to external modules or applications via programming and scripting languages; This leads to the following overview as described in Image 5.2: Figure 5.2: X3D System Architecture The image shows that a browser should be able to render X3D, but also VRML, X3Ds predecessor and binary X3D. The Scene Access Interface (SAI) is used for event passing with external applications. Scene Access Interface The Scene Access Interface (SAI) is a application programmer interface (API) that defines runtime access to the Scene. The SAI is used to create nodes, modify nodes, send events to nodes etc. We use the library created by Ajax3D [5] for our application. This library already defines Javascript methods that use the SAI to create an initial scene and add
82 56 CHAPTER 5. APPROACH IMPLEMENTATION - A CASE STUDY virtual objects. Google Sketchup We received an initial file of the entire campus in Google Sketchup format. The file, as we received it, was not useable for the web, due to its size and format, so we had to make it web-friendly. Starting from the initial file, we started by isolating all buildings. With this we mean that for each building in the campus, we removed all unrelated information. In other words, we started from the initial campus and removed all buildings, except the one we wanted to isolate, on a per-building base. The result is that, instead of one big file containing the entire campus with all it s buildings, we now have created multiple files, one per building. The buildings themselves still have their geo-location which was available in the initial Skecthup file. The next step was to create a simplified version of the building. Removing as much detail as possible, reducing the building to basic building blocks. This was typically done by taking the roof of the building, removing the entire structure underneath and afterwards extend the roof until the ground. Afterwards, we applied a texture to the buildings. The texture itself was taken from an image created with the Google Earth plugin called V-Ray for Sketchup 4. The final step in Google Sketchup was to export the buildings to VRML format. 5 Vivaty Studio Vivaty Studio, formerly known as Flux Studio, is a tool that allows the user to manipulate 3d scenes. The application allows, amongst others, to import VRML scenes and to export them to either uncompressed X3D or compressed X3D. We actually used the tool for both. We exported to uncompressed X3D to get the viewpoint we previously set in Google Sketchup 6, and we also used it to get a 4 We also directly applied a default viewpoint to the scene, for later use. 5 This is a feature that is only available in the Google Sketchup PRO version. 6 Vivaty somehow loses the viewpoints parameters, these need to be manually set
83 5.1. THE TECHNICAL BUILDING BLOCKS 57 compressed version of the scene. 7 Binary compression of the X3D files, greatly enhances downloadspeed. The downside is that the DOM structure of the binary file is no longer accessible which implies that the scene is no longer modifiable from the SAI afterwards. The solution to this problem is to compress the visual part of the scene after having seperated it from all non-visible nodes (like viewpoints, scripts etc). The nonvisual nodes are placed in a the text-version which references the binary file. An example can be found in the appendix. The reason for simplifying and compressing becomes clear when we look at the following table which highlights the file-size differences between the different possibilities (file-size of resulting.x3d files): Sketchup VRML Uncompressed X3D Compressed X3D Unmodified 13.6 Mb 17.3 Mb - - Simplified 10.5 Mb 119 Kb 227 Kb 10 Kb With textures 10.6 Mb 131 Kb 242 Kb 20 Kb Table 5.1: Compression differences between VRML, X3D and X3D compressed In case of the unmodified version, Vivaty studio is unable to export it as either form of X3D (uncompressed or compressed). The result of the simplified version and the version with an applied texture can be found in the appendix. We could improve the display result by using more detailed base structures etc (less abstraction), but this would increase the number of polygons that define the buidling. We could also improve the quality and the number of textures, which are simple images applied on a surface, but this would increase the file-size and thus also increase the render time. We chose a very simple texture to reduce the filesize of the image which means that we load the entire scene faster. The trade-off is between appearance and speed. 7 In the compressed version, we removed the viewpoint so we did not have any duplicate viewpoints.
84 58 CHAPTER 5. APPROACH IMPLEMENTATION - A CASE STUDY Semantic mapping We explained in our chapter on the approach, that we use a semantic mapping to relate ontologies to virtual environments. In our approach, we use OWL to define our ontology, we use SPARQL to retrieve information from it, and on the other side we use X3D for 3-dimensional representation of these objects. How does the semantic mapping connect these technologies? When the application starts up, it will start by getting information on the virtual objects that we need to display. This information comes from our ontology, but this information contains no visualisation information, we receive the buildings we would like to display in our paraverse. To get the display information, we map the objects to their 3-dimensional representation. The mapping uses an initial query to ask the ontology for the virtual objects to display. We also need a mapping file, that maps each object to an X3D file. When we have the objects we would like to display and we have their 3-dimensional representation in the form of an X3D file, we perform a function call on the Scene Access Interface, so we can add the object to our Virtual World. It is important to realise that we add multiple objects. For each object we received from our ontology, we perform a mapping. A mapping might look like this: <SceneMapping> <Mapping> <URI></URI> <SceneURL></SceneURL> </Mapping>... </SceneMapping> We have mapped our information from our ontology, building M indicated by the URI to a 3-dimensional representation in X3D: Using the Ajax3D implementation [5] we already have a function available to add the specific X3D information to the existing virtual world.
85 5.1. THE TECHNICAL BUILDING BLOCKS 59 External information We also use the semantic mapping to map external information. The procedure is the same, except for the fact that we can no longer use the Javascript call from Ajax3D that was used to add virtual objects. External information might alter the virtual world, instead of adding a virtual object. This implies that for external information, we do not map to an X3D file that represents the information, we map to a Javascript function call instead. It will be the implementation of the Javascript function that handles the external information. A small example will make things clear: Imagine that we would like to add weather information to our virtual world (this is actually what we do in our proof of concept). We do not add any objects when weather changes, instead we change the sky according to the weather conditions. We might also want to activate some fog in our virtual world. In this case, we will have a javascript function that receives weather information and modifies the scene accordingly PathManager The PathManager is the component that guides the user to its destination by providing the path from its current location to the destination, using a search algorithm over a graph. Figure 5.3: The map represented as graph We started by creating a graph that is an abstraction of the walking paths a person
86 60 CHAPTER 5. APPROACH IMPLEMENTATION - A CASE STUDY can take on the campus. The graph is created by taking a map of the campus and drawing routes on top of it. The resulting graph is shown in Image For the sake of simplicity, we use an unweighted bidirectional graph, so we can easily apply a Breadth-First-Search (BFS) algorithm to dynamically find a shortest path between two nodes 9 We retrieve the connections between the different points from the ontology. They are mapped to viewpoints, points with a certain location. Since these viewpoints are non-visible elements of a SceneGraph, we can use the same semantic mapping as we used to add virtual objects to the scene. We also use the same Javascript function call, using the Ajax3D API. At this point, we have a fully initialized application. The initial virtual objects are shown, it is enriched using external information, we have a representation of the Virtual World in the form of an in-memory graph which is handled by the PathManager and we have the query available to respond to any question coming from the user. The process of guiding the user are the following: 1. The user submits a query. The application translates this to a SPARQL query (static mapping) 2. Whether we ask information about persons, rooms, courses, the result will always be a building. This result is passed on to the PathManager. The PathManager knows the current location and knows the destination, which is related to the result of the query. It will return the starting viewpoint, a list of intermediate viewpoints and the destination viewpoint based on a graph search algorithm. 3. For each step in the list of viewpoints, the renderengine receives a functioncall to change the current viewpoint. We have added a small delay between each function invocation to give the navigation a more natural look and feel. 8 The actual implementation only implements a part of this graph, due to the fact that Vivaty Player only supports a limited number (65) of viewpoints 9 A more realistic approach would be to use a weighted graph, with the lengths of the paths as the weight of the vertices. This is possible of course, but then we would have to use a more complicated search-pattern, like Dijkstra s Shortest Path algorithm for example. This approach is out of scope for this POC, since it does not add any additional value to the challenges we address.
87 5.2. THE RESULT The User Interface We have chosen for a minimalistic search interface. The user can select the viewmethod (either jump or guided tour) and provide text, as search-input. Using ConcurTaskTrees (CTTs) 10, we come to the following overview: Figure 5.4: Concurrent Task Tree of the user interface The overview is very limited, it tells us that when we provide a request, we need to select a viewmethod and provide a query, this input can be provided in any order (indicated by the operator). Afterwards the first task is terminated and the second task performs, based on information coming from the first task (indicated by the []>> operator). 5.2 The result We have created two versions of the application, a guided tour and a version in which we use a simple search-engine, which queries the ontology providing us with query based navigation. 10 [6].
88 62 CHAPTER 5. APPROACH IMPLEMENTATION - A CASE STUDY In both cases, the user-interface is very similar. Figure 5.5: Screenshot of the application in action Image 5.5 shows the version of the application in which we can query the ontology. The application shows that we have searched for building M, and where the result gets mapped to a building. The building gets highlighted, which is shown in both the 2d map and the 3d world. There are two remarks concerning the image: The purpose was to highlight the building by changing its color. However, Vivaty doesn t allow to query the scenegraphs of binary scenes, so we placed a transparent box around the building as workaround. The 2d map was intended to be embedded as HUD, but Vivaty player is not stable enough to allow this, the map is now an embedded image in the webpage and is not a part of the scene Guided tour - Esplanada The guided tour is the application we started with. It follows the travel control way of navigation [56], or the Navigation by Query [52], but in a very simplistic
89 5.2. THE RESULT 63 way. Navigation by query implies that the user does not navigate himself, it is the system that guides the user through the Virtual World. The esplanada website 11. shows the visitor the location of interesting points/buildings on the campus by starting from a bird-eye view, zooming onto the requested location and zooming back out again. These movies are created in Google Sketchup and recorded as Flash movies. In fact, these movies are based on the same Google Sketchup model as we used for our POC. The 3d-world of our application mimics the behavior of the Esplanada introduction movies on the Esplanada website of the VUB. The Esplanada demonstration was easy, simply proving the concept that we could navigate in a Virtual World. It contained hard-coded POIs (Point Of Interests), that are available for selection in a drop-down box, as well as hard-coded paths from a starting point, to the destination and back again. The fact that hardcoded POIs are used implies that we make no use of the ontology yet. The viewpoints that were used for the movies were already available in the Google Sketchup project, so we started by extracting these viewpoints in the form of VRML and translated them to X3D using Vivaty Studio. The Points Of Interests (POIs) are available in a dropdown list in the application. Of course, they are indicated by a name that is understandable for the user, like Restaurant, Building C etc. A dedicated PathManager was written to return the viewpoints, as a path to follow when navigating from a starting point, typically the current location of the user, to a destination, the result of the query initiated by the dropdown box Query based navigation A far more interesting application of the design is the use of the ontology to provide us with the destination viewpoint. Instead of supplying a dropdown box with predefined locations, we retrieve the locations from the ontology. The ontology is used to build a conceptual map of the campus by connecting all viewpoints as a graph. This graph is managed by our PathManager. The dropdown-box is replaced by a search option, which will be used to query the ontology. The result of the query will have some sort of geographical knowledge 11
90 64 CHAPTER 5. APPROACH IMPLEMENTATION - A CASE STUDY which will be used to query the PathManager for a path from the current position to the destination. The destination is a viewpoint, which is related to the result of the query. The graph manager returns the route to follow based on its internal graph. Moving between viewpoints now becomes a fluent movement, simulating the path a user will take when walking from one point to another in a real-life environment Considered approaches We examined some additional approaches for the POC, but had to abandon them due to technical reasons. Here is a small list that might be useful for future reference: The use of Level Of Detail (LOD). The idea was to change the image by one with a higher level of detail, when closer to the object. This way, we could only load the low-level image to start with, when approaching it, load the high-resolution version, so we could increase the level of details when zooming in. This does not work, since LOD requires that both versions are preloaded. Use of Javascript. In general we can say that Vivaty player and Javascript don t go well together. The player crashes often, reacts differently depending on the version. We therefor completely avoided the use of scripts within the X3D scene. The use of O3D. Google provides a tool to easily transfer.x3d files to.o3d files, in other words; to transfer x3d objects to o3d. This was very easy to implement, the result looked very good. The approach proved that the ontology did not need to change when changing the render engine. However, changing the viewpoints was a bit more challenging and this attempt was abandoned so we could focus on our main project Existing similar paraverses A lot of universities have a Virtual University (VU) in Second Life, these VUs explore the aspects of online learning, collaboration etc. Besides that, a lot of universities have a pure visual 3d representation in Google Earth. These fall outside
91 5.2. THE RESULT 65 the scope of this research, since they are based on virtual campusses for e-learning purposes. There are, however some projects that explore similar possibilities: F.E. Dozzi created for his/her master thesis a proof of concept (2000) to examine 3-d Virtual Worlds on the Internet using VRML, modeling the campus of the University of Amsterdam 12 Joris Gillis started an (unfinished) project at the University of Leuven where he uses Google Sketchup to create a 3d map of the campus and publish it on the web. 13 None of these two projects used ontologies. 12 eliens/archive/scripties/fedozzi/ 13 s /projects/campus3d
92 66 CHAPTER 5. APPROACH IMPLEMENTATION - A CASE STUDY
93 Chapter 6 Overall limitations Using information from the ontology in combination with semantic mappings gives us a relative flexible approach, but there are some limitations in our approach. The limitations fall under two categories; the semantic mapping being static and the pathmanager that uses a predefined graph. 6.1 Semantic mapping The semantic mapping bridges the information from the ontology and the virtual environment. The main limitations of our approach lie in the fact that the mappings are static. Users cannot influence the mappings, this needs to be done by the maintainer of the application Adding new objects Adding new virtual objects does not require code changes. The ontology needs to change, since the query now also must retrieve the new object. If the object is provided in the same way as the other virtual objects, the query (for instance: getallbuildings) does not need to change. However, the semantic mapping itself is static; adding new virtual objects requires that the mapping needs to be adapted. If no mapping is available, virtual objects 67
94 68 CHAPTER 6. OVERALL LIMITATIONS will not be displayed. This as such is not a real limitation, the limitation lies in the fact that this mapping is implemented in text-files that reside on the server. The mappings are only editable by the application administrator, not by users Changing the queries This mapping uses SPARQL to query the ontology, these queries are, just like the mappings, encoded in text-files. There are two issues with this approach. The first issue is that the interfaces of these queries are fixed. If we would like to return more information from the query, or change parameter names, we need to adapt the query, but also the application code to deal with those changes. Again, the queries are on the server, the queries cannot be modified by the user of the system. It is up to the maintainer of the application to decide which information is visible and in what way. 6.2 PathManager The pathmanager queries the ontology for POIs and the connections between them. These connections are currently coded in the ontology, not derived via inference. If routes change, the ontology needs to be adapted. Since we use semantic mappings between the POIs and viewpoints in our virtual environment, we also need to adapt the mapping and the viewpoints. Again, these mappings are done at the server.
95 Chapter 7 Conclusion Web 3.0 is on our doorstep, and although the defintions of what web 3.0 exactly is differ, most defintions agree that the semantic web is part of it, and possible also web3d. In this thesis, we have used the semantic web (ontologies) to enrich the 3-dimensional web. Enrichment from data point-of-view, but also from usability point-of-view. We have done this by addressing three challenges: Initiating a Virtual World using ontologies Enriching the Virtual World with near real-time external data Using the ontology to help us with navigation We have shown that we can use an ontology as base for Virtual Environments. We use semantic mappings to map our information of virtual objects to their 3- dimensional representation. Doing this, the virtual objects we show are becoming must more than a collection of polygons, textures, etc. that make up a Scene- Graph. The virtual objects in a virtual environment can be given a meaning, becoming objects of which we know what they are. Additionally, we have shown that it is possible to enrich the virtual environment with external data. We can combine multiple external resources into a single new resources, which follows the idea of mashups and all this be done in a near real-time way. To be able to use different data-formats, we have used dedicated 69
96 70 CHAPTER 7. CONCLUSION translators that parse the data and provide it in RDF format, so we can query it in the same way we query the ontology. Finally, we have used the ontology to help us with navigational issues. It is easy to get lost in virtual worlds, so instead of letting the user navigate, we let our application help the user. Our approach is based on Navigation by query. We have introduced a path manager that, in combination with the semantic mapping, constructs a cognitive map of the virtual world we are using. This map is internally represented as a graph, and the path manager can now construct our navigation path using a search-algorithm on this graph. It uses the current location as starting point and the destination will be tied to the result of a query to the ontology. This path is visualized as a sequence of viewpoints which we follow, giving the user the impression that he is walking in the virtual world. 7.1 Future work Currently, our ontology has no knowledge of locations. We query the ontology for buildings on the campus, or in a more specific approach, we query the ontology for the virtual objects to display. The result is a list of buildings/virtual objects and the semantic mapping maps these to their visual representation. It is the visual representation that has geospatial knowledge. A future improvement might be to extend the ontology with geospatial knowledge using GeoRSS encoding. The W3C Geospatial Vocabulary 1 defines a basic ontology and OWL vocabulary for representation of geospatial properties including points, lines, polygons, boxes and more. We could also think of adding referential knowledge to the ontology, for example: building A is next to building B. This knowledge can be used, via reasoning, to create the graph that is used by our pathmanager for tourguides. Another thing we can imagine is a more flexible approach towards external information. At the moment, external information is mapped to functioncalls at the client side. This mapping is static, it needs to be added by the application maintainer. We could imagine a more dynamic approach, where the user can connect the external information to the appropriate function call. This will lead to some additional challenges where the user also needs to have the ability to inject client- 1
97 7.1. FUTURE WORK 71 side calls, like Javascript functions. Of course, we can extend the combination of ontologies and virtual worlds by adding multiple users, chat options. It would be very interesting to login, see if certain persons are online and directly have the ability to start a chat session, collaborate on documents etc. Finally, the current limitations need to be addressed. The semantic mappings and the queries to the ontologies are static, they reside in files on the server and can only be modified by the application administrator. It would be interesting to see how this can be made more flexible.
98 72 CHAPTER 7. CONCLUSION
99 Appendix A Model simplification Building B/C. The unmodified version has a file-size of more then 17 Mb when exported to VRML. The reduced version has a filesize of 119 Kb, when exported to VRML. Afterwards we apply texttures. The export to VRML now takes 131 Kb, the size of the texture is 12 Kb. In X3D we can use binary (compressed) scenes, reducing the overall size to 20 Kb. Figure A.1: Google sketchup - single building, original Sketchup version 73
100 74 APPENDIX A. MODEL SIMPLIFICATION Figure A.2: Google sketchup - single building, simplified Figure A.3: Google sketchup - single building, simplified, textures applied
Johan Van den Broeck
FACULTY OF SCIENCES Web & Information Systems Engineering Error-correction for Ontology-based Websites through a Version Log A thesis presented in fulfilment of the thesis requirement for a License Degree
JCR or RDBMS why, when, how?
JCR or RDBMS why, when, how? Bertil Chapuis 12/31/2008 Creative Commons Attribution 2.5 Switzerland License This paper compares java content repositories (JCR) and relational database management systems
MEMOIRE PRESENTE A L'UNIVERSITÉ DU QUÉBEC À CHICOUTIMI COMME EXIGENCE PARTIELLE DE LA MAÎTRISE EN INFORMATIQUE PAR WEI RAN B.A.A.
MEMOIRE PRESENTE A L'UNIVERSITÉ DU QUÉBEC À CHICOUTIMI COMME EXIGENCE PARTIELLE DE LA MAÎTRISE EN INFORMATIQUE PAR WEI RAN B.A.A. SEMANTIC WEB AND BUSINESS APPLICATION April 2011 Content Abstract - 1 Résumé
INTRODUCTION TO THE INTERNET AND WEB PAGE DESIGN
INTRODUCTION TO THE INTERNET AND WEB PAGE DESIGN A Project Presented to the Faculty of the Communication Department at Southern Utah University In Partial Fulfillment of the Requirements for the Degree
Master Thesis. Viban Terence Yuven. Harnessing The Power Of Web 2.0 For Providing A Rich User Experience In An elearning Application
Hochschule für Angewandte Wissenschaften Hamburg Hamburg University of Applied Sciences Master Thesis Viban Terence Yuven Harnessing The Power Of Web 2.0 For Providing A Rich User Experience In An elearning
Organization of Flexible User Interface for Policy Management Systems Supporting Different Rule Abstraction Levels
Faculty of Computer Science, Electronics and Telecommunication Organization of Flexible User Interface for Policy Management Systems Supporting Different Rule Abstraction Levels Ph.D. Dissertation Author: TITLE: Virtual Service AUTHOR(s): R. David Lankes PUBLICATION TYPE: Chapter DATE: 2002 FINAL CITATION: Virtual Service. Lankes, R. David (2002). In Melling, M. & Little, J. (Ed.),
Introduction to SOA with Web Services
Chapter 1 Introduction to SOA with Web Services Complexity is a fact of life in information technology (IT). Dealing with the complexity while building new applications, replacing existing applications,
Architectural patterns
Open Learning Universiteit Unit 3 Learning Unit 3 Architectural patterns Contents Introduction............................................... 35 3.1 Patterns..............................................
Detecting Inconsistencies in Requirements Engineering
Swinburne University of Technology Faculty of Information and Communication Technologies HIT4000 Honours Project A Thesis on Detecting Inconsistencies in Requirements Engineering Tuong Huan Nguyen Abstract
Vrije Universiteit Brussel Faculteit Wetenschappen Departement Informatica en Toegepaste Informatica,
THE DESIGN AND IMPLEMENTATION OF AN E-COMMERCE SITE FOR ONLINE BOOK SALES. Swapna Kodali
THE DESIGN AND IMPLEMENTATION OF AN E-COMMERCE SITE FOR ONLINE BOOK SALES By Swapna Kodali Project Report Submitted to the faculty of the University Graduate School in partial fulfillment of the requirements
Integrating Conventional ERP System with Cloud Services
1 Integrating Conventional ERP System with Cloud Services From the Perspective of Cloud Service Type Shi Jia Department of Computer and Systems Sciences Degree subject (EMIS) Degree project at the
Use of IFC Model Servers
Aalborg University Department of Production Department of Civil Engineering Aarhus School of Architecture Department of Building Design Use of IFC Model Servers Modelling Collaboration Possibilities in
Development of support web applications in.net
Development of support web applications in.net For Visit Technology Group Master of Science Thesis in Software Engineering and Technology ANDERS CLAESSON CHRISTOPHE DUBRAY Department of Computer Science
AN OBJECT-BASED SOFTWARE DISTRIBUTION NETWORK ARNO BAKKER
AN OBJECT-BASED SOFTWARE DISTRIBUTION NETWORK ARNO BAKKER COPYRIGHT c 2002 BY ARNO BAKKER The cover of this dissertation illustrates the difficulty of content moderation. VRIJE UNIVERSITEIT AN OBJECT-BASED
1Introduction to SharePoint 2010
1Introduction to SharePoint 2010 WHAT S IN THIS CHAPTER? Information about tools to integrate with Silverlight, LINQ, and BCS New features in social computing New features in ECM New features in Search
Working Paper Series of the German Data Forum (RatSWD)
Working Paper Series of the German Data Forum (RatSWD) The RatSWD Working Papers series was launched at the end of 2007. Since 2009, the series has been publishing exclusively conceptual and historical | http://docplayer.net/988168-Vrije-universiteit-brussel-faculteit-wetenschappen-departement-informatica-en-toegepaste-informatica.html | CC-MAIN-2016-44 | refinedweb | 20,952 | 53.1 |
C and C++ are probably the only viable languages for true cross-platform development.
- Introduction
- The Salami Method
- Beautiful Symmetry
- Write Once, Run Anywhere… Not!
- Meta
Introduction
Over the past several years, I worked on several core C++ libraries that needed to be integrated into multiple platforms. The same C++ code needed to run on mobile devices (iOS, Android), desktops (Windows DLLs, Linux shared objects), cloud services (Linux and .NET integration) and web-browsers (emscripten, FireBreath).
That is quite a list of target platforms, each with its own constraints, its own “native” environment, language, run-time, type-system, UI-system and OS models. In this context, “native” means the “natural” way to develop on the platform, e.g. Java on Android, JavaScript in the browser and Objective-C/Swift on iOS. This is contrary to C++ being a “native” language in the “Going Native”, bare-metal, sense.
Along the way, I developed my own way of structuring such cross-platform (core) C++ code.
The Salami Method
Like all good architectures, the Salami Method tries to cleanly separate concerns.
Nevertheless, it lacks the greasy, heart-attack-inducing goodness of a good salami.
Be it creating DLLs, Android NDK/JNI, C++ on iOS or even GUI-based desktop apps, many samples, articles, tutorials and examples frequently mix platform specific code with core functionality. While this might serve to demonstrate specific API usage and techniques, it often leads to spaghetti code. The result is a refactoring and maintenance nightmare that is non-portable, untestable with ample nooks and crannies for bugs to hide in. To make things worse, module boundaries (e.g. DLL APIs), are dangerous places where error handling must be considered and addressed carefully as things like exceptions might not be able to percolate further causing program termination or undefined-behavior..
The benefits of thinly slicing our API include:
- The DRY principle: Sharing as much code as possible between platforms, avoids duplication and reimplementation.
- Single Responsibility and Testability: Each layer has its own single purpose and can be debugged and tested independently.
- Consistency: Business logic remains isolated in the deepest layers and is shared among all target platforms. This ensures consistent behavior across platforms.
- New Platforms: Code is future ready for targeting new platforms.
- Developer Skills: Leverage skills of different developers independently at relevant parts of the code. No mixing of concerns.
- Refactoring: Well separated concerns allow for easier refactoring.
We identify the following conceptual layers:
Often you will find that not all of these layers make sense as distinct code layers. In some situations it may be more practical to merge two layers into a single layer - thicker slices, if you will.
Similarly, some platforms may not require all the layers described here. For example, C++ code can be integrated into iOS and Objective-C code more painlessly than e.g. creating an Android JNI. On these platforms the top layers can be left unused.
Even when not actually implementing all these layers as separate code, it is important to realize that they might still be conceptually in the code.
The Cross Platform Core
At the heart of our system lies the cross-platform C++ core. The apple of our eye, the IP, the business logic, the raison d’être of this exercise. This is your well written, idiomatic C++ code base. Since it is cross-platform, this code, along with its dependencies, ought to build on all the target platforms using their tool chains. It is recommended that this core is buildable as one or more (static [1]) libraries.
Testing: Use your favorite unit and functional test framework at this level.
The Cross Platform Public C++ Interface (XAPI)
At this layer we expose only the public API of our C++ core.
Here we consider the codebase from the user or client usage perspective as opposed to the architectural design perspective we may have used in the core layer. We should apply good API design principles as usual, thinking about how the API is to-be used, considering things like initialization and shutdown, lifetime management, sessions, configuration, serialization etc.
It is a kind of SDK that can be delivered and built by other teams without the need for access to, or familiarity with, the full codebase, the build tools or any dependent libraries.
This is the opportunity for a compilation firewall (e.g. via the pImpl Idiom). Keep private headers, types and repos private.
We might want to remove certain types from the public API and use various alternatives instead. For example, perhaps our codebase passes and manipulates
std::filesystem::path objects. It is often easier for external users to use
std::string instead (see my “Emscriptened!” post for an exactly this use case).
Another example I came across was a team that did not
know how want to include Boost in their build chain. They asked that any Boost used in the core is contained within the code and does not leak through the API. In fact, we eventually delivered only headers and binary libraries for this particular team.
The Cross Platform C++ Public API layer is possibly a poster child candidate for C++ Modules when they finally land.
Testing: At this level, mock and unit test the API/SDK itself.
Naming Convention: Given a core file
core.cpp, I would often have a corresponding file
core_api.cpp
For smaller projects, or for ones where the core architecture already provides a natural API, you may be able to skip this layer and go directly to the next one.
⚠️ WARNING!
From this point on, it is essential, not to insert any functional or business logic into any subsequent layer since some target platforms might not actually be using them. Introducing functional logic henceforth will cause duplication of effort (DRY-violation) or worse, inconsistent behavior between platforms.
The Cross Platform Public C Interface (XCAPI)
Although some platforms may be able to directly assimilate C++ APIs (e.g. iOS, emscripten-embind (see warning above)) the real truly cross-platform lingua-franca of computing is C. The main reason for this is ABI compatibility (no nasty mangling issues) and a simple, sufficiently well defined, binding/linking model supported practically by anything vaguely resembling a computing platform . This means that even though you can cross some module boundaries with C++ objects (e.g. with COM), doing it with a C API is much simpler (once you have it of course) and much more widely supported.
At this layer, we define a C-style interface to our C++ public API defined in the previous layer. A C-style interface means an
extern "C" interface based on global standalone functions without C++ classes. These functions will use the C++ API inside their
.cpp implementations.
Sometimes, the function based API will pass C++ types as arguments, e.g.
std::string is a common example - in these cases additional conversions would be required later on (at the cost of thickening that layer - more about this in the footnote later on).
This layer should be as thin as possible and only be concerned with the “usual” aspects of wrapping a C++ API in C. Often this would simply be an
extern "C" function calling a C++ function. More complex APIs may need managing of object lifetimes. Some APIs can get away with one global “Singleton” object which is all that is needed for using the API. In other cases, you might need to pass around opaque handles to objects into and out of the C API.
Note that C wrapper friendliness in general and object lifetime management via a C API in particular should be a significant concern to take into account when designing the public C++ interface described in the previous section.
Whether you may or may not use C structs in the API or must limit yourself only to primitive C types will ultimately be determined by the type richness or paucity of the target platforms. For example, you can pass C structs through DLL functions, but Android JNI is less forthcoming in allowing them through. You will have to decide at which layer to make such a decision, e.g. keep the C-struct on all other platforms and only break it up on JNI.
This layer is also the place to resolve overloaded C++ functions by creating separate differently named C functions to call the overloaded C++ function.
Testing: At this level, mock and unit test the C API/SDK itself verifying conversions, overloads and object lifetimes are properly done.
Naming Convention: Given a public API file
core_api.h, the corresponding file would be
core_c_api.cpp
A recent blog post, Generate C interface from C++ source code using Clang libtooling, describes some of the issues involved in generating a C interface from C++ source code, and how an automated tool might do this… automatically.
If and when such a tool is available, it will make the previous C++ API layer even more important as the automated tool will just convert arguments and function calls without any “design” related considerations.
Our layer files might look something like this:
// foo_session_c_api.h extern "C" { bool initFromFileName(std::string const& fileName); bool initFromCount(int count); bool processBuffer(uint8_t* buffer, int size); bool isReady(); }
- Use
extern "C"in header for C linking;
- Break overloads with longer names e.g.
FooSession::init().
// foo_session_c_api.cpp #include <foo_session_api.hpp> // C++ API #include "foo_session_c_api.h" // header for this file Foo::Session the_session; // use a single global "singleton". bool initFromFileName(std::string const& fileName) { return the_session.init(fileName); } bool initFromCount(int count) { return the_session.init(count); } bool processBuffer(uint8_t* buffer, int size) { return the_session.process(gsl::span<uint8_t>(buffer, buffer+size)); } // Use gsl::span<> bool isReady() { return the_session.isReady() }
- For brevity, this example uses a single global session object as the backend of the API.
- Typically, all the functions are simple thin wrappers for method calls.
- Use type helpers like
gsl::span<>or
std::string_viewto lift weaker low-level types to stronger safer types as early as possible [2].
Alas, sometimes it is not practical to create C-style APIs and the next layer may have to work directly with the C++ API. For example, I once had a continuation-based asynchronous C++ core that would return results asynchronously on different threads. This worked fine on iOS, but these multi-threaded responses had to be manually injected into JVM threads (on Android). Adding an additional C-style API in-between was an added complexity (to a complex enough flow). Instead, I had the Android JNI interface use the C++ API directly. The cost of this was that, had I needed to target a third platform, I might have needed to re-implement the threading logic injection on that platform too.
The Platform-Specific Boundary Interface Layer (BIL)
Up until now, everything we wrote was cross-platform C/C++. From this point onward, everything we do is platform-specific. This layer needs to be implemented independently for each target platform..
For many platforms, this layer is the module boundary. The final frontier. Anything that happens beyond it is happening in a different environment, run-time, language and universe. Exceptions are not welcome across this boundary. Unhandled exceptions percolating to this layer, will cause severe havoc, undefined behavior and most likely a program or process crash.
This layer is the final stand for handling any exceptions that have made it thus far. It is also the natural place to insert any logging logic since it is here that we have access to the platform’s logging facilities.
Combined with logging, exceptions can be caught, logged and reported. Furthermore, on some platforms, like the JVM, it is possible to throw a new JVM Java exception with the C++ exception info - simulating passing the exception through the module boundary.
Testing: Unfortunately, I have yet to come by a good general solution for testing code written at this layer. I have a long standing, as-yet unanswered, StackOverflow question about this. Yet another reason to keep this layer as thin as possible.
Naming Convention: Since this is platform specific code, each target platform might have a different name. Given a public C API file
core_c_api.h, the corresponding files might be called
core_c_api_jni.cppor
core_c_api_dll.cppfor Android JNI or Windows DLLs respectively.
Windows/Linux DLL files typically look something like this:
// foo_session_c_api_dll.h extern "C" { bool DLL_EXPORT FooSession_initFromFileName(LPCSTR fileName); bool DLL_EXPORT FooSession_initFromCount(int count); bool DLL_EXPORT FooSession_processBuffer(unsigned char* buffer, int size); bool DLL_EXPORT FooSession_isReady(); }
- Prefix a “namespace”
FooSessionto the function name to avoid export name collisions. We could have done this at the previous level as well - in that case we would have needed different names here to avoid ambiguity.
- The
DLL_EXPORTmacro resolves to the proper platform specific attribute based on build and include configurations, e.g.
__declspec(dllexport)on Windows or
__attribute__((visibility("hidden")))on Linux. I usually have CMake generate this macro for me for all builds.
- Uses e.g. Windows-specific
LPCSTRon Windows to pass strings.
// foo_session_c_api_dll.cpp #include <foo_session_c_api.h> // C API #include "foo_session_c_api_dll.h" // header for this file bool DLL_EXPORT FooSession_initFromFileName(LPCSTR fileName) try { return ::initFromFileName(fileName); } // automatic LPCSTR conversion to std::string catch (...) { return false; } bool DLL_EXPORT FooSession_initFromCount(int count) try { return ::initFromCount(count); } catch (...) { return false; } >bool DLL_EXPORT FooSession_processBuffer(uint8_t* buffer, int size) try { return ::processBuffer(buffer, size); } catch (...) { return false; } bool DLL_EXPORT FooSession_isReady() try { return ::isReady() } catch (...) { return false; }
- Catch and handle all exceptions. I find the function-try-block syntax more concise here.
- Typically, all the functions are simple thin wrappers for C API calls.
On Android we typically have something like this:
// foo_session_c_api_jni.cpp #include <jni.h> // JNI headers #include <android/log.h> // Android loggin facilities #include <foo_session_c_api.h> // C API #include "jni_utils.h" // For JNIByteArrayAdapter and exceptionHandler JNIEXPORT jboolean JNICALL Java_initFromFileName(JNIEnv* env, jobject thiz, jstring fileName) try { return ::initFromFileName(jni_utils::getString(env, fileName)); } // JNI string helper catch(...) { return exceptionHandler(); } JNIEXPORT jboolean JNICALL Java_initFromCount(JNIEnv* env, jobject thiz, jint count) try { return ::initFromCount(count); } catch(...) { return exceptionHandler(); } JNIEXPORT jboolean JNICALL Java_processBuffer(JNIEnv* env, jobject thiz, jbyteArray buffer) try { jni_utils::JNIByteArrayAdapter buffer_span(env, buffer); // JNI helper wrapper return ::processBuffer(buffer_span.ptr(), buffer_span.size()); } catch(...) { return exceptionHandler(); } JNIEXPORT jboolean JNICALL Java_isReady(JNIEnv* env, jobject thiz) try { return ::isReady() } catch(...) { return exceptionHandler(); }
- Function signature, types and names must conform to JNI conventions, e.g. must prefix with
Java_.
- No need for header, the NDK compiler needs only this
.cpp.
- Data cannot always be passed directly to the C API and must be converted via the JVM (and taking care to free resources when done). The
jni_utils::JNIByteArrayAdapterclass is an RAII wrapper over the JVM calls that adapts a JNI array to a C-style array. How it works is beyond the scope of this post. Similarly,
jni_utils::getStringprovides access and RAII facilities for JNI strings.
- For exception handling, my JNI utils also includes
exceptionHandler()which intercepts any caught exceptions, logs them using
__android_log_print()and generates a JVM exception using the
JNIEnv::ThrowNew()API. Again, the details are beyond the scope of this post.
Having reached the final frontier, it is time to boldly go to infinity and beyond.
The Native Import Layer (NIMP)
Every target platform has a different way of importing, loading and consuming our service. At this end of the universe we may be on a different device and hardware, running a different OS and writing a different language altogether.
Once the service is loaded it would typically be available through what is commonly called a “native” interface. Ironically, “native” in this context refers to our C/C++ bare-metal service as opposed to the managed or interpreted code running on a VM such as the CLR, JS or the JVM.
The “native” interface is an exact match to the boundary interface we exposed above. There is not much to say since the syntax and types are completely dictated by the importing target platform.
Testing: You should run Integration Tests for/on the target platform using whatever facilities are available there.
Naming Convention: Since this is platform specific code, each target platform might have a different name. Given
core_c_api_jni.cppthe corresponding Java file might be
core_native.javaor
core_native_dll_wrapper.cs.
For example, our Java JNI interface might look something like this:
// foo_session_native.java // imports ... public class FooSession { static { System.loadLibrary("native_foosession"); } // load the DLL public static native boolean initFromFileName(String fileName); public static native boolean initFromCount(int count); public static native boolean processBuffer(byte[] buffer); public static native boolean isReady(); }
- This is a direct mapping of the JNI function names and type to the Java type system.
- The code for managed C# is almost identical.
For C/C++ DLLs, changing the macro
DLL_EXPORT to e.g.
__declspec(dllimport) (on Windows) at build time, we can use the same header
foo_session_c_api_dll.h as for exporting (assuming we did not
#include any unnecessary, non-deliverable, header into it.
The prototypes and types allowed by the platform’s export/import facilities often create ugly, low-level APIs which are verbose, inconvenient and unnatural to use on the target platform. As responsible library writers, we’d like to facilitate a more natural interaction interface for our users. This is the role of the last layer.
The Native Interface Wrappers (NIW)
Given the low-level interface of the previous layer, it is frequently very effective to wrap it with a higher level interface more suitable for the target environment. This wrapper would simply wrap the
native calls, but provide a more natural and familiar syntax and higher level types for the users. This will allow e.g. the mobile developers to seamlessly work with our code without knowing too much about loading native libraries or native data types.
Testing: If you use such a wrapper, it should be part of the Integration Tests mentioned above.
Naming Convention: This is platform specific code so each target may have a different name. The interface can enrich the existing native class in the same file or done as a standalone API.
Let’s say we have a face detector that returns the 2D position of the center of a face in an image. The native result is returned as an array of two
floats since this is the only way to pass such data through the native interface. We can enrich that to return an Android Java type:
// face_detector_native.java import android.graphics.PointF; // Android point type public class FaceDetector { static { System.loadLibrary("native_facedetector"); } // load the DLL // native import function/method, returns a float array public static native float[] getFaceCenterPoint(); // Java-ized wrapper: return proper 2D point type public static PointF GetFaceCenterPoint() { float[] centerPt = getFaceCenterPoint(); // call native function return new PointF(centerPt[0], centerPt[1]); // return as Android Java type: PointF } }
- The wrapper here is just another non-
nativemethod:
GetFaceCenterPoint()for the same class. Similar wrappers can be made for .NET managed code as well.
Beautiful Symmetry
In the XCAPI and BIL layers, we created C-style wrappers for the C++ API. This entailed going to lower-level code with less expressive syntax and weaker types. At the NIW layer we have the opportunity to undo that and restore order. We wrap the low level code with higher level functions and types. We get a kind of mirror symmetry between our cross-platform code and the platform-specific SDK/API running on the target platform.
Write Once, Run Anywhere… Not!
The Salami Method is quite removed from the ideal of “write once, run anywhere” proclaimed by some languages and platforms. On the other hand, it does allow supporting a very wide variety of platforms while keeping the high-performance profile of C/C++ (in as much as the platform allows).
As Coldplay said: Nobody said it was easy!
But what’s the alternative?
Keep separate code-bases with multiple teams for maintenance?
Spaghetti-code mixing all the above in single monolithic structures?
From my experience, most projects do not implement all these layers as distinct interfaces. Depending on the target platforms and practical considerations, some of these layers might be merged, though it is important to keep in mind that the role of each such layer still holds.
Meta
A first post for the new year! And my longest one yet!
Although this post has been in planning for several years, a colleague prodded me to finally write it.
I hope you enjoy it. Happy New Year 2017 🎉
I’d like to thank @galsh83, @MaximRaskin and @orens for their valuable feedback on this post.
If you found this post helpful, or you have more thoughts or horror stories on this subject, please leave a message in the comments below, on Twitter or Reddit.
Credits: banner :: giphy :: giphy :: giphy :: Starving Donald Duck Scene
Prefer static libs because they can be integrated directly into the DLL further down and enabling delivery of a single DLL file (per platform). ↩
The sharp eyed reader would have noticed that the first function takes an argument of type
std::stringwhich is a C++ type and would certainly not get proper C ABI (and require the user to include
<string>of a potentially different STL implementation. There are several reasons I put it in the example that I wanted to demonstrate: (1) The other C-style abstractions, e.g. lifetime management, overloaded name resolutions etc. are just as important at this point; (2) As mentioned above, we can often do the remaining type conversions at the next layer (3) Some tools like emscripten embind can automatically consume standard C++ types like
std::stringso at this layer there is no gain from making the API even more primitive. ↩ | http://videocortex.io/2017/salami-method/ | CC-MAIN-2020-16 | refinedweb | 3,593 | 55.54 |
Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
3 years, 1 month ago.
How can I get the TCPSocketserver to work?
Hi i can't seem to get a simple socket server to work:
This is my code:
#include "mbed.h" #include "EthernetInterface.h" #define SERVER_PORT 80 EthernetInterface iface; TCPSocket server; Socket *client; int main (void) { iface.connect(); printf("\nServer IP Address is %s\n\r", iface.get_ip_address()); server.open(&iface); server.bind(SERVER_PORT); server.listen(); while (true) { printf("Server bound and listening\n"); while (true) { client = server.accept(); printf("Client connected, stack at 0x%08lX\n", client); char buffer[1024]; int n; //= client->recv(buffer, sizeof(buffer)); printf("Received %u bytes from remote host\n", n); // print received message to terminal // buffer[n] = '\0'; // printf("Received message from Client :'%s'\n",buffer); //client->close(); } } }
The server does accept a connection from the remote host but the pointer to the client is a NULL pointer. I've been pulling my few remaining hears for about a day now ... Can someone please give me some pointers?
Kind regards,
Koen.
1 Answer
3 years, 1 month ago.
Hello Koen,
I hope that the following code will save your hair:
#include "mbed.h" #include "EthernetInterface.h" #include "TCPServer.h" #include "TCPSocket.h" #define SERVER_PORT 80 EthernetInterface iface; TCPServer server; TCPSocket client; SocketAddress clientAddress; int main(void) { iface.connect(); printf("\nServer IP Address is %s\n\r", iface.get_ip_address()); server.open(&iface); server.bind(iface.get_ip_address(), SERVER_PORT); server.listen(5); while (true) { printf("Server bound and listening\n"); while (true) { server.accept(&client, &clientAddress); printf("Connection succeeded!\n\rClient's IP address: %s\n\r", clientAddress.get_ip_address()); char buffer[1024]; int n = client.recv(buffer, sizeof(buffer)); printf("Received %u bytes from remote host\n", n); //print received message to terminal buffer[n] = '\0'; printf("Received message from Client :'%s'\n", buffer); client.close(); } } }
Thanks ! That works, but I get two warning messages from the compiler (mbed online compiler using mbed-os);
Warning: Function "TCPServer::TCPServer()" (declared at line 39 of "/extras/mbed-os.lib/features/netsocket/TCPServer.h") was declared "deprecated" in "TCPSocketServer.cpp", Line: 9, Col: 12 Warning: Function "TCPServer::accept(TCPSocket *, SocketAddress *)" (declared at line 81 of "/extras/mbed-os.lib/features/netsocket/TCPServer.h") was declared "deprecated" in "TCPSocketServer.cpp", Line: 23, Col: 21
Can you point me the correct manual pages ? I found this: obviously wrong article.
Also ... How do you paste the code legible in the forum? The
<<code>> <</code>> tags do not seem to work.
Thanks for your help.posted by 30 Sep 2018
I also have this problem. Did you find a solution?posted by Nikolai Zimfer 10 Nov 2018
If you update the mbed os at least the accept () function works. But last time I checked close() caused a run time error.posted by Koen Kempeneers 10 Nov 2018 | https://os.mbed.com/questions/82557/How-can-I-get-the-TCPSocketserver-to-wor/ | CC-MAIN-2021-49 | refinedweb | 494 | 61.33 |
int p_to_w ( SS_XYZ *pt, int screen_x, int screen_y )
SS_XYZ *pt; // address of 3D point to receive world point
int screen_x; // screen x coordinate
int screen_y; // screen y coordinate
Synopsis
#include "silver.h"
The p_to_w function computes a 3D world coordinate based on the screen coordinates screen_x and screen_y . The world point is copied into the SS_XYZ at pt .
Parameters
pt is the address of a 3D point that is to receive the computed world point. screen_x and screen_y are graphics screen coordinates, such that 0 <= screen_x < spixel_width and 0 <= screen_y < spixel_height .
Return Value
If the screen coordinate is within the bounds of the current window, then p_to_w returns 1, and pt is computed such that it lies on the current window in world space. Otherwise p_to_w returns 0.
While related to the function w_to_p , the two are not inverse functions. Calling p_to_w with the results of w_to_p may not return the original point because w_to_p does not preserve any depth information, and may truncate a value when converting to integer space.
See Also
w_to_p
Help URL: | http://silverscreen.com/p_to_w.htm | CC-MAIN-2021-21 | refinedweb | 176 | 62.17 |
Okay so now you have Tomcat integrated with Eclipse. When you integrate with Eclipse, Eclipse keeps what's known as a "metadata" copy of Tomcat information.
The reason for this is apparent if you were using a remote Tomcat that you didn't have the configuration files on some network share that you could access. Tomcat provides a way to "publish" a web application via an upload. However, for security reasons, you cannot change configuration files like this. So you have to tune the Eclipse copy of the configuration files to match the server configuration before you have an In-Sync copy of the server on the local machine.
Let's head to Eclipse and understand this a little better. On the Server tab right mouse click on your Tomcat server and select Properties.
As you can see from the screenshot, the location is current set to [workspace metadata]. When you start the server from Eclipse, it will use the binary program that we have in "bin/apache-tomcat" but it will use the files located in the Eclipse metadata as the web and configuration repository.
This metadata location is [wherever you have your Eclipse workspace]/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
I store my workspace in ~/src/eclipse-workspace, so my metadata copy of Tomcat is located in ~/src/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Also note one more thing. If you have more than one server in Eclipse, then you'll notice a tmp0, tmp1, tmp2… The servers are numbered in the order in which they appear in Eclipse from top down.
Okay, so basically we could just change our location that we are using, but it is important to keep our copy in-sync in the Eclipse metadata. So we are going to copy the example pages from the Tomcat install that we have in our bin folder to our copy in the metadata storage.
So head over to "bin/apache-tomcat-7.0.33/webapps/", or wherever you've extracted your Tomcat install. There you will see the web applications that come with Tomcat. They are:
- docs — which is really just a bunch of pages of Tomcat documentation bundled up as a web application.
- examples — which are the example servlets and JSPs and the code for those examples. I'll go ahead and state that a lot of the examples are a bit out of date.
- host-manager — I've never really used this web application but I believe that it allows you to control somethings in Tomcat via the web, which is silly, because that's a huge security hole.
- manager — Which I think is a program that allows you to handle the web container side of Tomcat via the web. Again, I've never used it.
- ROOT — This is just a little welcome to Tomcat JSP application. It acts as a hub for linking to all of the other web applications I just listed.
I'm sure you are starting to notice that web applications that you install in Tomcat are basically, stored in a folder and that folder is stored in the "webapps" folder. You would be absolutely correct. When we go to install an application into Tomcat, we simply just put the folder with all our files, images, and java classes into the webapps folder in Tomcat. There a little more to it, like configuring connections to a database, restricting access to authenticated users and what-not, but that's the gist of very basic web applications.
So, basically what we are going to do, is copy the ROOT and examples web applications from the Tomcat folder and paste the folders into our metadata copy.
- Copy the ROOT and examples folder from the ~/bin/apache-tomcat-7.0.33/webapps/ folder.
- Paste the folders in the ~/src/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps folder.
If you get a prompt to "merge" thing just go ahead and click "OK".
Now hope back into Eclipse, start up your server from Eclipse, open browser to and poof! You should now see the Tomcat welcome page as oppose to the 404 error you got last time.
Making your first servlet...
And now it is time to make your very own servlet! I know exciting! Here's the basic breakdown.
Tomcat is expecting your Java class files to have certain hooks that it can latch onto, in order to run your Java code. It use to be that your class would have to extend a standard base class and then you'd create an XML file that the server would read which would help it to figure out how to latch onto your class file. It was all a very crazy mixture of XML files and Interfaces. The nice thing about Java servlet version 3.0 is, you don't have to do that any more! Hooray!! There are these things now called Java annotations that you can add to your class file. Annotations don't do anything code wise, but they allow you to mark certain sections of your code as something, sort of like HTML markup. Basically, you can now annotate you Java class, and Tomcat will read the annotations to figure out how to hook into your Java class.
Easy stuff! You can still do it the old way. In fact, if you do provide an XML file, it will override whatever annotations are found. The old way is still very useful for commercial products that just give you compiled class files and allow you to fine tune the program for your needs by editing XML files. You obviously can't change the annotations in a compiled class file.
So our very first servlet is basically going to write to the screen, the current time and "Hello, world!". To begin, let's click on the "New Project" button on the toolbar. Here's a picture of the button.
Go ahead and click Finish as you won't need any of the other steps from the wizard.
You will now see your new project in the "Project Explorer".
A servlet is a Java resource so we will right mouse click on "Java Resources" and choose New → Class and get the "New Java Class Wizard". We just want to create a very basic class, so just fill out the dialog as follows:
Now let's add some code to get to handle all the needed things for being a servlet, because at the moment our Tomcat server would have no idea what to do with this class. Begin by placing the cursor just above the class statement (public class…) and type
@WebServlet("/Hello")
Eclipse will underline this statement with a red wavy underline. That means there is a problem with the code. move you cursor so that it is somewhere within the offending code and a "quick fix" tool tip will appear. Click on the quick fix to "import javax.servlet.annotation.WebServlet". This will add the import statement to your class file.
Now we are going to say our class extends the basic HttpServlet class. We need to extend this class as it brings in all the needed hooks into our class that Tomcat is expecting. To extend our class we just need to add a bit of code.
So basically you are just adding "extends HttpServlet" to the end of the class statement. Eclipse will yet again, underline the new code. Click on the code and in the quick fix, import the javax.servlet.http.HttpServlet class.
You should now see a little light bulb with a warning exclamation sign on it.
That means Eclipse wants to help you out on something. Usually, these things won't keep your code from working but it's good form to address something here. In this case, HttpServlet is marked Serializable, and thus your class should provide a Version UID. It's a good idea to go ahead and do this. I usually just go for the default value as opposed to a randomly generated one. Click on the light bulb and make your choice.
The default UID looks like this:
private static final long serialVersionUID = 1L;
Okay now, all of the underlines and light bulbs have been dismissed. We now have all the hooks that we need for Tomcat to interact with with our class, but at the moment, absolutely nothing will happen. So let's make something happen!
First things, first. Let's create a no argument constructor. It's important that we at the very least have this going forward. To do this in the outline pane on the right, right mouse click the class (that's the green ball C).
Once you right click select Source → Generate Constructors From Superclass... You don't really need to mess with the dialog that pops up, just click OK. Now you have your no argument constructor. Next we need to override the "doGet" method from HttpServlet.
The reason we will be over riding this method is that when the web server receives a HTTP GET request from a client, the web container will call this method. By default the method does nothing, in fact, by default all of the methods do nothing. You are going to over ride this method with your own custom method.
To over ride the method, again, right mouse click on the class in the Outline pane and select Source → Override / Implement Methods... A dialog will appear and you should select the "doGet" method by checking the box beside it. You can also do some automatic generation of the comments for this over ride by checking the box to do so toward the bottom of the dialog. I usually don't however as I like my own comments on code.
You'll see that in the code editor pane the new code has been added. Go ahead and remove the code that says:
super.doGet(req, resp);
That removes any reference to the default code of "do nothing". Now, you are ready to implement your own response. Take a look at my code below and I'll explain what I did right after. SayHelloServlet extends HttpServlet { public SayHelloServlet() { super(); // TODO Auto-generated constructor stub } private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub java.util.Date d = new java.util.Date(); java.io.PrintWriter pw = resp.getWriter(); resp.setContentType("text/html"); pw.println("<html><head><title>Sample 01</title></head><body>"); pw.println("<h1>" + d.toString() + "</h1>"); pw.println("Hello, World!"); pw.println("</body></html>"); } }
You can always remove all of those TODO comments out of the code. As you can see. I create a new java.util.Date called d. That stores our date. Next I created a PrintWriter called pw. This will provide us a way to write to the response that will be sent back to the client.
I then start writing HTML to the print writer and I convert the date to a string so that it can be written to the print writer.
So that's about it, now let's go ahead and run this servlet and see what happens! To run the program that we've just created, in the project explorer (remember the pane on the left), right mouse click on the top level object of our project (looks like a blue folder called helloone) and choose Run As → Run on Server option.
A run dialog will appear but you can just click on the Finish button.
And... WAIT! You got a 404 error!? Of course you did. If you look back at our code notice the @WebServlet("/Hello") part. The part in quotes is what you need to add to the URL to get the results. So the correct location should be…
The helloone is the name of the web application and Hello is the name of the servlet inside the web application.
Now you've had a taste of your first web servlet. I know most likely you are thinking that this has got to be a pain to code in if I have to encode a whole web page into Java code. However, servlets aren't exactly made for serving up pages as it is more along the lines of doing the leg work in web applications.
I will try to make it clearer as to the purpose of servlets, but for now, you've had the ability to sink your teeth into it a little bit. I'll try not to make the post this crazy long again, but I did cover a lot of fundamentals here.
Cheers!
Cheers! | http://ramenboy.blogspot.com/2012/11/getting-examples-and-your-first-tomcat.html | CC-MAIN-2018-13 | refinedweb | 2,123 | 72.46 |
high specificity spread all throughout your stylesheet. However, there are a few problems I have with the syntax that can cause issues in production as well as cause confusion for developers. I prefer to use a slightly tweaked version of the syntax instead. I call it ABEM (Atomic Block Element Modifier):
[a/m/o]-blockName__elementName -modifierName
An Atomic Design Prefix
The a/m/o is an Atomic Design prefix. Not to be confused with Atomic CSS which is a completely different thing. Atomic design is a methodology for organizing your components that maximizes the ability to reuse code. It splits your components into three folders: atoms, molecules, and organisms. Atoms are super simple components that generally consist of just a single element (e.g. a button component). Molecules are small groups of elements and/or components (e.g. a single form field showing a label and an input field). Organisms are large complex components made up of many molecule and atom components (e.g. a full registration form).
The difficulty of using atomic design with classic BEM is that there is no indicator saying what type of component a block is. This can make it difficult to know where the code for that component is since you may have to search in 3 separate folders in order to find it. Adding the atomic prefix to the start makes it immediately obvious what folder the component is stored in.
camelCase
It allows for custom grouping
Classic BEM separates each individual word within a section with a single dash. Notice that the atomic prefix in the example above is also separated from the rest of the class name by a dash. Take a look at what happens now when you add an atomic prefix to BEM classic vs camelCase:
/* classic + atomic prefix */ .o-subscribe-form__field-item {} /* camelCase + atomic prefix */ .o-subscribeForm__fieldItem {}
At a glance, the component name when reading the classic method looks like it's called "o subscribe form". The significance of the "o" is completely lost. When you apply the "o-" to the camelCase version though, it is clear that it was intentionally written to be a separate piece of information to the component name.
Now you could apply the atomic prefix to classic BEM by capitalizing the "o" like this:
/* classic + capitalized atomic prefix */ .O-subscribe-form__field-item {}
That would solve the issue of the "o" getting lost amongst the rest of the class name however it doesn't solve the core underlying issue in the classic BEM syntax. By separating the words with dashes, the dash character is no longer available for you to use as a grouping mechanism. By using camelCase, it frees you up to use the dash character for additional grouping, even if that grouping is just adding a number to the end of a class name.
Your mind will process the groupings faster
camelCase also has the added benefit of making the grouping of the class names easier to mentally process. With camelCase, every gap you see in the class name represents a grouping of some sort. In classic BEM, every gap could be either a grouping or a space between two words in the same group.
Take a look at this silhouette of a classic BEM class (plus atomic prefix) and try to figure out where the prefix, block, element and modifier sections start and end:
Ok, now try this one. It is the exact same class as the one above except this time it is using camelCase to separate each word instead of dashes:
That was much easier wasn't it? Those silhouettes are essentially what your mind sees when it is scanning through your code. Having all those extra dashes in the class name make the groupings far less clear. As you read through your code, your brain tries to process whether the gaps it encounters are new groupings or just new words. This lack of clarity causes cognitive load to weigh on your mind as you work.
classic BEM + atomic prefix
camelCase BEM + atomic prefix
Use multi class selectors (responsibly)
One of the golden rules in BEM is that every selector is only supposed to contain a single class. The idea is that it keeps CSS maintainable by keeping the specificity of selectors low and manageable. On the one hand, I agree that low specificity is preferable over having specificity run rampant. On the other, I strongly disagree that a strict one class per selector rule is the best thing for projects. Using some multi-class selectors in your styles can actually improve maintainability rather than diminish it.
"But it leads to higher specificity! Don't you know that specificity is inherently evil?!?"
Specificity != bad.
Uncontrolled specificity that has run wild = bad.
Having some higher specificity declarations doesn't instantly mean that your CSS is more difficult to maintain. If used in the right way, giving certain rules higher specificity can actually make CSS easier to maintain. The key to writing maintainable CSS with uneven specificity is to add specificity purposefully and not just because a list item happens to be inside a list element.
Besides, don't we actually want our modifier styles to have greater power over elements than default styles? Bending over backwards to keep modifier styles at the same specificity level as normal styles seems silly to me. When do you actually want your regular default styles to override your specifically designated modifier styles?
Separating the modifier leads to cleaner HTML
This is the biggest change to the syntax that ABEM introduces. Instead of connecting the modifier to the element class, you apply it as a separate class.
One of the things that practically everyone complains about when they first start learning BEM is how ugly it is. It is especially bad when it comes to modifiers. Take a look at this atrocity. It only has three modifiers applied to it and yet it looks like a train wreck:
B__E--M:
<button class="block-name__element-name block-name__element-name--small block-name__element-name--green block-name__element-name--active"> Submit </button>
Look at all that repetition! That repetition makes it pretty difficult to read what it's actually trying to do. Now take a look at this ABEM example that has all the same modifiers as the previous example:
A-B__E -M:
<button class="a-blockName__elementName -small -green -active"> Submit </button>
Much cleaner isn't it? It is far easier to see what those modifier classes are trying to say without all that repetitive gunk getting in the way.
When inspecting an element with browser DevTools, you still see the full rule in the styling panel so it retains the connection to the original component in that way:
.a-blockName__elementName.-green { background: green; color: white; }
It's not much different to the BEM equivalent
.block-name__element-name--green { background: green; color: white; }
Managing state becomes easy
One large advantage that ABEM has over classic BEM is that it becomes immensely easier to manage the state of a component. Let's use a basic accordion as an example. When a section of this accordion is open, let's say that we want to apply these changes to the styling:
- Change the background colour of the section heading
- Display the content area
- Make a down arrow point up
We are going to stick to the classic B__E--M syntax for this example and strictly adhere to the one class per css selector rule. This is what we end up with (note, that for the sake of brevity, this accordion is not accessible):
See the Pen Accordion 1 - Pure BEM by Daniel Tonon (@daniel-tonon) on CodePen.
The SCSS looks pretty clean but take a look at all the extra classes that we have to add to the HTML for just a single change in state!
HTML while a segment is closed using BEM:
<div class="revealer accordion__section"> <div class="revealer__trigger"> <h2 class="revealer__heading">Three</h2> <div class="revealer__icon"></div> </div> <div class="revealer__content"> Lorem ipsum dolor sit amet... </div> </div>
HTML while a segment is open using BEM:
<div class="revealer accordion__section"> <div class="revealer__trigger revealer__trigger--open"> <h2 class="revealer__heading">One</h2> <div class="revealer__icon revealer__icon--open"></div> </div> <div class="revealer__content revealer__content--open"> Lorem ipsum dolor sit amet... </div> </div>
Now let's take a look at what happens when we switch over to using this fancy new A-B__E -M method:
See the Pen Accordion 2 - ABEM alternative by Daniel Tonon (@daniel-tonon) on CodePen.
A single class now controls the state-specific styling for the entire component now instead of having to apply a separate class to each element individually.
HTML while a segment is open using ABEM:
<div class="m-revealer o-accordion__section -open"> <div class="m-revealer__trigger"> <h2 class="m-revealer__heading">One</h2> <div class="m-revealer__icon"></div> </div> <div class="m-revealer__content"> Lorem ipsum dolor sit amet... </div> </div>
Also, take a look at how much simpler the javascript has become. I wrote the JavaScript as cleanly as I could and this was the result:
JavaScript when using pure BEM:); })
JavaScript when using ABEM:
class revealer { constructor(el){ Object.assign(this, { $wrapper: el, isOpen: false, }); this.$trigger = this.$wrapper.querySelector('.m-revealer__trigger'); this.$trigger.onclick = ()=> this.toggle(); } toggle(){ if (this.isOpen) { this.close(); } else { this.open(); } } open(){ this.$wrapper.classList.add(`-open`); this.isOpen = true; } close(){ this.$wrapper.classList.remove(`-open`); this.isOpen = false; } } document.querySelectorAll('.m-revealer').forEach(el => { new revealer(el); })
This was just a very simple accordion example. Think about what happens when you extrapolate this out to something like a sticky header that changes when sticky. A sticky header might need to tell 5 different components when the header is sticky. Then in each of those 5 components, 5 elements might need to react to that header being sticky. That's 25
element.classList.add("[componentName]__[elementName]--sticky") rules we would need to write in our js to strictly adhere to the BEM naming convention. What makes more sense? 25 unique classes that are added to every element that is affected, or just one
-sticky class added to the header that all 5 elements in all 5 components are able to access and read easily?
The BEM "solution" is completely impractical. Applying modifier styling to large complex components ends up turning into a bit of a grey area. A grey area that causes confusion for any developers trying to strictly adhere to the BEM naming convention as closely as possible.
ABEM modifier issues
Separating the modifier isn't without its flaws. However, there are some simple ways to work around those flaws.
Issue 1: Nesting
So we have our accordion and it's all working perfectly. Later down the line, the client wants to nest a second accordion inside the first one. So you go ahead and do that... this happens:
See the Pen Accordion 3 - ABEM nesting bug by Daniel Tonon (@daniel-tonon) on CodePen.
Nesting a second accordion inside the first one causes a rather problematic bug. Opening the parent accordion also applies the open state styling to all of the child accordions in that segment.
This is something that you obviously don't want to happen. There is a good way to avoid this though.
To explain it, let's play a little game. Assuming that both of these CSS rules are active on the same element, what color do you think that element's background would be?
.-green > * > * > * > * > * > .element { background: green; } .element.-blue { background: blue; }
If you said green due to the first rule having a higher specificity than the second rule, you would actually be wrong. Its background would be blue.
Fun fact:
* is the lowest specificity selector in CSS. It basically means "anything" in CSS. It actually has no specificy, meaning it doesn't add any specificity to a selector you add it to. That means that even if you used a rule that consisted of a single class and 5 stars (
.element > * > * > * > * > *) it could still be easily overwritten by just a single class on the next line of CSS!
We can take advantage of this little CSS quirk to create a more targeted approach to the accordion SCSS code. This will allow us to safely nest our accordions.
See the Pen Accordion 4 - ABEM nesting bug fix by Daniel Tonon (@daniel-tonon) on CodePen.
By using the
.-modifierName > * > & pattern, you can target direct descendants that are multiple levels deep without causing your specificity to get out of control.
I only use this direct targeting technique as it becomes necessary though. By default, when I'm writing ABEM, I'll write it how I did in that original ABEM accordion example. The non-targeted method is generally all that is needed in most cases. The problem with the targeted approach is that adding a single wrapper around something can potentially break the whole system. The non-targeted approach doesn't suffer from this problem. It is much more lenient and prevents the styles from breaking if you ever need to alter the HTML later down the line.
Issue 2: Naming collisions
An issue that you can run into using the non-targeted modifier technique is naming collisions. Let's say that you need to create a set of tabs and each tab has an accordion in it. While writing this code, you have made both the accordion and the tabs respond to the
-active class. This leads to a name collision. All accordions in the active tab will have their active styles applied. This is because all of the accordions are children of the tab container elements. It is the tab container elements that have the actual
-active class applied to them. (Neither the tabs nor the accordion in the following example are accessible for the sake of brevity.)
See the Pen Accordion in tabs 1 - broken by Daniel Tonon (@daniel-tonon) on CodePen.
Now one way to resolve this conflict would be to simply change the accordion to respond to an
-open class instead of an
-active class. I would actually recommend that approach. For the sake of an example though, let's say that isn't an option. You could use the direct targeting technique mentioned above, but that makes your styles very brittle. Instead what you can do is add the component name to the front of the modifier like this:
.o-componentName { &__elementName { .-componentName--modifierName & { /* modifier styles go here */ } } }
The dash at the front of the name still signifies that it is a modifier class. The component name prevents namespace collisions with other components that should not be getting affected. The double dash is mainly just a nod to the classic BEM modifier syntax to double reinforce that it is a modifier class.
Here is the accordion and tabs example again but this time with the namespace fix applied:
See the Pen Accordion in tabs 2 - fixed by Daniel Tonon (@daniel-tonon) on CodePen.
I recommend not using this technique by default though mainly for the sake of keeping the HTML clean and also to prevent confusion when multiple components need to share the same modifier.
The majority of the time, a modifier class is being used to signify a change in state like in the accordion example above. When an element changes state, all child elements, no matter what component they belong to, should be able to read that state change and respond to it easily. When a modifier class is intended to affect multiple components at once, confusion can arise around what component that modifier specifically belongs to. In those cases, name-spacing the modifier does more harm than good.
ABEM modifier technique summary
So to make the best use of the ABEM modifier, use
.-modifierName & or
&.-modifierName syntax by default (depends on what element has the class on it)
.o-componentName { &.-modifierName { /* componentName modifier styles go here */ } &__elementName { .-modifierName & { /* elementName modifier styles go here */ } } }
Use direct targeting if nesting a component inside itself is causing an issue.
.o-componentName { &__elementName { .-nestedModifierName > * > & { /* modifier styles go here */ } } }
Use the component name in the modifier if you run into shared modifier name collisions. Only do this if you can't think of a different modifier name that still makes sense.
.o-componentName { &__elementName { .-componentName--sharedModifierName & { /* modifier styles go here */ } } }
Context sensitive styles
Another issue with strictly adhering to the BEM one class per selector methodology is that it doesn't allow you to write context sensitive styles.
Context sensitive styles are basically "if this element is inside this parent, apply these styles to it".
With context sensitive styles, there is a parent component and a child component. The parent component should be the one that applies layout related styles such as margin and position to the child component (
.parent .child { margin: 20px }). The child component should always by default not have any margin around the outside of the component. This allows the child components to be used in more contexts since it is the parent in charge of it's own layout rather than its children.
Just like with real parenting, the parents are the ones who should be in charge. You shouldn't let their naughty clueless children call the shots when it comes to the parents layout.
To dig further into this concept, let's pretend that we are building a fresh new website and right now we are building the subscribe form component for the site.
See the Pen Context sensitive 1 - IE unfriendly by Daniel Tonon (@daniel-tonon) on CodePen.
This is the first time we have had to put a form on this awesome new site that we are building. We want to be like all the cool kids so we used CSS grid to do the layout. We're smart though. We know that the button styling is going to be used in a lot more places throughout the site. To prepare for this, we separate the subscribe button styles into its own separate component like good little developers.
A while later we start cross-browser testing. We open up IE11 only to see this ugly thing staring us in the face:
IE11 does kind of support CSS grid but it doesn't support
grid-gap or auto placement. After some cathartic swearing and wishing people would update their browsers, you adjust the styles to look more like this:
See the Pen Context sensitive 2 - what not to do by Daniel Tonon (@daniel-tonon) on CodePen.
Now it looks perfect in IE. All is right with the world. What could possibly go wrong?
A couple of hours later you are putting this button component into a different component on the site. This other component also uses css-grid to layout its children.
You write the following code:
See the Pen Context sensitive 3 - the other component by Daniel Tonon (@daniel-tonon) on CodePen.
You expect to see a layout that looks like this even in IE11:
But instead, because of the grid-column: 3; code you wrote earlier, it ends up looking like this:
Yikes! So what do we do about this
grid-column: 3; CSS we wrote earlier? We need to restrict it to the parent component but how should we go about doing that?
Well the classic BEM method of dealing with this is to add a new parent component element class to the button like this:
See the Pen Context sensitive 4 - classic BEM solution by Daniel Tonon (@daniel-tonon) on CodePen.
On the surface this solution looks pretty good:
- It keeps specificity low
- The parent component is controlling its own layout
- The styling isn't likely to bleed into other components we don't want it to bleed into
Everything is awesome and all is right with the world… right?
The downside of this approach is mainly due to the fact that we had to add an extra class to the button component. Since the
subscribe-form__submit class doesn't exist in the base
button component, it means that we need to add extra logic to whatever we are using as our templating engine for it to receive the correct styles.
I love using Pug to generate my page templates. I'll show you what I mean using Pug mixins as an example.
First, here is the original IE unfriendly code re-written in mixin format:
See the Pen Context sensitive 5 - IE unfriendly with mixins by Daniel Tonon (@daniel-tonon) on CodePen.
Now lets add that IE 11
subscribe-form__submit class to it:
See the Pen Context sensitive 6 - IE safe BEM solution with mixins by Daniel Tonon (@daniel-tonon) on CodePen.
That wasn't so hard, so what am I complaining about? Well now let's say that we sometimes want this module to be placed inside a sidebar. When it is, we want the email input and the button to be stacked on top of one another. Remember that in order to strictly adhere to BEM, we are not allowed to use anything higher in specificity than a single class in our styles.
See the Pen Context sensitive 7 - IE safe BEM with mixins in sidebar by Daniel Tonon (@daniel-tonon) on CodePen.
That Pug code isn't looking so easy now is it? There are a few things contributing to this mess.
- Container queries would make this far less of a problem but they don't exist yet natively in any browser
- The problems around the BEM modifier syntax are rearing their ugly heads.
Now lets try doing it again but this time using context sensitive styles:
See the Pen Context sensitive 8 - IE safe Context Sensitive with mixins in sidebar by Daniel Tonon (@daniel-tonon) on CodePen.
Look at how much simpler the Pug markup has become. There is no "if this then that" logic to worry about in the pug markup. All of that parental logic is passed off to the css which is much better at understanding what elements are parents of other elements anyway.
You may have noticed that I used a selector that was three classes deep in that last example. It was used to apply 100% width to the button. Yes a three class selector is ok if you can justify it.
I didn't want 100% width to be applied to the button every time it was:
- used at all anywhere
- placed inside the subscribe form
- placed inside the side-bar
I only wanted 100% width to be applied when it was both inside the subscribe form and inside the sidebar. The best way to handle that was with a three class selector.
Ok, in reality, I would more likely use an ABEM style
-verticalStack modifier class on the
subscribe-form element to apply the vertical stack styles or maybe even do it through element queries using EQCSS. This would mean that I could apply the vertical stack styles in more situations than just when it's in the sidebar. For the sake of an example though, I've done it as context sensitive styles.
Now that we understand context sensitive styles, let's go back to that original example I had and use some context sensitive styles to apply that troublesome
grid-column: 3 rule:
See the Pen Context sensitive 9 - context sensitive method with mixins by Daniel Tonon (@daniel-tonon) on CodePen.
Context sensitive styles lead to simpler HTML and templating logic whilst still retaining the reusability of child components. BEM's one class per selector philosophy doesn't allow for this to happen though.
Since context sensitive styles are primarily concerned with layout, depending on circumstances, you should generally use them whenever you are dealing with these CSS properties:
- Anything CSS grid related that is applied to the child element (
grid-column,
grid-rowetc.)
- Anything flexbox related that is applied to the child element (
flex-grow,
flex-shrink,
align-selfetc.)
marginvalues greater than 0
positionvalues other than
relative(along with the
top,
left,
bottom, and
rightproperties)
transformif it is used for positioning like
translateY
You may also want to place these properties into context-sensitive styles but they aren't as often needed in a context sensitive way.
width
height
padding
border
To be absolutely clear though, context sensitive styles are not nesting for the sake of nesting. You need to think of them as if you were writing an
if statement in JavaScript.
So for a CSS rule like this:
.parent .element { /* context sensitive styles */ }
You should think of it like you are writing this sort of logic:
if (.element in .parent) { .element { /* context sensitive styles */ } }
Also understand that writing a rule that is three levels deep like this:
.grandparent .parent .element { /* context sensitive styles */ }
Should be thought of like you are writing logic like this:
if ( (.element in .parent) && (.element in .grandparent) && (.parent in .grandparent) ) { .element { /* context sensitive styles */ } }
So by all means, write a css selector that is three levels deep if you really think you need that level of specificity. Please understand the underlying logic of the css that you are writing though. Only use a level of specificity that makes sense for the particular styling that you are trying to achieve.
And again, one more time, just to be super clear, do not nest for the sake of nesting!
Summing Up
The methodology behind the BEM naming convention is something that I wholeheartedly endorse. It allows css to be broken down into small easily manageable components rather than leaving css in an unwieldy mess of high specificity that is difficult to maintain. The official syntax for BEM has a lot to be desired though.
The official BEM syntax:
- Doesn't support Atomic Design
- Is unable to be extended easily
- Takes longer for your mind to process the grouping of the class names
- Is horribly incompetent when it comes to managing state on large components
- Tries to encourage you to use single class selectors when double class selectors lead to easier maintainability
- Tries to name-space everything even when namespacing causes more problems than it solves.
- Makes HTML extremly bloated when done properly
My unofficial ABEM approach:
- Makes working with Atomic Design easier
- Frees up the dash character as an extra method that can be used for grouping
- Allows your mind to process the grouping of the class names faster
- Is excellent at handling state on any sized component no matter how many sub components it has
- Encourages controlled specificity rather than just outright low specificity to mitigate team confusion and improve site maintainability
- Avoids namespacing when it isn't needed
- Keeps HTML quite clean with minimal extra classes applied to modules while still retaining all of BEM's advantages
Disclaimer
I didn't invent the
-modifier (single dash before the modifier name) idea. I discovered it in 2016 from reading an article. I can't remember who originally conceptualised the idea. I'm happy to credit them if anyone knows the article though.
Update: 21st of January 2018 (comments response)
No one was able to link to the exact article where I learnt about the
-modifier syntax. What I can say is that I learnt it from reading an article about BEVM (block__element--variation -modifier).
Here are some other people that came up with the
-modifier syntax before me:
BEVM can still work with ABEM if you like that methodology (making it ABEVM). After using the
-modifier syntax for a while though I eventually stopped using the
&--modifier syntax altogether. I couldn't really see any benefit in keeping the double dash around when the single dash was easier to use in my CSS and was making my HTML much cleaner.
There were a few people who referenced BEMIT as being quite similar. They're right, it does share some similarities with BEMIT but it also has some differences.
You could merge ABEM and BEMIT together to an extent. I had people mention that they prefer the explicit "is" of the state based classes in BEMIT (eg.
.is-active). That is perfectly fine, if you want to add the "is" to ABEM I would recommend writing the modifier like this
.-is-modifierName. See what I mean by camelCase allowing for custom grouping?
The utilities can be carried across from BEMIT as well pretty easily, it would still be written as
.u-utilityName. The "utilities" folder/file should maybe be placed in the same directory as the atoms, molecules and organisms folders. I think that might make it easier to find. The "object" and "component" name spaces in BEMIT wouldn't carry across. They would be replaced with the Atomic Design name spaces in ABEM.
An interesting discussion in the comments was about using the
@extend functionality in Sass. For example using
<button class='subscribe-form__submit'></button> and
.subscribe-form__submit { @extend .button; grid-column: 3; }. I think context sensitive styles are the better way to go. I pretty strongly disagreed with that implementation of
@extend unless the CMS is forcing you down that path. You can see the full comment and my response here:.
A thing many people had issue with was that I didn't go into much depth around what Atomic Design is and how to use it. It was out of scope for this article. If I tried to go in depth on how to categorise components using Atomic Design principles, then it would have easily doubled the length of the article (and this article is already very long as it is). I gave enough of a summary to introduce the concept of Atomic Design and I linked to a resource that goes much more in depth on the topic. That was about as much attention as I wanted to give to explaining Atomic Design.
Since Atomic Design categorisation is such a confusing subject, I have plans to write an article that will be all about how to go about categorising Atomic Design components. I will attempt to create a set of clear guidelines to follow to help figure out what Atomic Design category a particular component belongs to. Don't expect it any time soon though. It's going to be a while before it gets published. | https://css-tricks.com/abem-useful-adaptation-bem/ | CC-MAIN-2019-04 | refinedweb | 5,031 | 61.26 |
,
JSP-related discussion should be kept here.
EJB-related discussion should be kept here.
Struts-related discussion should be kept here.
Hibernate-related thread
Compilation/deployment-related discussion should be kept here.
Hibernate-related discussion should be kept here.
J2EE servers integration-related discussion should be kept here.
Other frameworks-related discussion should be kept here.
Webservices-related discussion should be kept here.
Erroneous post, please ignore.
HTML authoring-related discussion should be kept here.
Other topics discussion should be kept here.
.... is nice, for certain JSPs and ways to write them, but it makes writing JSPs that can't
be reformatted for whatever reason a pain. I believe "correctly" reformatting JSPs - other
than most Java code - is inherently impossible, thus there should be a way to edit JSPs
without the formatter's "smartness" on how to indent lines and where to put the caret.
For an example why reformatting a manually formatted JSP file is impossible, please see
this:
Sascha
XML/JSP: Provide tag-coloring depending on namespace
All I want is a richer, fully documented, easier to use OpenAPI. One that allows me to build a framework-specific runtime model for the current project, and validate all involved elements -- some sort of "compiler" that knows what the java compiler would let pass, but that would cause an error/problem at runtime. Of course, this isn't limited to java files at all; in fact, most of the runtime model would be built from framework-specific XML files.
In other words, I need to:
- Validate java classes in a framework-specific manner. currently possible with a LocalInspectionTool.
- Validate xml files in a framework-specific manner. currently possible with a LocalInspectionTool.
- Provide custom code completion for java and xml files. currently not possible, AFAIK.
- Provide custom navigation between classes/xml files/etc. currently not currently possible, AFAIK.
- Add more actions to some refactorings. For example, when renaming a Tapestry page class, all references to the class should be renamed too -- and what constitutes references to this class, and how to rename them, should be determined by the plugin. currently not possible, AFAIK
I'm sure I could think of plenty of other things once me or someone else start developing a complex plugin to integrate something like Tapestry or Spring.
WebLogic Integration & CMP Ejb problem
We're using a web UI toolkit called Bindows.
It is a very rich OO toolkit that allows developing a pure browser
application (no plug-ins needed) that is as rich as desktop apps with a
much simpler and ordered development model of OO controls and event
driven flow (as opposed to page based).
Our application is a classic client-server application with a Bindows
UI, XML-RPC API (for which there is full support in Bindows as well as
SOAP) and on the server Jetty with Apache XML-RPC.
Since Bindows is a JavaScript toolkit, Revamped JavaScript support would
be very useful, with inter-file and OO awareness, as right now I can't
refactor class names, class function names, etc.
The next step would be a UI builder, but I acknowledge it may be too
specialized.
Amnon
We use Jetty as our servlet container (small, simple, fast).
It seems I can't easily integrate with it as a J2EE server so we just
run it as a normal Java app.
Any plans to more easily integrate with it?
Amnon
Hello Mike,
MA> Webservices-related discussion should be kept here.
Good question. The answer is yes please :)
I think there was a discussion a while back about having even basic web service
generation. In other words integrate, intelligently like idea usually does,
wsdl2java and java2wsdl in a way that would help me create the services quickly
and generate a package for my users which I can deploy to my site so people
can start generating the stubs off of my wsdl and doing their work.
I am not exactly sure how to go about this, since I usually do this manually,
but I know NetBeans has a way to do it, and so does Sun Studio Creator.
I think NetBeans' way of doing it seems easy, but I'm not in Netbeans long
enough to really judge it.
R
I can't say this enough times: I am getting really sick and tired of having
to switch app servers for every run config. If I have a run config right
now, to create a new one, I need to also change the module's default app
server. That needs to be redesigned. I should be able to pick an app server
run config and just run my module with it. Plain and simple. I shouldn't
have to go editing anything else and remembering the different places where
this might make a difference, and when I switch from Tomcat to JBoss or Resin,
then I also lose the jboss config files, which I have to resetup all over
again once I change to another app server. That's really really really really
annoying.
R
I have not developed any EJB's, but I have worked on a couple of
projects and have set-up IJ to build .ear files for three projects. IJ
is actually the most flexible of the editors we have here (IJ, JBuilder,
Eclipse and maybe NetBeans). However, there is some room for
improvement. The modules could be a little smarter. If I have a web
module, it's most likely going to be dependent on the EJB module. If I
create a web module and there is an EJB module, it should prompt me.
The same goes for if I create an EJB module and I already have a web module.
EJB 3 support is a must. We are going to deploy JBoss 4.03 as soon as we
can get it tested.
Also, when editing the code, it should make some assumptions. If I am
using an object of type abc and there is an abcEntity (or whatever the
naming convention is), it should give me a way to navigate directly to
the object instead of taking me to the I/F when I CTRL-click it. That
would be sweet.
Mike Aizatsky (JetBrains) wrote:
Struts is the most widely used web framework. Look at the Struts
plugin. It does almost everything that needs to be done. Some cool
stuff would be intentions on form objects. If I create a path (abc.do)
and it does not exist, prompt me to map a new Struts action.
Mike Aizatsky (JetBrains) wrote:
I would love an awesome interface in IntelliJ for working with Spring
projects.
so +5 for that
"Robert Sfeir" <nomail@jetbrains.com> wrote in message
news:7c2dbfd120d518c7994124d4c260@news.jetbrains.com...
>
>
>
>
>
The EJB deployment view really needs to look exactly like the file that
will be build, including manifest files, etc. The hardest thing about
EJB development is configuring it correctly. Right now, we have to
build the .ear, then open it and see if everything is where is should
be. Rebuild, re-open. It takes forever. It would be really nice if I
could change a configuration, then switch to deployment view and see the
difference that it made. Currently only the war has a good deployment
view, but it never gets the manifest when in an .ear.
Mike Aizatsky (JetBrains) wrote:
Norris Shelton wrote:
>
>> Compilation/deployment-related discussion should be kept here.
+1, but OpenAPI first must be extended in some ways:
some of them overlap ;)
None of our apps have the style sheet declared in the individual JSPs.
It's usually declared in a single wrapper page. Make the style sheet
property look-up work like the .properties lookup.
Mike Aizatsky (JetBrains) wrote: | https://intellij-support.jetbrains.com/hc/en-us/community/posts/206912495-Feedback-on-enterprise-application-development-is-needed-?page=1 | CC-MAIN-2020-40 | refinedweb | 1,286 | 64.71 |
Errata for Domain-Driven Design Using Naked Objects
The latest version of the book is P1.0, released almost (27-Apr-10)
Paper page: 33
Unless I am misunderstanding (hand coding in Netbeans 6.8)
book shows nakedobjects.properties as
nakedobjects.services.prefix = com.pragprog.dhnako.carserv.dom
should read
nakedobjects.services.prefix = com.pragprog.dhnako.carserv.service
At least, that what I needed to do to get it running--Alan Franklin
- Reported in: P1.0 (14-Mar-10)
PDF page: 49
Just submitted an erratum relating to the Coffee Bytes link given on this page being broken, then was surprised not to see it in the list of errata.
Then I saw the message that errata containing hyperlinks are not accepted! I'll try again, leaving the protocol part off the URLs.
The link you gave for Coffee Bytes was to
This is broken, but this works: archive.realjenius.com/platform_support
The latter link is referenced from the project page at code.google.com/p/coffee-bytes/
(which mentions that this project is no longer being maintained)
-- Justin
--Justin Forder
- Reported in: P1.0 (04-Jan-10)
Paper page: 75
references FredSmithSessionFixture instead of LogonAsFredSmithFixture (not that I can get it to work anyway!)--Niall Barry
- Reported in: P1.0 (04-Jan-10)
PDF page: 89
Paper page: 72
Last sentence on page seems to be a 'composite' of two - first should state something like "...by pressing the Shift key at the same time as clicking on the icon, you can see the menu options shown in fig 4.3. If you do [whatever] using the HTML viewer, it ..."--Niall Barry
- Reported in: P1.0 (19-Aug-11)
PDF page: 91
Cannot get "fsmith" to login, the logged in user is still "exploration" when I run it in exploration. The same problem persists even when I import chapter04-02 into eclipse from the given source code, except that in this case, the user "sven" is logged in. Long story short, I cannot log in as "sfmith" using the LogonAsFredSmithFixture method. It seams this error is very similar to error #42002.
- Reported in: P1.0 (21-Aug-11)
PDF page: 123
In the Exercises section, the sentence "Finally, we
could simplify the AbstractCustomerFixture’s newCar( ) method to use Customer’s
newCar( ) action instead." should be "Finally, we
could simplify the AbstractCarFixture’s createCar( ) method to use Customer’s
newCar( ) action instead."
- Reported in: P1.0 (23-Aug-11)
PDF page: 127
In the createCar method, two lines (Car car = newTransientInstance(Car.class); car.modifyOwningCustomer(customer);) should be replaced with only one line (Car car = customer.newCar();).
- Reported in: B7.0 (08-Dec-09)
PDF page: 162
Customer-Name.java
public class Car ... should be public class Customer ...--Cesar Lesc
- Reported in: P1.0 (07-Sep-11)
PDF page: 231
The GivenCustomerWithNoVehiclesTest class has a typo: the line assertThat(customer.disableDeleteVehicle(), is(nullValue())); should be assertThat(customer.disableDeleteVehicle(), is(not(nullValue()))); | https://pragprog.com/titles/dhnako/errata | CC-MAIN-2016-50 | refinedweb | 490 | 59.4 |
desktop wallpaper to one of six pre-defined selections?
-- SB
Hey, SB. You know, when the Scripting Guy who writes this column first sat down to tackle this problem he thought he had a really cool solution for you. Recently this Scripting Guy read about Johannes Trithemius, a Benedictine monk from the 1400s who was one of the fathers of modern cryptography. That’s all well and good, but what really caught the Scripting Guy’s attention was Johannes’ system for communicating by having angels pass messages from one person to another. Imagine how cool that would be: someone wants to change their desktop wallpaper, and an angel comes down from heaven and makes the change for them. Talk about making an impression on your users, eh?
Unfortunately, though, the Scripting Guy who writes this column could never quite figure out how to conjure up a heavenly angel. On two separate occasions he did manage to conjure up outfielders from the Los Angeles Angels of Anaheim, but neither of them would agree to go out and change people’s wallpaper. Of course, that could be due to the fact that the Scripting Guy who writes this column never actually asked them about changing the wallpaper, but instead spent the whole time making fun of their team name.
Still, he’s a little surprised they wouldn’t do it. After all, they’ll have plenty of spare time in October, when other teams are in the playoffs.
Regardless, the Scripting Guy who writes this column was unable to get angels of any kind to change the wallpaper. Instead, the best he could come up with was a script that could do this:
One quick note before we explain how this script works. It’s actually quite easy to change the wallpaper: you just assign the wallpaper path to a value in the registry (HKEY_CURRENT_USER\Control Panel\Desktop\Wallpaper). The only problem is that the change does not take place immediately; in fact, it doesn’t take place until the user logs off and then logs back on. (Why not? Because, without downloading a third-party utility from somewhere, there’s no straightforward and reliable way to refresh desktop settings using a script.) That doesn’t mean that you can’t change the wallpaper, it just means that you can’t make dynamic changes during the current logon session. Consequently, you might want to assign this script as a logoff script. That way, when the user logs off the script will run and the wallpaper will change. In turn, the change will take effect the next time the user logs on.
At any rate, let’s see if we can figure out how the script works. We start out by defining a constant named HKEY_CURRENT_USER and assigning it the value &H80000001; we’ll use this constant to tell the script which registry hive to work with. We then connect to the WMI service on the local computer (although we could also perform this task remotely), taking care to bind to the root\default namespace:
Set objReg = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
Now it’s time to randomly select one of our 6 wallpapers. Admittedly, generating random numbers in VBScript can be a little confusing. Our advice? Don’t worry too much about the details. Just follow the basic template we’ve used here and you’ll be fine.
With that in mind we start out by assigning values to two variables, variables which represent the high and low numbers in our number range. Because we have 6 wallpapers to choose from that means we want our numbers to range from 1 to 6; hence we assign those values (1 and 6) to our variables:
intLowNumber = 1 intHighNumber = 6
Next we call the Randomize function, a function that “seeds” the random number generator with the current system time. Is that important? You bet it is: if you don’t use the Randomize function the script will simply generate the same “random” number each time it runs. We then use this line of code and the Rnd function to randomly select a number between 1 and 6:
intNumber = Int((intHighNumber - intLowNumber + 1) * Rnd + intLowNumber)
At this point the variable intNumber contains one of the following values: 1, 2, 3, 4, 5, or 6. To convert this random number into desktop wallpaper we use the following Select Case statement, in which we assign the variable strValue a different wallpaper path based on the value of intNumber:
See how that works? If intNumber is equal to 1 the variable strValue gets assigned the path C:\WINDOWS\System32\Wallpaper1.bmp. If intNumber is equal to 2 the variable strValue gets assigned the path C:\WINDOWS\System32\Wallpaper2.bmp. And so on.
At this point we’re almost done. After assigning the wallpaper path to strValue we then use these two lines of code to assign values to variables that represent the appropriate registry key within HKEY_CURRENT_USER (Control Panel\Desktop) and the appropriate registry value within that key (Wallpaper):
strKeyPath = "Control Panel\Desktop" ValueName = "Wallpaper"
We then call the SetStringValue method to write the changes to the registry:
objReg.SetStringValue HKEY_USERS, strKeyPath, ValueName, strValue
That will change the registry although, again, the user won’t actually see the new wallpaper until he or she logs off and logs back on.
As we noted, in addition to trying to find a way to use angels to deliver messages Johannes Trithemius was also interested in more mundane forms of cryptography, particularly steganography, which involves hiding secret messages in plain sight. (For example, you might read the message by taking every other letter of every other word.) That, of course, leads to an interesting question: have the Scripting Guys been including secret messages in the things that they write?
Well, we can’t speak for the other Scripting Guys. But if you can find any kind of message or meaning in a Hey, Scripting Guy! column (let alone a hidden one) we can only assume that you must have made a mistake. | http://www.microsoft.com/technet/scriptcenter/resources/qanda/jan07/hey0118.mspx | crawl-002 | refinedweb | 1,012 | 58.11 |
At the latest London Unity User Group, the evening kicked off with a beginner talk by Jasper Stocker, and was followed by ‘Open Mic’ talks by myself — demoing a quick Space Shooter demo I made in Unity — and LUUG regular Quickfingers, showing off a game he made for recent Ludum Dare 48 game jam. The headline act was Richard Fine, who gave an excellent talk on creating large game worlds in Unity.
As usual I do my best to capture the LUUG meets for others to catch up with, this time however I only had a single camera to work with, and no screen capture — ability.. but here is the footage anyway! enjoy folks..
Quickfingers — Making AWOL for Ludum Dare
Richard Fine — Making Large Game Worlds
Part One
;
Part Two
For more info on London Unity Usergroup, including the next meetup, see the meetup site —.
Will GoldstoneОктябрь 19, 2011 в 4:38 дп
Thanks for the slides Richard!
John Morales (Zyxil)Сентябрь 14, 2011 в 9:13 пп
Excellent talks.
@Richard Fine: This is brilliant:
public class InspectorBase : Editor where T : UnityEngine.Object
{
protected T Target { get { return (T) target; } }
}
Richard FineСентябрь 9, 2011 в 5:36 дп
Finally got the slides online:
Keynote:
Powerpoint:
Georges PazСентябрь 5, 2011 в 3:29 дп
Awesome useful tips/hints for newcomers (and seasoned alike) Unity developers!
Keep it up!
Cheers,
Richard FineСентябрь 1, 2011 в 6:26 пп
I’ve not got my slides quite ready to post online yet, but they should go up in the next day or two, I promise!
(Also, I should qualify my statement about Rebellion’s games. Obviously I didn’t actually mean that their games aren’t very good. I mean, obviously, the ones *I* worked on were all *excellent*…) | https://blogs.unity3d.com/ru/2011/09/01/london-unity-user-group-4-all-your-unity-are-belong-to-us/ | CC-MAIN-2019-35 | refinedweb | 295 | 67.89 |
OpenCV Error: LNK1181: cannot open input file 'opencv_core2410.dll.lib'
- Todd Morehouse
I am new to the Qt ide, and am still learning C++. So I apologize in advance if I do not quite understand something.
I am trying to setup OpenCV to use inside the Qt IDE for my senior project.
I have gone through the grueling process of attempting to follow the steps by many tutorials (Steps were easy, errors were the hard part).
I somehow managed to get through all of these errors, and now I am at my final error (hopefully) and hoping somebody here can help :), here it goes.
I compiled OpenCV using minGW to c:\opencv\build\install. (OpenCV version 2.4.10)
This seems OK.
I set the proper environment variables for this as well, and set what seems to be the proper includes in my .pro file.
Once I try to run the application, I get the following error.
:-1: error: LNK1181: cannot open input file 'opencv_core2410.dll.lib'
Inside the lib folder, everything is named .dll.a, I am not sure if these are supposed to be .dll.lib, or if the .dll.lib files are somewhere else and or missing them.
# # Project created by QtCreator 2015-03-30T22:25:22 # #------------------------------------------------- QT += core QT -= gui TARGET = untitled4 CONFIG += console CONFIG -= app_bundle TEMPLATE = app SOURCES += main.cpp INCLUDEPATH += C:\\opencv\\build\\install\\include LIBS += -LC:\\opencv\\build\\install\\x64\\mingw\\lib \ -lopencv_core2410.dll \ -lopecv_highgui2410.dll \ -lopencv_imgproc2410.dll \ -lopencv_features2d2410.dll \ -lopencv_calib3d2410.dll
main.cpp
#include <opencv2/highgui/highgui.hpp> int main(){ cv::Mat image = cv::imread("img.jpg"); cv::namedWindow("My Image"); cv::imshow("My Image", image); cv::waitKey(5000); return 1; }
Thank you in advance for the help, it is much appreciated :)!
LIBS += -LC:\opencv\build\install\x64\mingw\lib
-lopencv_core2410
-lopecv_highgui2410
-lopencv_imgproc2410
-lopencv_features2d2410
-lopencv_calib3d2410
If your *.lib in "C:\opencv\build\install\x64\mingw\lib" and add the "C:\opencv\build\install\x64\mingw\bin" ( should containing your DLLs ) in your Project-Enviroment Path
- Todd Morehouse
I still come out to the same error. | https://forum.qt.io/topic/52741/opencv-error-lnk1181-cannot-open-input-file-opencv_core2410-dll-lib | CC-MAIN-2018-30 | refinedweb | 343 | 67.65 |
Inherits QWidget and QRangeControl.
QSpinBox allows the user to choose a value either by clicking the up/down buttons to increase/decrease the value currently displayed or by typing the value directly into the spin box. If the value is entered directly into the spin box, Enter (or Return) must be pressed to apply the new value. The value is usually an integer.
Every time the value changes QSpinBox emits the valueChanged() signal. The current value can be fetched with value() and set with setValue().
The spin box keeps the value within a numeric range, and to multiples of the lineStep() size (see QRangeControl for details). Clicking the up/down buttons or using the keyboard accelerator's up and down arrows will increase or decrease the current value in steps of size lineStep(). The minimum and maximum value and the step size can be set using one of the constructors, and can be changed later with setMinValue(), setMaxValue() and setLineStep().
Most spin boxes are directional, but QSpinBox can also operate as a circular spin box, i.e. if the range is 0-99 and the current value is 99, clicking "up" will give 0.). currentValueText() returns the spin box's current value as text.
Normally the spin box displays up and down arrows in the buttons. You can use setButtonSymbols() to change the display to show + and - symbols if you prefer. In either case the up and down arrow keys work as expected.
It is often desirable to give the user a special (often default) choice in addition to the range of numeric values. See setSpecialValueText() for how to do this with QSpinBox.
The default QWidget::focusPolicy() is StrongFocus.
If using prefix(), suffix() and specialValueText() don't provide enough control, you can ignore them and subclass QSpinBox instead.
QSpinBox can easily be subclassed to allow the user to input things other than an integer value as long as the allowed input can be mapped to a range of integers. This can be done by overriding the virtual functions mapValueToText() and mapTextToValue(), and setting another suitable validator using setValidator().
For example, these functions could be changed so that the user provided values from 0.0 to 10.0, or -1 to signify 'Auto', while the range of integers used inside the program would be -1 to 100:
class MySpinBox : public QSpinBox
{
Q_OBJECT
public:
...
QString mapValueToText( int value )
{
if ( value == -1 ) // special case
return QString( "Auto" );
return QString( "%1.%2" ) // 0.0 to 10.0
.arg( value / 10 ).arg( value % 10 );
}
int mapTextToValue( bool *ok )
{
if ( text() == "Auto" ) // special case
return -1;
return (int) ( 10 * text().toFloat() ); // 0 to 100
}
};(). | http://www.linuxmanpages.com/man3/qspinbox.3qt.php | crawl-003 | refinedweb | 438 | 56.66 |
What is a Multimethod's Identity?
The key question with multimethods is one of identity. A multimethod is a collection of methods, but when should two piles of identically-named methods be a single method and when should they be separate?
Other ways to phrase the question:
- When do two
defs with the same name collide and when do they merge?
- When do two
imports of methods with the same name collide, and when do they merge?
- When a method is defined in one module, which other modules see that change?
Current Implementation
The current implementation works like this:
Imagine the
import graph of a set of modules. If module
a imports
b then there's a directed edge from
a to
b. Two methods are part of the same multimethod if there is a path from one to the other, or if they each have a path to a third shared method.
For example:
.----------. | // a.mag | | def m1() | '----------' / \ .----------. .----------. | // b.mag | | // c.mag | | import a | | import a | | def m1() | | def m1() | | def m2() | | def m2() | '----------' '----------'
Here, there is only a single
m1 method across all three modules, but
b and
c each have their own
m2. Note that if an
m2 were later added to
a, then all three would collapse into a single multimethod.
Use Cases and Problems
There are a number of relevant use cases:
Overloading
This should not be an error:
def method(n Int) ... def method(s String) ...
But this should:
def method(n Int) ... def method(s Int) ...
Unrelated Methods
Given this:
// a.mag def method(n Int) ... // b.mag def method(n Int) ...
As long as those two modules are never both imported unqualified by another module, the above should be fine and produce no error. Those methods should be oblivious to each other.
Overriding
// a.mag def method(any) ... def callIt(arg) method(any) // b.mag import a def method(n Int) "int" callIt(123) // should return "int"
Here module
a defines a multimethod
method. Module
b refines it. The important part is
callIt(). It exists only in module
a and isn't aware of module
b at all. But when it's called, it should still successfully find the more specific method defined in
b.
The specific case where this arose is:
// core.mag def (left Comparable) < (right Comparable) left compareTo(right) == -1 end // spec.mag defclass TestComparable // ... end def (left TestComparable) compareTo(right TestComparable) ... var test = TestComparable new() test < test
The last line calls
< which in turn calls
compareTo from
core.mag. But since
core.mag didn't know about
TestComparable at all, it never saw that specialization in
spec.mag.
The fix was to import entire multimethods on
import. So when
spec.mag imported
core.mag it got a reference to the
compareTo multimethod— the actual same object that the
core.mag module was referencing. When we defined
compareTo on
TestComparable, that method went into that same multimethod object, so
core.mag was later able to see it.
Colliding Getters
Every field on a class has a corresponding getter, which is just a multimethod. Given that, consider:
defclass Person var name String end defclass Pet var name String end
In the current implementation, this code in a single module will implicitly create a single
name multimethod with specializations for
Person and
Pet, so it works as expected. Now consider:
// a.mag defclass Person var name String end // b.mag defclass Pet var name String end // c.mag import a import b
Those imports will collide when they both try to import distinct and unrelated
name multimethods. One possible solution is to have those imports merge and create a single
name multimethod. As long as none of the specializations collide (which they don't here), that would be fine.
But now consider the previous overriding use case. Consider:
// a.mag defclass Person var name String end // b.mag defclass Pet var name String end // c.mag import a import b def (_ Int) name ...
Which multimethod do we define that last
name in? The one from
a or
b, or both?
Another example of the problem:
// a.mag def method(s String) "string" def callFromA(arg) method(arg) // b.mag def method(b Bool) "bool" def callFromB(arg) method(arg) // c.mag import a import b def method(n Int) "int" method(true) // should be "bool" callFromA(123) // "int"? callFromB("str") // "string"?
Maybe the way to phrase the question is: are methods lexically scoped or dynamically scoped? This last example implies a certain amount of dynamic scoping:
callFromA() should have access to the
method methods defined where
callFromA() is being called. But that kind of seems like crazy talk.
Chained Imports
Imports are not and should not be transitive. If I import
a which imports
b, I don't get everything in
b imported into my module, just the stuff from
a. If we were to try to dynamically scope methods, though, that would break it. Consider:
// a.mag def aMethod() "a" // b.mag import a def bMethod() aMethod() // c.mag import b bMethod() // should return "a"
When we call
bMethod(), we can look it up in module
c because it's been imported. But when that in turn looks up
aMethod(), we can't look that up in
c, because
aMethod() hasn't been imported into it.
Solutions
No Spanning Across Modules
The simplest solution is that multimethods are never shared across modules. Instead, each module has its own multimethod for a given name. When you import, the methods are imported individually and piled into that collection. That addresses overloading, colliding getters, and unrelated methods. It's also concurrency friendly (since defining a method in one module doesn't affect others.
It breaks overriding. As far as I can tell, that's the only real problem with this, though that's certainly a valid one.
// core.mag def (left Comparable) < (right Comparable) left compareTo(right) == -1 end // spec.mag defclass TestComparable // ... end def (left TestComparable) compareTo(right TestComparable) ... var test = TestComparable new() test < test
Global Multimethods
The interpreter keeps a global pool of multimethods. Any method defined with a given name in any package becomes part of the same multimethod.
If you haven't defined a method with a given name, or imported it, you won't see that name at all, but if you have, you see the same one as every other module.
This solution is pretty simple, and addresses every use case lists above except for unrelated methods. It also doesn't allow lexically-scoped multimethods, but it could be that this "global pool" rule only applies to top-level multimethods or something.
But, of course, unrelated methods were one of the main motivations for multimethods in the first place.
Current Solution
The current solution works pretty well. When you import a multimethod, you import the exact same object, so when you add new methods, the original module can see them too. That addresses overriding while still allowing unrelated methods.
The only real problem with it is colliding getters. The CLOS solution is to just rename:
// a.mag defclass Person var name String end // b.mag defclass Pet var name String end // c.mag import a = a import b = b Person new("Bob") a.name Pet new("Ginny") b.name
That's perfectly valid for most methods. It just feels a bit weird to have to do it for getters. One angle to look at it is, "if two classes have the same field, should you be able to treat them generically?" Consider:
defclass Person var name String end defclass Pet var name String end def sayName(who) print(who name)
Should we expect
sayName() to work with both people and pets? If the answer is yes, then renaming is wrong. If it's no, then it's reasonable. If you should be able to act on those classes generically, then one solution is:
defclass Named var name String end defclass Person : Named end defclass Pet : Named end def sayName(who Named) print(who name)
That's probably the Right Thing, and not that this also fixes the colliding getter problem. Even if
Person and
Pet are defined in different modules, they will both be importing the one that defines
Named so they'll use the same multimethod for
name.
So maybe the current system is the best we can do. | http://magpie.stuffwithstuff.com/design-questions/what-is-a-multimethods-identity.html | CC-MAIN-2017-30 | refinedweb | 1,394 | 67.25 |
I managed to download and install the .deb package from Album Cover Art Downloader. In Synaptic I can se that albumart is installed. But I can't find the application on any menu. How can I run it?
When I typed sudo albumart-qt in the terminal I got the following lines:
Traceback (most recent call last):
File "/usr/bin/albumart-qt", line 145, in <module>
sys.exit(runGui())
File "/usr/bin/albumart-qt", line 77, in runGui
import albumart_dialog
File "/usr/lib/albumart/albumart_dialog.py", line 5
SyntaxError: Non-ASCII character '\xf6' in file /usr/lib/albumart/albumart_dialog.py on line 5, but no encoding declared; see for details
What does this mean? | http://forums.linuxmint.com/viewtopic.php?f=47&t=9996 | CC-MAIN-2015-18 | refinedweb | 114 | 52.26 |
Sometimes..
22 thoughts on “When You Need A Scope, You Need A Scope”
This is funny. I am just sitting down to troubleshoot an i2c issue. I turned on my scope and then checked my email to find this. I call an oscilloscope a time microscope — which is most certainly what it is. Almost the equivalent of “put a printf in the code and let it tell you what it is doing” is “hook up the scope and see what is really going on”.
Now that you mention the printf, there is a trick I learned a long time ago. Let’s say you want to debug a state machine. You can use an unused DAC (or even connect one) in your uP and output a different voltage for every state. Then on the scope is obvious what your program is doing. This has saved me a lot of time debugging embedded circuits.
Wow! That’s a pretty ingenious idea. Never thought of that. I’ve done something similar in using a few extra GPIOs as state flags with some encoding register states and some which step it was on, but was limited by number of pins. Combining the two gives me a much greater flexibility.
Slight variation:
Output the debug data to whatever (serial) peripheral your’re not using uart, i2c, spi, etc and catch it with a logic analyser. Much more accurate and you can search through your data.
Years ago I wore some macro’s for AVR to do this at a random pin and I was amazed how usefull this was.
/*===========================================================================
User definitions for: Debugging.
===========================================================================*/
/* Simple and low impact debugging lib.
It’s main use is to output some values to a logic anaylzer to trace back which
parts of your code are exectuded and the timing between marked points.
1). Define “DEBUG_PORT”, “DEBUG_DDR”, and “DEBUG_BIT” macro’s for the
debug output and include this header file in each .c(pp) file you want
to use it for debugging. Copy/paste the example:
//#define DEBUG_PORT PORTD // This define adds/removes the debug code.
#define DEBUG_DDR DDRD
#define DEBUG_BIT (1<<7)
#include "debug.h"
2). It's possible this way to use a different debug pin for each source file.
3). Call the DEBUG_OUTPUT_ENABLE macro once to enable the output.
4). DEBUG(X) can now be used to trace the execution path through your software
with a logic analyzer.
5). Output format is serial, 7N1 with a baudrate of 50% of F_CPU.
6). Commenting out "DEBUG_PORT" & recompile will completely disable debugging.
7). If optimisation level is higher than -O1 timing gets messed up.
8). For an overview of the meaning of your debug numbers you can comment
the debug lines and then do a grep on that file. See example below.
Bug: Enchancement, Use hardware SPI, U(S)ART or whatever is available.
– Variables can be send.
– Even lower inpact on program timing.
– Less flexibility in output pins.
– needs more i/o pins.
– This debug can use different pins for each source code file.
*/
#ifdef DEBUG_PORT
// Just to make sure the user knows the debug code is inserted.
// Higher optimisation levels disrupts the timing for debugging.
#warning Debug code inserted. Use optimisation level: -O1.
// Use this macro to enable the debug output pin.
#define DEBUG_OUTPUT_ENABLE _SET, (DEBUG_DDR |= DEBUG_BIT)
// 3 little Macro's for internal use only.
#define _SET (DEBUG_PORT |= DEBUG_BIT)
#define _CLEAR (DEBUG_PORT &= ~DEBUG_BIT)
#define _BIT(X,Y) ((X) &(0x01 << (Y)) ? (_SET) : (_CLEAR))
// Startbit, a bunch of data bits and a stop bit.
#define DEBUG(X) (_CLEAR,\
_BIT(X,0), _BIT(X,1), _BIT(X,2),_BIT(X,3),\
_BIT(X,4), _BIT(X,5), _BIT(X,6), \
_SET)
#else
// Preprocessor removes debug statements.
#define DEBUG_OUTPUT_ENABLE
#define DEBUG(x)
#endif
The stuff on my website is getting pretty old unfortunately…
I’ve debugged JTAG breakpoint code with an oscilloscope and put rising edges on unused pins at points in the code to trigger. It really can be simplest way to figure out what’s wrong at the software level.
I hope the readers are all smart enough to know the difference between the two devices mentioned and the voltage limitations involved with one of them….
That said, having a logic analyzer, I would have pulled it out and used it for I2C, as it’s going to have some protocol analysis available so I can see what’s going on without having to decipher the bits to be sure.
Short of having the logic analyzer, a ‘scope will work, but it’s more work to get an actual value out of your display, unless you have a more expensive scope that can do communication protocols as well.
But using a “LOGIC” logic analyzer that is limited to TTL and trying to read real, full level RS232 is going to bite someone if they don’t know better.
A scope would cover it, but having a headline like this and then talking about a completely different piece of gear is kind of weird.
But you are the only one talking about a logic analyzer.
Oops, I stand corrected – yes the title is misleading. I find logic analyzers a pain in the rear to set up, but invaluable when you have lots of channels and only care about logic states. An oscilloscope on the other hand is usually quick and easy to clip onto a single signal and of course shows you the full range of voltage levels. I just invested in a Rigol DS1054Z and could not be more delighted. My old Tektronix 7603 won’t be seeing much use.
That’s a Saleae logic analyzer’s output in the pic, isn’t it? Good stuff, those, and a better UI than any other logic analyzer I’ve used. The newer devices with analog channels can even be a passable substitute for an oscilloscope, so long as you’re working with fairly low frequencies like I2C.
Regarding the Saleae logic analyzer, a few years ago I’ve bought the 1st version (8bit and digital only). It is a wonderful device that has helped me out many many times. In combination with the protocol analyzers it is really practical. It is just so much easier then counting edges on the signals of an oscilloscope screen.
But what is the greatest of all is the infinite depth, you can sample for very long, minutes on 24MHz is you have to. Which is great if you do not know when your problem is going to happen or to which event it is related.
It is a shame that there are cheap clones/copies out there that pretend to be the real device and therefore use the same software. So if you want a versatile but cheap analyser, go for the Saleae one, support the designers not the pirates that make the clones.
Or you can use sigrok with the “clones”. They have fully open source firmware and driver for them and sigrok/pulseview are open source as well. Support open source, not over charging corporations.
If you are implying that Saleae is an “over charging corporation” you are dead wrong. The owners are makers like all of us that are making a living by creating a fantastically well-designed product at a very reasonable price. I have bought several logic analyzers from them and are among the finest measurement devices I have ever had. My Kudos to them and Jii not everyone that sales something is a crook, somehow people has to make a living and employ other people. I’m sure Saleae creates a lot of direct and indirect employment.
Well sorry, but charging over a hundred for 8 bit 24 Mhz Logic analyser for 3,3V logic (as, if i remember correctly, the original does not have a buffer or is the wrong kind, it can overload 5V pins, just like in some clones) made from 2 dollar MCU and the whole thing isn’t their design, as i’ve understood, pretty much brings them to a over charging corporation in my book.
If it actually was reasonably priced, i’d have no problem. There is no way to be able to beat the chinese, if you keep over valuing your brand. You pay 15 dollars or 150 dollars. Well, maybe i’m wrong, look where Apple is.
If you have $100 to spend on a logic analyzer, look into the DSLogic. HaD even has a review and sell that in their store. It has 16 channels with 16MB buffer and can sample to 100MS/s or 200MS/s for 4-bit. Software is a bit crude and it locks up once in a while, but it does it job.
Oops. It can go up to 400MS/s for 4 inputs. The probes are passive probes with a voltage divider and to reduce loading for high speed signals and it is a micro coax cable. Most of your your usual DIY or those 24MHz toys just feed the signal with a short loose wire into a chip or a buffer. There is a bit of engineering for that price.
Absolutely love Saleae’s products and support. Recently upgraded my Logic16 to a Logic16 Pro (which has some useful analog functionality). The software sells their product IMO
Unfortunately, no USB LA is a substitute for a physical one, for the simple reason that it’s triggered. Physical ones can be left to roll, which means you get to see the glitches that happen when you don’t expect, and the infrequent ones too.
Once you know they’re there, by all means use a USB one, but there are many bugs I’ve caught in the past just by having the ‘scope on roll, and seeing something ‘odd’ that I wouldn’t have captured otherwise.
Quite a strange article in my opinion… The arduino code is really trivial and there is certainly already something like this on the internet – or to quote some other comments: Where’s the hack? Using an AVR with internal I2C hardware to receive I2C isn’t one.
Ok, let’s say something more useful… For those like me that need to debug an I2C (or other) bus with a scope that doesn’t has protocol decoders (like the famous DS1052E): It’s quite easy to export the data from the scope, convert it and feed it to the I2C analyzer of the Open Logic Sniffer software or some other software (protocol decoders or other stuff). I did this once using a USB flash drive, it’s works but saving 1M points in csv is reaaaaaally slow (and even if the native Rigol format has been reverse-engineered it’s to complicate for a quick thing). I plan to connect the scope to the computer and automate the entire thing using Perl. It’s quite easy to talk to the scope and the commands are documented entirely by Rigol – have fun!
(For those like me that don’t have a logic analyzer but only a scope…)
If you have a device or a master that pulls down the clock or data line line out of turn, then all you can see on the logic analyzer are corrupted data.
If you have a scope, you can at least put a small series resistor in the 100 ohms range on the device and try to observe the voltage drop across it to determine if who is acting funny pulling the signal down. The current shows up as a small I*R drop and can be seen in a scope.
Ideally, you want to have both – one for timing and one for looking at the signal level and signal quality.
i had a simular issue with driving an I2C OLED from arm when the exact same code worked well on an arduino.
after some datasheet diving i ended up changing slew rate and drive strength on the i2c gpio ( PORT_PCR_DSE_MASK and PORT_PCR_SRE_MASK) and then it just worked ;)
In my day, oscilloscopes were often affectionately referred to as “Truth Meters”. A well applied scope really is hard to beat! I often use mine as a quick replacement even for a voltmeter. | https://hackaday.com/2016/08/04/when-you-need-a-scope-you-need-a-scope/ | CC-MAIN-2019-35 | refinedweb | 2,031 | 70.53 |
This lesson teaches you to
- Subclass a View
- Define Custom Attributes
- Apply Custom Attributes to a View
- Add Properties and Events
- Design For Accessibility
You should also read
Try it out
CustomView.zip
A well-designed custom view is much like any other well-designed class. It encapsulates a specific set of functionality with an easy to use interface, it uses CPU and memory efficiently, and so forth. In addition to being a well-designed class, though, a custom view should:
- Conform to Android standards
- Provide custom styleable attributes that work with Android XML layouts
- Send accessibility events
- Be compatible with multiple Android platforms.
The Android framework provides a set of base classes and XML tags to help you create a view that meets all of these requirements. This lesson discusses how to use the Android framework to create the core functionality of a view class.
Subclass a View
All of the view classes defined in the Android framework extend
View. Your
custom view can also
extend
View directly, or you can save time by extending one of the
existing view
subclasses, such as
Button.
To allow the Android Developer Tools
to interact with your view, at a minimum you must provide a constructor that takes a
Context and an
AttributeSet object as parameters.
This constructor allows the layout editor to create and edit an instance of your view.
class PieChart extends View { public PieChart(Context context, AttributeSet attrs) { super(context, attrs); } }
Define Custom Attributes
To add a built-in
View to your user interface, you specify it in an XML element and
control its
appearance and behavior with element attributes. Well-written custom views can also be added and
styled via XML. To
enable this behavior in your custom view, you must:
- Define custom attributes for your view in a
<declare-styleable>resource element
- Specify values for the attributes in your XML layout
- Retrieve attribute values at runtime
- Apply the retrieved attribute values to your view
This section discusses how to define custom attributes and specify their values. The next section deals with retrieving and applying the values at runtime.
To define custom attributes, add
<declare-styleable>
resources to your project. It's customary to put these resources into a
res/values/attrs.xml file. Here's
an example of an
attrs.xml file:
<resources> <declare-styleable <attr name="showText" format="boolean" /> <attr name="labelPosition" format="enum"> <enum name="left" value="0"/> <enum name="right" value="1"/> </attr> </declare-styleable> </resources>
This code declares two custom attributes,
showText and
labelPosition, that belong
to a styleable
entity named
PieChart. The name of the styleable entity is, by convention, the same name as the
name of the class
that defines the custom view. Although it's not strictly necessary to follow this convention,
many popular code
editors depend on this naming convention to provide statement completion.
Once you define the custom attributes, you can use them in layout XML files just like built-in
attributes. The only
difference is that your custom attributes belong to a different namespace. Instead of belonging
to the namespace, they belong to[your package name]. For example, here's how to use the
attributes defined for
PieChart:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <com.example.customviews.charting.PieChart custom: </LinearLayout>
In order to avoid having to repeat the long namespace URI, the sample uses an
xmlns directive. This
directive assigns the alias
custom to the namespace. You can choose any alias
you want for your
namespace.
Note: If you are not using Gradle to build
your project, your
xlmns URI cannot include
res-auto.
Instead, the URI must contain the fully qualified name of your project. In
this example, the non-Gradle URI would be:.
Notice the name of the XML tag that adds the custom view to the layout. It is the fully
qualified name of the
custom view class. If your view class is an inner class, you must further qualify it with the name of the view's outer class.
further. For instance, the
PieChart class has an inner class called
PieView. To use the custom attributes from this class, you would
use the tag
com.example.customviews.charting.PieChart$PieView.
Apply Custom Attributes
When a view is created from an XML layout, all of the attributes in the XML tag are read
from the resource
bundle and passed into the view's constructor as an
AttributeSet.
Although it's
possible to read values from the
AttributeSet directly, doing so
has some disadvantages:
- Resource references within attribute values are not resolved
- Styles are not applied
Instead, pass the
AttributeSet to
obtainStyledAttributes().
This method passes back a
TypedArray array of
values that have
already been dereferenced and styled.
The Android resource compiler does a lot of work for you to make calling
obtainStyledAttributes()
easier. For each
<declare-styleable>
resource in the res directory, the generated R.java defines both an array of attribute
ids and a set of
constants that define the index for each attribute in the array. You use the predefined
constants to read
the attributes from the
TypedArray. Here's how
the
PieChart class
reads its attributes:
public PieChart(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.PieChart, 0, 0); try { mShowText = a.getBoolean(R.styleable.PieChart_showText, false); mTextPos = a.getInteger(R.styleable.PieChart_labelPosition, 0); } finally { a.recycle(); } }
Note that
TypedArray objects
are a shared resource
and must be recycled after use.
Add Properties and Events
Attributes are a powerful way of controlling the behavior and appearance of views, but
they can only be read
when the view is initialized. To provide dynamic behavior, expose a property getter and
setter pair for each
custom attribute. The following snippet shows how
PieChart exposes a property
called
showText:
public boolean isShowText() { return mShowText; } public void setShowText(boolean showText) { mShowText = showText; invalidate(); requestLayout(); }
Notice that
setShowText calls
invalidate()
and
requestLayout(). These calls are crucial
to ensure that the view behaves reliably. You have
to invalidate the view after any change to its properties that might change its
appearance, so that the
system knows that it needs to be redrawn. Likewise, you need to request a new layout if
a property changes
that might affect the size or shape of the view. Forgetting these method calls can cause
hard-to-find
bugs.
Custom views should also support event listeners to communicate important events. For
instance,
PieChart
exposes a custom event called
OnCurrentItemChanged to notify listeners that the
user has rotated the
pie chart to focus on a new pie slice.
It's easy to forget to expose properties and events, especially when you're the only user of the custom view. Taking some time to carefully define your view's interface reduces future maintenance costs. A good rule to follow is to always expose any property that affects the visible appearance or behavior of your custom view.
Design For Accessibility
Your custom view should support the widest range of users. This includes users with disabilities that prevent them from seeing or using a touchscreen. To support users with disabilities, you should:
- Label your input fields using the
android:contentDescriptionattribute
- Send accessibility events by calling
sendAccessibilityEvent()when appropriate.
- Support alternate controllers, such as D-pad and trackball
For more information on creating accessible views, see Making Applications Accessible in the Android Developers Guide. | http://developer.android.com/training/custom-views/create-view.html | CC-MAIN-2015-48 | refinedweb | 1,227 | 53.51 |
21 March 2012 11:18 [Source: ICIS news]
SINGAPORE (ICIS)--Taiwanese producer Nan Ya Plastics will bring forward a turnaround at its No 4 720,000 tonne/year monoethylene glycol (MEG) unit to late April from an original date of late June, a company source said on Wednesday.
“We decided to bring forward this turnaround to late April as some new equipment has already arrived,” the source said.
“The shutdown will last for around 40-50 days,” the source added.
As a result, the group’s supply to ?xml:namespace>
Asia MEG prices were still softening at $981-990/tonne (€746-752/tonne) CFR (cost and freight) CMP (
Nan Ya Plastics has four MEG units with a combined capacity of 1.8m | http://www.icis.com/Articles/2012/03/21/9543508/taiwans-nan-ya-to-bring-forward-no-4-meg-unit-turnaround-to-april.html | CC-MAIN-2014-10 | refinedweb | 122 | 66.07 |
Your Code Sunk My Battleship!
Starting Out:
We thought we had come up with a cool concept, and I knew it wouldn't be that difficult to build. After calling our dev-team into the office I started on it, by myself in my apartment. My goal was to have a single method to send any type of message that would then be picked up by an appropriate thread to deliver the message. As the whole idea here was to create and deliver messages, a logical place to start was a struct to hold our message fields. It's always good to keep other services in mind while you're building your own. I started off with the first 4 fields in any email. This covered message content and we only needed a bit more info to deliver the message. The medium type, along with an identifier field for your address (or screen name etc.), would cover this. Just in case a service we end up using needs a second identifier, I added one more. Check it out:
public struct ctMessage { public ctMessage(string sendToUser, string fromUser, string subj, string msg, string mediumType, string mediumArg1, string mediumArg) { this.toUser = sendToUser; this.fromUser = fromUser; this.subject = subj; this.message = msg; this.mediumType = mediumType; this.mediumArg1 = mediumArg1; this.mediumArg2 = mediumArg2; } public string toUser; //name of recipient public string fromUser; //name of sender public string subject; public string message; public string mediumType; //which node should deliver this public string mediumArg1; //varies, to identify the recipient public string mediumArg2; //varies, to identify the recipient }
Once we had a message designed I, of course, wanted to be able to send one! Eventually I wanted a bunch of different types of messages being sent, so a solid base class would save a ton of time later. Although all of the messaging services, or ‘nodes' would undoubtedly send the messages completely different, they would all need to run in a similar thread that sent messages coming from a single location. By doing a good job writing an abstract base class, we could add new services by only overriding the 'send' method later.
This abstract class would have a field identifying the type of messages it will handle, and call an external send method whenever messages of that type existed. A continuous loop to poll for messages, given a modest polling frequency would do the trick. Notice the protected methods and fields that we'll want to override.
public abstract class ctNode { public ctNode() { this.maxQueueSize = 100; //Set the size according to how long it will take to reach the Nth message this.msgQueue = new Queue(maxQueueSize); this.msPauseAfterRun = 10000; //If using a DB, polling it with no pause b/w queries is an unnecessary load this.runnerThread = new Thread(new ThreadStart(this.run)); } private Thread runnerThread; protected int msPauseAfterRun; protected Queue msgQueue; public int maxQueueSize; void run() { while (true) { while (this.msgQueue.Count > 0) { //pop a message and send it ctMessage ctm = (ctMessage)msgQueue.Dequeue(); try { sendSingleMessage(ctm); } catch (Exception e) { //Write a more detailed error log here Console.writeLine("the message could not be sent!" + e.toString()); } } //get new messages ctNode ctn = this; ctMessage[] newMessages = messageSender.getMessages(ref ctn, getRoomInQueue()); //Wait some time before checking for more messages! if (newMessages.Length == 0) Thread.Sleep(msPauseAfterRun); else this.EnqueueMessages(newMessages); } } public virtual void EnqueueMessages(ctMessage[] messagesToSend) { int roomInQueue = maxQueueSize - msgQueue.Count; if (messagesToSend.Length > roomInQueue) throw new Exception("Too many Messages have been inserted"); for (int i = 0; i < messagesToSend.Length; i++) { msgQueue.Enqueue(messagesToSend[i]); } } public virtual void EnqueueMessages(ctMessage messageToSend) { ctMessage[] ctm = new ctMessage[1]; ctm[0] = messageToSend; this.EnqueueMessages(ctm); } protected virtual void sendSingleMessage(ctMessage ctm) { //code to send an individual message } public void startThread() { runnerThread.Name = this.nodeType; runnerThread.Start(); } protected string nodeType; public string getNodeType() { return this.nodeType; } }
You might have noticed the big thing missing from these classes, a place to store, and retrieve messages! I initially put our message storage into an external static class. This made them centralized, easily accessible from any other objects that might need to access them, simple to ensure thread safety, and gave us room to move to a smarter mechanism later (or database. Notice the simplicity:
public static class messageSender { private static List<ctMessage> messagesToSend = new List<ctMessage>(); public static ctMessage[] getMessages(ref ctNode nodeRef, int numberOfMessages) { //We'll do this in a database later, but for now this works similarly List<ctMessage> returnMessages = new List<ctMessage>(); lock (messagesToSend) for (int i = 0; i < messagesToSend.Count; i++) if (messagesToSend[i].mediumArgs == nodeRef.getNodeType()) { returnMessages.Add(messagesToSend[i]); messagesToSend.RemoveAt(i); i--; } return returnMessages.ToArray(); } public static void sendMessage(ctMessage message) { lock (messagesToSend) messagesToSend.Add(message); } }
Now that the groundwork was done, I grabbed some eye drops and an energy drink to refresh for the best part, function! I started simple with an email node, and if you've played with email before in .net, you've definitely seen and loved the SmtpClient class in the System.Net.Mail Namespace. If you don't already have a local SMTP client set up, you can easily use a Gmail account as an SMTP server. Check out the following implementation, notice we only had to set the node type, initialize the SmtpClient and override the send method. Send a message through our message sender, and watch the node pick up the message and deliver it. Inheritance rocks!
ctMessage ctm = new ctMessge("Friend", "Developer", "testing", "My first message", "email", "yourEmail@yourDomain.com", ""); messageSender.sendMessage(ctm); public class ctNodeEmail : ctNode { public ctNodeEmail() : base() { this.nodeType = "email"; // //SET UP SMTP CLIENT // //GMAIL SERVER("YOURADDRESS@gmail.com", "YOUR_PASSWORD"); //LOCAL SERVER //this.mSmtpClient = new SmtpClient("localhost", 25); } SmtpClient mSmtpClient; protected override void sendSingleMessage(ctMessage ctm) { MailMessage msgMail = new MailMessage(new MailAddress(ctm.fromUser + "@ChalkTalkNow.com"), new MailAddress(ctm.mediumArgs)); msgMail.Subject = ctm.subject; string msg = ctm.message; msgMail.Body = msg; // Send the mail message mSmtpClient.Send(msgMail); } }
After writing this so quickly I wanted something a bit more than email, and knew text messages were only a step away. It's no secret that all major cell companies give your phone an email address, you just need to append the proper domain to your number. Building off of our email node, we used the first mediumArg to hold a phone number, and put the carrier into the second mediumArg.
public class ctNodeTextMessage : ctNode { public ctNodeTextMessage() : base() { this.nodeType = "textmessage"; // //SET UP SMTP CLIENT //("GMAIL@gmail.com", "PASSWORD"); } SmtpClient mSmtpClient; private string getEmailAddress(string phoneNumber, string provider) { switch (provider) { case "t-mobile": return phoneNumber + "@tmomail.net"; case "virginmobile": return phoneNumber + "@vmobl.com"; case "cingular": return phoneNumber + "@cingularme.com"; case "att": return phoneNumber + "@cingularme.com"; case "sprint": return phoneNumber + "@messaging.sprintpcs.com"; case "verizon": return phoneNumber + "@vtext.com"; case "nextel": return phoneNumber + "@messaging.nextel.com"; default: //assume cingular/att is the most popular return phoneNumber + "@cingularme.com"; } } protected override void sendSingleMessage(ctMessage ctm) { //send a single message string emailAddress = getEmailAddress(ctm.mediumArg1, ctm.mediumArg2); MailMessage msgMail = new MailMessage(new MailAddress(ctm.fromUser + "@chalktalk.net", ctm.fromUser), new MailAddress(emailAddress)); msgMail.Subject = ctm.subject; msgMail.Body = ctm.message; sendEmail(msgMail); } private void sendEmail(MailMessage msgMail) { // Send the mail message this.mSmtpClient.Send(msgMail); } }
Now to test this out, just like we sent the email we'll send a text. Cool!
ctMessage ctm = new ctMessge("Friend", "Developer", "testing", "hello world via text", "textmessage", "#########", "verizon"); messageSender.sendMessage(ctm);
When you're working on a project with a small team, it's especially important to build a good foundation like this so you can focus on easily added functionality without getting bogged down in complexity. This portion of the project was written over the course of a week and later on allowed us to focus almost exclusively on adding new services like Instant Messengers and interactive phone calling. Having functionality so quickly was crucial, along with a UI built by my brother, in getting the attention and support of others to build a business around this.
Yes a VB.net version would be nice.
@Bob Thanks, I will get to this then.
cool can you trancode it to vb language
Hi Robert,
An alternative would be to have a base abstract "Message" class and a sub-type for each message type, e.g. TextMessage, EmailMessage etc. To create a message you just call new TextMessage(args) and you have your TextMessage object.
The Message base class defines a method "send()". Each message sub-class should know how to send itself.
To send your messages all you have to do is go through your queue of Message objects calling "send()" on each.
I'm curious as to why you chose to sub-class the sender rather than the message, as "send()" seems like something a message should be able to do?
Cheers,
GC
GC,
You bring up a couple of interesting points, that are not well addressed in this piece. For the simple examples shown, you could certainly encapsulate sending functionality within the message struct, with perhaps a statically maintained connection.
When you're designing a web app with a lot done behind the scenes it's often best to decouple the interface and the processing. For the larger project here this meant an interface needed a message struct solely to hold fields. A second server, running the nodes might be actually doing the sending. This design allows you to not expose the node overhead to the UI developers that won't be it anyways.
The second point to consider is that a node may require a persistent singleton connection that must talk to another server. In this case it is easier to maintain sending in a separate class/thread that always runs.
-Rob
Yes Please give a VB version!!!
hey, the idea is cool but im not farmiliar with C# PLS CAN U TRASCODE IN VB
@rmehta looking into this
I could not find the downloable code on codeplex.
@Oron: Working on it, just have other things on my plate. can do most of the heavy lifting.
I could not find the downloable code on codeplex.
Just wanted to followup if you manged to get the code. I could not find the code at the downloadable link
@rmehta working on getting it back up.
Hey thanks, I know how it gets!!! | https://channel9.msdn.com/coding4fun/articles/Inherited-Message-Distributing | CC-MAIN-2017-51 | refinedweb | 1,713 | 57.57 |
CR There was a discussion a while ago, about using W3C icons.
LK Since it deals with branding can not modify the W3C icons.
CR You can not have the two icons together as one.
LK Right. If they are on the same page that's fine, but can't join them.
Resolved: You can not modify W3C icons but may use them along side a logo of your design.
WC Need exact date. PF would like to piggyback and prefer before XML 2000.
LK How long?
WC 1 day for us, 1/2 day with PF?
LK What about confidentiality issues?
WC Who does not have member access?
BM Does not although CAST has.
WC We can just avoid talking about member private issues.
Action WC: ask wai domain about PF and ER meeting and what to do about some issues that might be member private.
LK Do we sit in on their meeting or they sit in on ours?
/* XML 2000 is 3-8. Sunday through Friday. preconference tutorials are 3 & 4. */
Resolved: Thursday and Friday before XML 2000 is preferred (rather than Saturday, although Saturday is possible depending on what PF wants to do).
Len's notes from 18 August 2000.
LK Some pages already have link to TOC. This would give the functionality "automatically." "title" as new attribute in CSS.
HB Could something that is in CSS be used?
LK Not sure.
HB Hate to add something new that the processors don't recognize.
LK You can insert text into the text flow. If you use something that puts in the prefix that would make it invisible.
WC Could have 2 style sheets.
LK Or an extra style sheet that inserts the info so as not to duplicate the main style sheet. The user agent would have the ability to search on these inserted strings. Since they are inserted and visible, user agents that haven't implemented would show it. Then have JAWS set them up.
WC How will the cascade work if you define the same class twice? Will they unite or will one override the other?
LK So 2 questions: what does CSS spec say, what do browsers actually do?
/* WC reads through CSS 1 spec looking for info for defining classes in multiple sheets */
WC Could use ID and class?
HB Don't want to use ID. Have the info in the doc itself or separate style sheet.
LK You have a choice. Link to it or include in header.
WC What about the use of namespaces as suggested by Dan and Charles in their discussion? Looking for something that works today? Thoughts?
LK Didn't think about it much. How would it work?
WC Each class would have an associated class that would have info about it.
LK So RDF creates the link to info.
WC Namespaces is more of an XML convention rather than
/* scribe notes other discussions on this:
/* Brian has to leave, so discussed latest version of Bobby */
LK WC is there something that fully explains the namespaces proposal?
WC Yes, the discussions from Dan, but I'm not sure if it associates enough information, it focuses on links.
LK It is just a way of being able to use class names without conflicting with someone elses's use. But, it has nothing to do with "title." Therefore seems to be an independent issue. However, we could use the two together. Not an alternative but a parallel.
Action LK: add notes to draft to discuss :before and :after pseudo-elements to insert content. Then send on to WCAG and PF, also send heads-up to UA.
LK If there was a "title" property, is there another use in the general market place that would give it additional value? Tool tips?
WC Tool tip not a strong case, since lots of developers annoyed with tool tips and alt already.
HB We could then have a variety of titles for each element.
WC Sounds confusing and complex. How decide which one? Really need? Perhaps use it to create a link to the info contained within to simplify the page more. E.g. like frames: use the title as a link to the frame and handle each in their own "window." Good thing for mobile devices.
HB "http" duplicaiton.
BM Can clean up easily.
HB Webable is in cahoots w/you somehow.
BM It's on our news page. We've signed an agreement with them. Anytime someone says, "I don't have the time, can someone make them compliant?" We point them to webable. We can add others to the list.
LK Is this just a list that anyone wants to be added to?
BM We can make arrangements.
LK The question marks are links that don't go anywhere.
BM Went ahead and released. It's a bug.
LK Best just to make them inactive rather than have go nowhere.
BM good suggestion.
LK There are some pages that make the error of not wrapping javascript in comment, shows up in header.
BM We know about, but low priority.
LK At the top of some pages, you see javascript. When I see that, I think "Bobby's broken" although I know it is is problem with the page.
BM We haven't had many comments on that.
HB I was surprised when I saw it.
BM Good to know.
LK I will be sending these comments so we don't minute them in detail.
/* scribe relaxes a bit */
LK "user checks are not triggered."
BM Wording should be there.
LK On the page that I reviewed, the first 3 items did not have line numbers.
BM Not sure what to do about that. If we don't give a specific check, like "color contrast," we don't give line numbers.
LK So you have 3 categories:
BM, yes on 2, gets too overwhelming to present all instances. Adding "make sure that your alt-text is real" in the list of things to always check.
LK My concern is that you can pass Bobby with "garbage" alt-text, yet you don't want to clutter up the page.
LK What is "BA"?
BM Bobby approved. Isn't that described? This is the minimum to follow.
LK Advanced options could be missed. Search engines put it near the submit button.
BM Good idea. We could make it more noticeable.
LK Good to impersonate browsers, but can't do it completely accurately because of browser sniffing javascript tricks.
LK /* several more suggestions for cosmetics. will be sent as e-mail to the list */
HB HTML 4 check does not specify if it is strict, frame, or transitional.
BM Not checking DTD but tag list.
HB But tag list is different. Next release?
BM Couple months hope to clean up some bugs and rerelease.
/* discussion returns to classes */
WC I'm on vacation next week. We need a scribe for Monday. Then September 4 is a holiday, but we are scheduled to meet with AU on the 5th anyway.
Open: We need a scribe for the 28 August meeting.
Resolved: No meeting on 4 September, meet with UA on 5 September.
$Date: 2000/11/08 08:17:26 $ Wendy Chisholm | http://www.w3.org/WAI/ER/IG/2000/08/21-minutes.html | CC-MAIN-2015-22 | refinedweb | 1,206 | 86.5 |
How. In the Oracle database we will be having a table Employee Details with three columns Employee_ID, FirstName and LastName, having more than 10,000 data. Based on the Employee_ID we can search for the employees using this Silverlight search page.
Steps Involved:
Creating a Silverlight Application:
I. Open Visual Studio 2010.
ii. Go to File => New => Project.
iii. Select Silverlight from the Installed templates and choose the Silverlight Application template.
iv. Enter the Name and choose the location.
v. Click OK.
vi. In the New Silverlight Application wizard check the "Host the Silverlight Application in a new Web site".
vii. Click OK.
Adding WCF Service:
i. Right click on the asp.net website (in my case SilverlightApplicationSearchWebpartForOracle.web) which is automatically added to the Silverlight solution when we have created the Silverlight Application (If you check the Host the Silverlight application in a new Web site check box in the New Silverlight Application dialog box, an ASP.NET Web site is created and added to the Silverlight solution), select Add a new item.
ii. Select Web from the Installed templates and choose the WCF Service.
iii. Enter the Name for the service.
iv. Click OK.
v. Add the reference System.Data.OracleClient.
vi. Open IService1.cs.
vii. Replace the code with the following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel; | https://www.thetechplatform.com/post/how-to-connect-to-oracle-database-using-wcf-in-silverlight-1 | CC-MAIN-2022-21 | refinedweb | 230 | 52.56 |
Today, I conclude my story to your myths about C++. These myths are around function parameters, the initialisation of class members, and pointer versus references.
When a function takes its parameter and doesn't want to modify it, you have two options.
This was the correctness perspective, but what can be said about the performance. The C++ core guidelines is specific about performance. Let's look at the following example.
void f1(const string& s); // OK: pass by reference to const; always cheap
void f2(string s); // bad: potentially expensive
void f3(int x); // OK: Unbeatable
void f4(const int& x); // bad: overhead on access in f4()
Presumably, based on experience, the guidelines states a rule of thumb:
Okay, now you should know how big your data types are. The program sizeofArithmeticTypes.cpp gives the answers for arithmetic types.
// sizeofArithmeticTypes.cpp
#include <iostream>
int main(){
std::cout << std::endl;
std::cout << "sizeof(void*): " << sizeof(void*) << std::endl;
std::cout << std::endl;
std::cout << "sizeof(5): " << sizeof(5) << std::endl;
std::cout << "sizeof(5l): " << sizeof(5l) << std::endl;
std::cout << "sizeof(5ll): " << sizeof(5ll) << std::endl;
std::cout << std::endl;
std::cout << "sizeof(5.5f): " << sizeof(5.5f) << std::endl;
std::cout << "sizeof(5.5): " << sizeof(5.5) << std::endl;
std::cout << "sizeof(5.5l): " << sizeof(5.5l) << std::endl;
std::cout << std::endl;
}
sizeof(void*) returns if it is a 32-bit or a 64-bit system. Thanks to online compiler rextester, I can execute the program with GCC, Clang, and cl.exe (Windows). Here are the numbers for all 64-bit systems.
cl.exe behaves differently to GCC and Clang. A long int has only 4 bytes, and a long double has 8 bytes. On GCC and Clang, long int and long double have the double size.
To decide, when to take the parameter by value or by const reference is just math. If you want to know the exact performance numbers for your architecture, there is only one answer: measure.
First, let me show you initialisation and assignment in the constructor.
class Good{
int i;
public:
Good(int i_): i{i_}{}
};
class Bad{
int i;
public:
Bad(int i_): { i = i_; }
};
The class Good uses initialisation but the class Bad assignment. The consequences are:
The constructor initialisation is, on one hand, slower but does not work on the other hand for const members, references, or members which can not be default-constructed possible.
// constructorAssignment.cpp
struct NoDefault{
NoDefault(int){};
};
class Bad{
const int constInt;
int& refToInt;
NoDefault noDefault;
public:
Bad(int i, int& iRef){
constInt = i;
refToInt = iRef;
}
// Bad(int i, int& iRef): constInt(i), refToInt(iRef), noDefault{i} {}
};
int main(){
int i = 10;
int& j = i;
Bad bad(i, j);
}
When I try to compile the program, I get three different errors.
In the second successful compilation, I used the second commented out constructor which uses initialisation instead of assignment.
The example used references instead of raw pointers for a good reason.
Motivated by a comment from Thargon110, I want to be dogmatic: NNN. What? I mean No Naked New. From an application perspective, there is no reason to use raw pointers. If you need pointer like semantic, put your pointer into a smart pointer (You see: NNN) and you are done.
In essence C++11 has a std::unique_ptr for exclusive ownership and a std::shared_ptr for shared ownership. Consequently, when you copy a std::shared_ptr, the reference counter is incremented, and when you delete the std::shared_ptr, the reference counter is decremented. Ownership means, that the smart pointer keeps track of the underlying memory and releases the memory if it is not necessary any more. The memory is not necessary any more in the case of the std::shared_ptr when the reference counter becomes 0.
So memory leaks are gone with modern C++. Now I hear your complaints. I'm happy to destroy them.
The last complaint is quite dominant. The small example should make my point:
// moveUniquePtr.cpp
#include <algorithm>
#include <iostream>
#include <memory>
#include <utility>
#include <vector>
void takeUniquePtr(std::unique_ptr<int> uniqPtr){ // (1)
std::cout << "*uniqPtr: " << *uniqPtr << std::endl;
}
int main(){
std::cout << std::endl;
auto uniqPtr1 = std::make_unique<int>(2014);
takeUniquePtr(std::move(uniqPtr1)); // (1)
auto uniqPtr2 = std::make_unique<int>(2017);
auto uniqPtr3 = std::make_unique<int>(2020);
auto uniqPtr4 = std::make_unique<int>(2023);
std::vector<std::unique_ptr<int>> vecUniqPtr;
vecUniqPtr.push_back(std::move(uniqPtr2)); // (2)
vecUniqPtr.push_back(std::move(uniqPtr3)); // (2)
vecUniqPtr.push_back(std::move(uniqPtr4)); // (2)
std::cout << std::endl;
std::for_each(vecUniqPtr.begin(), vecUniqPtr.end(), // (3)
[](std::unique_ptr<int>& uniqPtr){ std::cout << *uniqPtr << std::endl; } );
std::cout << std::endl;
}
The function takeUniquePtr in line (1) takes a std::unique_ptr by value. The key observation is that you have to move the std::unique_ptr inside. The same argument holds for the std::vector<std::unique_ptr<int>> (line 2). std::vector as all containers of the standard template library wants to own its elements but to copy a std::unique_ptr is not possible. std::move solves this issue. You can apply an algorithm such as std::for_each on the std::vector<std::unique_ptr<int>> (line 3) if no copy semantic is used.
On the end, I want to refer to the key concern of Thargon110. Admittedly, this rule is way more import in classical C++ without smart pointers because smart pointers are in contrast to raw pointers owners.
Use a reference instead of a pointer because a reference has always a value. Boring checks such as the following one are gone with references.
if(!ptr){
std::cout << "Something went terrible wrong" << std::endl;
return;
}
std::cout << "All fine" << std::endl;
Additionally, you can forget the check. References behave just as constant pointers.
The C++ core guidelines defines profiles. Profiles are subset of rules. They exist for type safety, bounds safety, and lifetime safety. They will be my next topic.20
Yesterday 8573
Week 9594
Month 168025
All 5037339
Currently are 130 guests and no members online
Kubik-Rubik Joomla! Extensions
Read more...
Read more... | https://www.modernescpp.com/index.php/more-myths-of-my-blog-readers | CC-MAIN-2020-50 | refinedweb | 1,003 | 57.27 |
On Tue, 22 Sep 2009, Joe Perches wrote:> On Tue, 2009-09-22 at 10:38 -0700, Sage Weil wrote:> > These headers describe the types used to exchange messages between the> > Ceph client and various servers. All types are little-endian and> > packed.> []> > diff --git a/fs/ceph/ceph_fs.h b/fs/ceph/ceph_fs.h> > new file mode 100644> > index 0000000..15150fc> > --- /dev/null> > +++ b/fs/ceph/ceph_fs.h> []> > +static inline __u32 frag_make(__u32 b, __u32 v)> > +{> > + return (b << 24) |> > + (v & (0xffffffu << (24-b)) & 0xffffffu);> > +}> > frag_<foo> inlines might have a conflict with ipv6I'll prefix those with 'ceph_'.> > +static inline const char *ceph_mds_state_name(int s)> > +{> > + switch (s) {> []> > + case CEPH_MDS_STATE_STOPPING: return "up:stopping";> > + default: return "";> > + }> > + return NULL;> > +}> > inline?> > It's probably better not to use inlines here> as the strings could be duplicated unnecessarily.Agreed. They were easier to maintain that way when the constants changed frequently, but they can be uninlined now.Thanks!sage | http://lkml.org/lkml/2009/9/22/442 | CC-MAIN-2015-22 | refinedweb | 155 | 57.16 |
TestNG Tutorial: This post, we are going to share the complete TestNG tutorials for both fresher and experienced testers. TestNG is an automation testing framework where NG stands for “Next Generation.”
It is an open-source testing framework, and also it is inspired by the JUnit and NUnit. But TestNG has introduced some new functionality which makes this framework is more powerful and easy to use.
TestNG Tutorial In Selenium WebDriver
In this tutorial post, we are going to discuss things like:
- Why Should we use TestNG
- How to Install TestNG
- How to Create a first test Case using TestNG
- How to Create a Test Suite
- Understanding on TestNg.xml
- Package Tag in TestNG. Xml
The above topics we are going to discuss one by one in detail. i hope after going through with all those topics, you have a clear idea, and also, you know how you can use testNG.xml in your Selenium automation framework with Selenium WebDriver.
Why Should We Use TestNG Framework?
In our previous post, we have written so many automation scripts during the discussion of various topics of Selenium WebDriver. If you have noticed in all last example, we have written all the script inside the main method. To execute any particular script, we are executing the specific method of that class.
Let us take a real-time scenario of your automation framework where you can find more then 50+ automation test scripts are available. But let’s think about the below scenarios:
- Lets your requirement is run all those test scripts at a time, then, in that case, you need to write a separate runner class where you can call the main method of each script class. During the execution of those scripts, if you want to stop or continue your script execution, then its very much complicated.
- Out of all those scripts, if you want to run some specific test scripts or based on some condition if you’re going to run some particular script, then for that, you need to write manual lots of codes.
- Each test cases have some prerequisites and post requisites. To achieve this again, you need to write lots of code, and some times you need to write the same code repeatedly.
- If some scripts are dependent on some other scripts, then its very much complicated to handle this type of scenario.
- If you need to send your execution report after each execution, then for report generation again, you need to write a bunch of codes.
The above are the typical scenario that you face while writing the automation scripts, and to achieve this, we need to spend lots of time and also need extra coding effort. So at that time, if you have found something which has already had those features and no need for additional coding, then that will save you lots of time and effort too.
To solve those problems, we can use the TestNG with our script by simply plug-in or adding that with our automation script. Its just like Selenium, which means by using Selenium WebDriver, we can operate Launch the browser, loading a URL without writing any extra codes on our own. Like this, TestNG also comes in the form of Jar. Once we have added to our framework, then we will get lots of predefined ready-made functionalities, and we can use those functionalities.
Key Points Of TestNG Framework
- TestNG is a testing framework which mainly designed for Unit Testing purposes, but today its used for all types of testing.
- When it was develope, that time majorly concentrate on simplifying the different testing like System Testing or Unit Testing.
- TestNG is an open-source framework that is inspired by the JUnit & NUnit.
- You can use this for any testing that may be a Web Application Testing or API Testing.
Features of TestNG Framework
TestNG support so many powerful features and also easy to sue. So we have listed some of the TestNG noteworthy features below:
- Logs can be generated.
- It provides annotation, which makes the code efficient and easy to manage.
- You can include or exclude any test method from execution by using attributes.
- Supports parallel testing of the application
- Support parameterization, we can achieve this by using the parameter tag.
- It Supports Data-Driven Testing using @DataProvider
- You can set the priorities so that test methods will be executed in order.
- You can easily integrate various tools like build tools (Maven) & different IDE like (Eclipse).
- Supported different Annotations like @BeforeSuite, @AfterSuite, @BeforeClass, @AfterClass, @BeforeTest, @AfterTest, @BeforeGroups, @AfterGroups, @BeforeMethod, @AfterMethod, @DataProvider, @Factory, @Listeners, @Parameters, @Test.
Advantages of TestNG over JUnit
TestNG most popular then JUnit because its more rich functionality and features, so we have listed functions below:
- TestNG annotation are easy to understand as compare to the JUnit annotations.
- There are constraints like you have to declare the @BeforeClass and @AfterClass, but when it comes to TestNG, there is no such restriction.
- You can not be grouping test cases in JUnit, but you can do that with the TestNG.
How to Install TestNG in Eclipse?
We have made a separate post to make this post informative and straightforward. You can check how to Install TestNG in Eclipse by following this link.
How to Create a First Test Case with TestNG?
There is nothing much different between a Java class and a TestNG class. In TestNg class, you need to use the @test annotation in the place of the main() method. In Java programming language The JVM will start the execution from the Main method, but in TestNG, the execution will begin from the @test annotation. You can follow our article on how to write your first test case using TestNG.
How to Create Test Suite?
Above, we have seen how to create a test case using TestNG. There we have seen how to run the test case using the “Run as” option. When you want to run a set of test cases together, we can do that by generating a test suite. Follow this link to learn how you can create a test suite.
Understanding of TestNG.xml
You have seen when we are creating a test suite, an XML file generated. In the XML file, there are five levels is there & that is:
- Suite
- Test
- Class
- Classes
- Method
Internal Logic Of Generation Of TestNG.xml
When we are creating the testng.xml file for a class or package or project, you will see that only those classes are available inside the xml file, which has one or more @test annotated methods.
package TestNGPrograms; public class NoTestMethod { public void doNothing() { System.out.println(" Do nothing"); } }
If we are tr to create an xml file for this class then the XML file should be looking something like below:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM ""> <suite name="Suite"> <test thread-</test> <!-- Test --> </suite> <!-- Suite -->
As the above java file does not have any @test annotated method, that’s why the XMl file does not have a class tag.
If the class have annotation like @BeforeClass or @BeforeSuite etc. in a class then also the xml file ignore those classes. Because as there is no @test annotated method, then TestNG finds out there is nothing to test in that class, that’s why it ignores those classes.
Note: So testng.xml will include only those classes which have at least one @Test annotated method in it.
Package Tag In TestNG
When we are discussing the different tags in the testng.xml file at that time, we have mentioned that there is a 4 level of tags are available. But apart from those 5, one more tag is present that’s package tag.
As earlier, we have mentioned that if all the classes have the @test annotation and you generate the testng.xml file, then all the class comes inside the classes tag. Similarly, if there are multiple packages are present with multiple classes, and you create the testng.xml file also all the class of different packages comes under one classes tag, but inside the class tag, you will find the class name mentioned with the respective_packagename.class_name Format.
But the main problem here is a different class of each package is not in order, so it is very much difficult to find a class from a specific package. To solve such type of problem in TestNG we have another tag called <packages> & <package> tag.
With the help of using this <packages> & <package> tag we can categorize or group all different package under <packages> tag and all different classes of a package under <package> tag.
So to create such a testng.xml file with package tag, you need to select the “packages” from the Class selection drop-down window. Then it will include all the classes of those packages in the test suite.
Note: Here, you will not get any option to select the classes for a run when you are using the package option.
If you want to include all classes or packages, then you can mention this in the test suite:
For Packages:
<packages> <package name=".*" /> </packages>
For Classes:
<classes> <class name=".*" /> </classes>
Note: If you’re going to run all the classes by using a test suite and you have used the above technique, then you will get a TestNG Exception because it will search for a class with class name .*. So, in that case, you can use the package tag to run all the classes of a specific package.
How to Deal Sub packages In TestNG?
We created packages created for grouping similar types of classes or interfaces. In the same way, we can create the sub-packages. But it is important to deal with the sub-packages because when we are creating the test suite for the main packages, you can find out that it only adds the classes of main packages and ignoring the sub-packages classes.
Similarly, if you will create a testng.xml file for the sub-package, then it will add only the subpackage classes and will ignore the main package classes.
So you can add all the classes of the main package and sub-packages in two ways:
- By Selecting The Project
- By including all package using the <packages> and <package> tag.
By Selecting The Project
For all classes of main package and subpackage, right-click on the project name and generate the testng.xml file.
By Manually Including Packages
As we have discussed, you can add all the classes manually by mentioning inside the <classes> tag and the class name mentioning package hierarchy.class_name;
How to Run Inner TestNG Class from the main testNG.xml?
Suppose there is a Java Class which have an inner class, like below:
package InnerClassPackage; import org.testng.annotations.Test; public class OuterClass { @Test public void outerMethod() { System.out.println("Outer"); } class InnerClass { @Test public void innerMethod() { System.out.println("Inner"); } } }
Now let us create a testng.xml for this and try to run. As we can see that we got a TestNGException by mentioning, “Cannot find the class in classpath.” It means it is not able to find the inner class.
So to handle such types of issues, we can take the help of <package> tag. So let us create a testng.xml file with the package option and try to run.
How to use Interface With TestNG?
Let’s Create an Interface with @test annotation:
package TestNGInterface; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public interface InterfaceTestNGMethods { // TestNG annotated methods in an Interface @BeforeTest public void beforeTestMethod(); @Test public void testMetho() ; @BeforeTest public void afterTestMethod(); }
Let’s create a testng.xml file and run it. As a result, we can say that the result becomes total test run=0, failures=0, and skips=0.
Now let us update the above interface with the default and static method:
package TestNGInterface; import org.testng.annotations.Test; public interface InterfaceTestNGMethods { // TestNG annotated methods in an Interface @Test public static void staticMethod() { System.out.println("Static method"); } @Test public default void DefaultMethod() { System.out.println("Default Method"); } }
Now, let’s run the updated interface again and check the result. This time also we are getting the same result, which is total test run=0, failures=0, and skips=0.
Now we will try to implement the interface in a class, like below:
package TestNGInterface; import org.testng.annotations.Test; public class DriverClass implements InterfaceTestNGMethods { @Test public void DriverClassMethod() { System.out.println("Driver class method"); } }
For one more time, prepare the test suite having both interface and implemented class and run that.
For this time, we can see both interfaces and implemented class methods got executed.
Note: An interface can have TestNG annotated methods, but those interface methods can only be executed once those implemented. If an interface has fully implemented default and static method, also if you run them, those will be executed, not gives you any errors.
More Articles About TestNG Tutorial:
- How to Install TestNG
- First Test Case Using @TestNG
- Different TestNG Annotation
- Different TestNG Attributes
- @Test Annotation
- Priority Attributes
- Timeout Attributes
- Always Run Attribute
- TestNG expectedException Attribute
- TestNG Dependency
- Parameterization In TestNG
- How to do parallel test execution using TestNG
- TestNG Assertions
- TestNG Groups
- TestNG Inheritance
- TestNG Method Overloading
- TestNG Overriding
- TestNG Method with return Statement
- DataProvider in TestNG
- @Factory Annotation In TestNG
- DataProvider VS Factory
- TestNG Listeners
- ITestContext in TestNG
- TestNG Report
- How to Use Extent Report
- Execute TestNG Command Prompt
I hope this article helps you know the Basic things about the TestNG. If you enjoy reading this article, then you can help us by sharing this article link with your friends so that they can also benefit. If there are any Tips/suggestions or questions, then you can drop in the comment section, and we are happy to reply ASAP. | https://www.softwaretestingo.com/testng-tutorial/ | CC-MAIN-2019-51 | refinedweb | 2,306 | 62.17 |
When new Python syntax is introduced, the usual approach will be to give both specific examples and general templates. In general templates for Python syntax the typeface indicates the the category of each part:
A more complete example of using this typography with several parts would be a description of an assignment statement:
variableName = someExpression
with an arbitrary identifier, the specific symbol =, and an expression.
I try to make the parts that are not verbatim to be descriptive of the expected use.
We will use these conventions shortly in the discussion of function syntax, and will continue to use the conventions throughout the tutorial.
If you know it is the birthday of a friend, Emily, you might tell those gathered with you to sing “Happy Birthday to Emily”.
We can make Python display the song. Read, and run if you like, the example program birthday1.py:
print("Happy Birthday to you!") print("Happy Birthday to you!") print("Happy Birthday, dear Emily.") print("Happy Birthday to you!")
You would probably not repeat the whole song to let others know what to sing. You would give a request to sing via a descriptive name like “Happy Birthday to Emily”.
In Python we can also give a name like happyBirthdayEmily, and associate the name with whole song by using a function definition. We use the Python def keyword, short for define.
Read for now:
There are several parts of the syntax for a function definition to notice:
Line 1: The heading contains def, the name of the function, parentheses, and finally a colon. A more general syntax is
def function_name():
Lines 2-5: The remaining lines form the function body and are indented by a consistent amount. (The exact amount is not important to the interpreter, though 2 or 4 spaces are common conventions.)
The whole definition does just that: defines the meaning of the name happyBirthdayEmily, but it does not do anything else yet - for example, the definition itself does not make anything be printed yet. This is our first example of altering the order of execution of statements from the normal sequential order.
Note
The statements in the function definition are not executed as Python first passes over the lines.
The code above is in example file birthday2.py. Load it in Idle and execute it from there. Nothing should happen visibly. This is just like defining a variable: Python just remembers the function definition for future reference.
After Idle finished executing a program, however, its version of the Shell remembers function definitions from the program.
In the Idle Shell (not the editor), enter
happyBirthdayEmily
The result probably surprises you! When you give the Shell an identifier, it tells you its value. Above, without parentheses, it identifies the function code as the value (and gives a location in memory of the code). Now try the name in the Idle Shell with parentheses added:
happyBirthdayEmily()
The parentheses tell Python to execute the named function rather than just refer to the function. Python goes back and looks up the definition, and only then, executes the code inside the function definition. The term for this action is a function call or function invocation.
Note
In the function call there is no def, but there is the function name followed by parentheses.
function_name()
In many cases we will use a feature of program execution in Idle: that after program execution is completed, the Idle Shell still remembers functions defined in the program. This is not true if you run a program by selecting it directly in the operating system.
Look at the example program birthday3.py. See it just adds two more lines, not indented. Can you guess what it does? Try it:
The execution sequence is different from the textual sequence:
Functions alter execution order in several ways: by statements not being executed as the definition is first read, and then when the function is called during execution, jumping to the function code, and back at the the end of the function execution.
If it also happens to be Andre’s birthday, we might define a function happyBirthdayAndre, too. Think how to do that before going on ....
Here is example program birthday4.py where we add a function happyBirthdayAndre, and call them both. Guess what happens, and then try it:
'''Function definitions and invocation.''' def happyBirthdayEmily(): print("Happy Birthday to you!") print("Happy Birthday to you!") print("Happy Birthday, dear Emily.") print("Happy Birthday to you!") def happyBirthdayAndre(): print("Happy Birthday to you!") print("Happy Birthday to you!") print("Happy Birthday, dear Andre.") print("Happy Birthday to you!") happyBirthdayEmily() happyBirthdayAndre()
Again, everything is definitions except the last two lines. They are the only lines executed directly. The calls to the functions happen to be in the same order as their definitions, but that is arbitrary. If the last two lines were swapped, the order of operations would change. Do swap the last two lines so they appear as below, and see what happens when you execute the program:
happyBirthdayAndre() happyBirthdayEmily()
Functions that you write can also call other functions you write. It is a good convention to have the main action of a program be in a function for easy reference. The example program birthday5.py has the two Happy Birthday calls inside a final function, main. Do you see that this version accomplishes the same thing as the last version? Run it. :
If we want the program to do anything automatically when it is runs, we need one line outside of definitions! The final line is the only one directly executed, and it calls the code in main, which in turn calls the code in the other two functions.
Detailed order of execution:
There is one practical difference from the previous version. After execution, if we want to give another round of Happy Birthday to both persons, we only need to enter one further call in the Shell to:
main()
As a simple example emphasizing the significance of a line being indented, guess what the the example file order.py does, and run it to check:
def f(): print('In function f') print('When does this print?') f()
Modify the file so the second print function is outdented like below. What should happen now? Try it:
def f(): print('In function f') print('When does this print?') f()
The lines indented inside the function definition are remembered first, and only executed when the function f is invoked at the end. The lines outside any function definition (not indented) are executed in order of appearance., Python.
Python works something like that, but with its own syntax. The term “person’s name” serves as a stand-in for the actual data that will be used, “Emily”, “Andre”, or “Maria”. This is just like the association with a variable name in Python. “person’s name” is not a legal Python identifier, so we will use just person as this stand-in.
The function definition indicates that the variable name person will be used inside the function by inserting it between the parentheses of the definition. Then in the body of the definition of the function, person is used in place of the real data for any specific person’s name. Read and then run example program birthday6.py:
In the definition heading for happyBirthday, person is referred to as a formal parameter. This variable name is a placeholder for the real name of the person being sung to.
The last two lines of the program, again, are the only ones outside of definitions, so they are the only ones executed directly. There is now an actual name between the parentheses in the function calls. The value between the parentheses here in the function call is referred to as an argument or actual parameter of the function call. The argument supplies the actual data to be used in the function execution. When the call is made, Python does this by associating the formal parameter name person with the actual parameter data, as in an assignment statement. In the first call, this actual data is 'Emily'. We say the actual parameter value is passed to the function. [1]
The execution in greater detail:
Lines 3-7: Definition remembered
Line 9: Call to happyBirthday, with actual parameter 'Emily'.
Line 3: 'Emily' is passed to the function, so person = 'Emily'.
Lines 4-7: The song is printed, with 'Emily' used as the value of person in line 4: printing
Happy Birthday, dear Emily.
End of line 9 after returning from the function call
Line 10: Call to happyBirthday, this time with actual parameter 'Andre'
Line 3: 'Andre' is passed to the function, so person = 'Andre'.
Lines 4-7: The song is printed, with 'Andre' used as the value of person in line 4: printing
Happy Birthday, dear Andre.
End of line 10 after returning from the function call, and the program is over.
Note
Be sure you completely understand birthday6.py and the sequence of execution! It illustrates extremely important ideas that many people miss the first time!
It is essential to understand the difference between
The beauty of this system is that the same function definition can be used for a call with a different actual parameter, and then have a different effect. The value of the formal parameter person is used in the third line of happyBirthday, to put in whatever actual parameter value was given.
Note.
You can go back to having a main function again, and everything works. Run birthday7.py:
'''Function with parameter called in main''' def happyBirthday(person): print("Happy Birthday to you!") print("Happy Birthday to you!") print("Happy Birthday, dear " + person + ".") print("Happy Birthday to you!") def main(): happyBirthday('Emily') happyBirthday('Andre') main()
In birthday6.py, the function calls in lines 9 and 10 were outside any function definition, so they did actually lead to immediate execution of the function. In birthday7.py the calls to happyBirthday are inside another function definition (main), so they are not actually run until the function main is run (from the last line, outside any function).
See Birthday Function Exercise.
We can combine function parameters with user input, and have the program be able to print Happy Birthday for anyone. Check out the main method and run birthday_who.py:
This last version illustrates several important ideas:
Now that we have nested function calls, it is worth looking further at tracebacks from execution errors. If I add a line to main in birthday7.py:
happyBirthday(2)
as in example file birthdayBad.py, and then run it, you get something close to:
Traceback (most recent call last):File “/hands-on/../examples/birthdayBad.py”, line 15, in <module>main()File “/hands-on/../examples/birthdayBad.py”, line 13, in mainhappyBirthday(2)File “/hands-on/../examples/birthdayBad.py”, line 6, in happyBirthdayprint(“Happy Birthday, dear ” + person + ”.”)TypeError: Can’t convert ‘int’ object to str implicitly
Your file folder is probably different than /hands-on/examples. The last three lines are most important, giving the line number where the error was detected, the text of the line in question, and a description of what problem was found. Often that is all you need to look at, but this example illustrates that the genesis of the problem may be far away from the line where the error was detected. Going further up the traceback, you find the sequence of function calls that led to the line where the error was detected. You can see that in main I call happyBirthday with the bad parameter, 2.
Make your own further change to birthday7.py and save it as birthdayMany.py: Add a function call (but not another function definition), so Maria gets a verse, in addition to Emily and Andre. Also print a blank line between verses. (You may either do this by adding a print line to the function definition, or by adding a print line between all calls to the function.)
A function can have more than one parameter in a parameter list separated by commas. Here the example program addition5.py changes example program addition4a.py, using a function to make it easy to display many sum problems. Read and follow the code, and then run:
'''Display any number of sum problems with a function. Handle keyboard input separately. ''' def sumProblem(x, y): sum = x + y sentence = 'The sum of {} and {} is {}.'.format(x, y, sum) print(sentence) def main(): sumProblem(2, 3) sumProblem(1234567890123, 535790269358) a = int(input("Enter an integer: ")) b = int(input("Enter another integer: ")) sumProblem(a, b) main()
The actual parameters in the function call are evaluated left to right, and then these values are associated with the formal parameter names in the function definition, also left to right. For example a function call with actual parameters, f(actual1, actual2, actual3), calling a function f with definition heading:
def f(formal1, formal2, formal3):
acts approximately as if the first lines executed inside the called function f were
formal1 = actual1 formal2 = actual2 formal3 = actual3
Functions provide extremely important functionality to programs, allowing tasks to be defined once and performed repeatedly with different data. It is essential to see the difference between the formal parameters used to describe what is done inside the function definition (like x and y in the definition of sumProblem) and the actual parameters (like 2 and 3 or 1234567890123 and 535790269358) which substitute for the formal parameters when the function is actually executed. The main method above uses three different sets of actual parameters in the three calls to sumProblem.
The example addition5.py is a modification of addition4a.py, putting the arithmetic problem into a function and then calling the function several times with different parameters. Similarly modify quotientformat.py from Quotient Format Exercise and save it as quotientProb.py. You should create a function quotientProblem with numerical parameters. Like in all the earlier versions, it should print a full sentence with input, quotient, and remainder. The main method in the new program should test the quotientProblem function on several sets of literal values, and also test the function with input from the user.
You probably have used mathematical functions in algebra class, but they all had calculated values associated with them. For instance if you defined
f(x)=x2
then it follows that f(3) is 32, and f(3)+f(4) is 32 + 42
Function calls in expressions get replaced during evaluation by the value of the function.
The corresponding definition and examples in Python would be the following, taken from example program return1.py. Read and run:
'''A simple function returning a value, used in an expression''' def f(x): return x*x print(f(3)) print(f(3) + f(4))
The new Python syntax is the return statement, with the word return followed by an expression. Functions that return values can be used in expressions, just like in math class. When an expression with a function call is evaluated, the function call is effectively replaced temporarily by its returned value. Inside the Python function, the value to be returned is given by the expression in the return statement.
After the function f finishes executing from inside
print(f(3))
it is as if the statement temporarily became
print(9)
and similarly when executing
print(f(3) + f(4))
the interpreter first evaluates f(3) and effectively replaces the call by the returned result, 9, as if the statement temporarily became
print(9 + f(4))
and then the interpreter evaluates f(4) and effectively replaces the call by the returned result, 16, as if the statement temporarily became
print(9 + 16)
resulting finally in 25 being calculated and printed.
Python functions can return any type of data, not just numbers, and there can be any number of statements executed before the return statement. Read, follow, and run the example program return2.py:
The code above has a new feature, variables separator and result are given a value inside the function, but separator and result are not among the formal parameters. The assignments work as you would expect here. More on this shortly, in Local Scope.
Details of the execution:
Compare return2.py and addition5.py, from the previous section. Both use functions. Both print, but where the printing is done differs. The function sumProblem prints directly inside the function and returns nothing explicitly. On the other hand lastFirst does not print anything but returns a string. The caller gets to decide what to do with the string, and above it is printed in the main program.
Open addition5.py again, and introduce a common mistake. Change the last line of the function main inserting print, so it says
print(sumProblem(a, b))
Then try running the program. The desired printing is actually done inside the function sumProblem. You introduced a statement to print what sumProblem returns. Although sumProblem returns nothing explicitly, Python does make every function return something. If there is nothing explicitly returned, the special value None is returned. You should see that in the Shell output. This is a fairly common error.
Warning
If you see a ‘None’ is your printed output where you do not expect it, it is likely that you have printed the return value of a function that did not return anything explicitly!
In general functions should do a single thing. You can easily combine a sequence of functions, and you have more flexibility in the combinations if each does just one unified thing. The function sumProblem in addition5.py does two things: It creates a sentence, and prints it. If that is all you have, you are out of luck if you want to do something different with the sentence string. A better way is to have a function that just creates the sentence, and returns it for whatever further use you want. Printing is one possibility, done in addition6.py:
'''Display a sum problems with a function returning a string, not printing directly. ''' def sumProblemString(x, y): sum = x + y return 'The sum of {} and {} is {}.'.format(x, y, sum) def main(): print(sumProblemString(2, 3)) print(sumProblemString(1234567890123, 535790269358)) a = int(input("Enter an integer: ")) b = int(input("Enter another integer: ")) print(sumProblemString(a, b)) main()
Create quotientReturn.py by modifying quotientProb.py in Quotient Function Exercise so that the program accomplishes the same thing, but everywhere change the quotientProblem function into one called quotientString that merely returns the string rather than printing the string directly. Have the main function print the result of each call to the quotientString function.
The Python.
For the logic of writing functions, it is important that the writer of a function knows the names of variables inside the function. On the other hand, if you are only using a function, maybe written by someone unknown to you, you should not care what names are given to values used internally in the implementation of the function you are calling. Python enforces this idea with local scope rules: Variable names initialized and used inside one function are invisible to other functions. Such variables are called local variables. For example, an elaboration of the earlier program return2.py might have its lastFirst function with its local variable separator, but it might also have another function that defines a separator variable, maybe with a different value like '\n'. They would not conflict. They would be independent. This avoids lots of errors!
For example, the following code in the example program badScope.py causes an execution error. Read it and run it, and see:
'''program causing an error with an undefined variable''' def main(): x = 3 f() def f(): print(x) # error: f does not know about the x defined in main main()
We will fix this error below. The execution error message mentions “global name”. Names defined outside any function definition, at the “top-level” of your program are called global. They are a special case. They are discussed more in the next section.
If you do want local data from one function to go to another, define the called function so it includes parameters! Read and compare and try the program goodScope.py:
'''A change to badScope.py avoiding any error by passing a parameter''' def main(): x = 3 f(x) def f(x): print(x) main()
With parameter passing, the parameter name x in the function f does not need to match the name of the actual parameter in main. The definition of f could just as well have been:
def f(whatever): print(whatever)
If you define global variables (variables defined outside of any function definition), they are visible inside all of your functions. They have global scope. It is good programming practice to avoid defining global variables and instead to put your variables inside functions and explicitly pass them as parameters where needed. One common exception is constants: A constant is a name that you give a fixed data value to, by assigning a value to the name only in a single assignment statement. You can then use the name of the fixed data value in expressions later. A simple example program is constant.py:
'''Illustrate a global constant being used inside functions.''' PI = 3.14159265358979 # global constant -- only place the value of PI is set def circleArea(radius): return PI*radius*radius # use value of global constant PI def circleCircumference(radius): return 2*PI*radius # use value of global constant PI def main(): print('circle area with radius 5:', circleArea(5)) print('circumference with radius 5:', circleCircumference(5)) main()
This example uses numbers with decimal points, discussed more in Decimals, Floats, and Floating Point Arithmetic. By convention, names for constants are all capital letters.
Issues with global variables do not come up if they are only used as constants.
Function names defined at the top-level also have global scope. This is what allows you to use one function you defined inside another function you define, like calling circleArea from inside main. | http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/functions.html | CC-MAIN-2016-22 | refinedweb | 3,658 | 55.34 |
0
So I've been trying to make a VERY simple calculator program, but I tried so many things, and all of my methods failed. I've been at this for weeks, and I'm pretty frustrated up to this point. Nothing calls back on the entry box correctly, and although at certain points I was able to make numbers appear on the entry widget, I couldn't interact with them (e.g. add, subtract, etc.)
For now, I'm trying to make my program add 1+1 so it'll equal 2. However, Python IDLE is telling me that I have indentation problems. As far as I know, everything looks fine. I also copied bits of another calculator program elsewhere. If anyone knows a detailed source on entry boxes, please let me know. Thanks in advance!
from Tkinter import * root=Tk() class Calculator(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() display = StringVar() ent=Entry(self, textvariable=display).pack(side=TOP) self.onebutton=Button(self, text="1", command=self.number).pack() self.twobutton=Button(self, text="2", command=self.number).pack() self.eqlbutton=Button(self, text="=", command=self.equal).pack() def number(self, event): lambda w=display, s=' %s '%text:w.set(w.get() + s)) def equal(self, event): lambda e, s=self, w=display: s.calc(w), '+') def calc(self, display): try: display.set(eval(display.get())) except: display.set("ERROR") Calculator().mainloop() | https://www.daniweb.com/programming/software-development/threads/90614/completely-lost-with-entry-widget | CC-MAIN-2017-43 | refinedweb | 239 | 53.88 |
code not working properly
code not working properly protected void doPost(HttpServletRequest...);
String target="jsp/hrms_default.jsp";
String action... from the jsp page */
System.out.println("inside action_submit
output not coming properly - JSP-Servlet
Here i am showing the source code of above jsp...output not coming properly I am not getting the output properly when i had written my code like below:
Add Employee Details
calender working in struts - Struts
calender working in struts when i execute the following code ,that is working properly
if i convert to struts html tags that code is not working
please help me to rectify the problem
Not get ans properly
name (e.g emp)
6. Click "Ok" and then compile the following java code.
import
JTable values are not gettiing properly
but not 9.i.e a[0][0]=8
a[0][1]= (nothing printed)
Please go through my code
jsp code - JSP-Servlet
;
}
}
Thanks its not working properly....In second row it is not showing...jsp code i want to add and remove rows dynamically ... in that row 3... colum. Hi Friend,
Try the following code:
Add/Remove
Sql querry not working
of slabs.
CBID is cutblock ID.
My code:
ResultSet rc=st.executeQuery("select... should get ROWCOUNT:1
For the first two times my query is getting executed properly
how to display jsp page containing mysql query in particular division using ajax ?my code is below bt i cundt get it properly
how to display jsp page containing mysql query in particular division using ajax ?my code is below bt i cundt get it properly index.html
<... will display here</div>
</body>
</html>
print("code sample...(""+value+""
);
print("code sample
Struts validation not work properly - Struts
================================
JSP for exampleForm
Name
Database connectivity with jsp code - JSP-Servlet
Database connectivity with jsp code I have written a program in java having connectivity with online_exam. Its working properly. Connection has been established and the code in java is showing the output. But the problem :
Why is this code working
Why is this code working Looking at this piece of code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _point{
int x;
int y;
} point;
int main (void)
{
point *ptr;
point obj
Datagrid not working
Datagrid not working The code here is working fine, apart from the fact that that I'm using netbeans 6.5 and the servlet v2.5 and struts 1.1.... working. please help me out
Working with sessions
the saved data to the user in another page.
Here is the code of the JSP file... Working with sessions
This JSP Tutorial
logout code in JSP
logout code in JSP im using session.invalidate() for logout but its not working
html dropdown not working firefox
html dropdown not working firefox I am writing a Dropdown code in HTML which is not working in firefox. What could be the reason as it's perfectly working in IE and Crome.
Thanks
Code Works - JSP-Servlet
Code Works Hi
The code provided is working fine along with the pagination . i edited the queries and that makes difference..
here is the code.
Thank you
Regards
Eswaramoorthy
Pagination of JSP page
myJSF,Hibernate and Spring integration code is not working. - Hibernate
myJSF,Hibernate and Spring integration code is not working. the code given in this url :
i have tried but it does not work.
when i write
Dynamic-update not working in Hibernate.
Dynamic-update not working in Hibernate. Why is dynamic update not working in hibernate?
Dynamic-update is not working. It means when... am giving you a small block of code for updating of employee detail-
public
working of a div tag in html
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "...;
This is a simple code. but after executing it i am not getting the sentence
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 have split a string by space ,done some operation and now how to properly order them for sending a mail in java or jsp - JSP-Servlet
i have split a string by space ,done some operation and now how to properly... a text area in that i typed a some matter this is in one jsp .Then i got that matter in another jsp and stored in a string using getParameter(),then i splitted
Working Example for Spring AOP - Spring
Working Example for Spring AOP Hi All,
I need a complete working Java example /Code/Logic for Spring -Aspect Oriented Programming.
Code provided will be highly appreciated.
--
Deepak Lal
Working With Alignment Using JSP for Excel
Working with alignment using jsp for excel
In this program we are going to set... alignments.
The code of the program is given below:
<
Session Problem in JSP - JSP-Servlet
normally from Remote machine by only writing JSP code. Hi friend... in JSP platform. I have created normal session in JSP page. It is running in my machine properly, but when I am trying to access it from another machine
stuts java script validation is not working.
stuts java script validation is not working. --of jsp page--
Enter name:
Enter pass:
<html:submit/>
--of validation.xml--
<form name="logonForm">
<
File Upload - JSP-Servlet
multiple file upload code of roseindia is working on localhost but the same code is not working on server.i think the package commons-fileupload-1.2.jar is not properly working on server.why this is heppening.any help will be greatly.
jsp
the request. Check your code properly...jsp when i run jsp program it shows error-500 what is that error
my source code is
<% page import="java.sql.*" %>
<%!
Connection
to enter some value....all these which worked earlier is not properly working now ,i didnot change the code,then what would be the reason?? Hi... compatibility (some time some Scripting code works in one browser and not in other
Why are my variables not dividing properly?
Why are my variables not dividing properly? Why are my variables not dividing properly
jsp - JSP-Servlet
;
}
}
Thanks it is not working properly... in second row... the following code:
Add/Remove dynamic rows in HTML table
var i=0,j=0,sum/servlet login program - JSP-Servlet
the example it is working properly. If it arises problem on your system just try...jsp/servlet login program hello sir,
well i have a problem with some code(loginbean.jsp),which i actually got from ur site:
i am trying to create
jsp - Java Beginners
start working on it here at :... Program.
1. Write your JSP code or find it from the above given link and write... is not working.
Check it and run your server properly.
and then run your file - JSP-Servlet
and third colum shows sum of that 2 colum...
for that i have below code but when i will add new row than it is not working properly.. it is not showing sum...;
}
}
Hi Friend,
Try the following code");
< | http://www.roseindia.net/tutorialhelp/comment/36592 | CC-MAIN-2014-49 | refinedweb | 1,187 | 66.64 |
Lecture 2 – The Gospel of John, part 2
Card Set Information
Author:
crunchybunnies27
ID:
150770
Filename:
Lecture 2 – The Gospel of John, part 2
Updated:
2012-04-28 19:18:04
VLI John Gospel
Folders:
Description:
Lecture 2 – The Gospel of John, part 2
Show Answers:
List (in one phrase each) the main story lines of the Gospel of John taught in the lectures.
1. The cosmic spiritual battle, launched in heaven, but fought on earth, is between light and darkness
2. Life
3. Discipleship
4. The Ministry of the Holy Spirit
5. Jesus’ Death and Resurrection
Recognize parallels between the four key aspects of Jesus’ relationship with his Father and the four key aspects of the disciple’s relationship with Jesus (sect. 9.1 and 9.2 ).
Dependency
The Son can do nothing by himself; he can do only what he sees his Father doing (5:19).
Remain in me, and I will remain in you. No branch can bear fruit by itself; it must remain in the vine. Neither can you bear fruit unless you remain in me…apart from me you can do nothing (15:4-5).
Recognize parallels between the four key aspects of Jesus’ relationship with his Father and the four key aspects of the disciple’s relationship with Jesus (sect. 9.1 and 9.2 ).
Obedience
whatever the Father does the Son also does (5:19).
Whoever has my commands and obeys them, he is the one who loves me. He who loves me will be loved by my Father, and I too will love him and show myself to him (14:21).
A new command I give you
: love one another. As I have loved you, so you must love one another. By this all men will know that you are my disciples, if you love one another (13:34-35).
Recognize parallels between the four key aspects of Jesus’ relationship with his Father and the four key aspects of the disciple’s relationship with Jesus (sect. 9.1 and 9.2 ).
Intimacy
For the Father loves the Son and shows him all he does. (5:20)No one has ever seen God, but God the One and Only, who is at the Father’s side, has made him known (1:18).
Intimacy
One of them, the disciple whom Jesus loved, was reclining next to him….Leaning back against Jesus [literally, ‘on the breast [chest] of Jesus,’ he asked him, “Lord, who is it?” (13:23-25; cf 1:18)
On that day you will realize that I am in my Father, and you are in me, and I am in you (14:20).
I no longer call you servants, because a servant does not know his master’s business. Instead, I have called you friends, for everything that I learned from my Father I have made known to you (15:15).
Recognize parallels between the four key aspects of Jesus’ relationship with his Father and the four key aspects of the disciple’s relationship with Jesus (sect. 9.1 and 9.2 ).
Authority
(5:21-27. (5:21 (14:12-14).
I tell you the truth, my Father will give you whatever you ask in my name. Until now you have not asked for anything in my name. Ask and you will receive, and your joy will be complete(16:23-24).
Understand the three steps Jesus followed to disciple his followers (sect. 9.3).
1. Jesus models the message (ch. 13)
“Having loved his own who were in the world, he now showed them the full extent of his love (13:1). “Now that I your Lord and teacher, have washed your feet, you also should wash one another’s feet. I have set you an example that you should do as I have done for you” (13:14-15).
2.
Jesus proclaims what he has modeled
Jesus reveals the future (14:1-4)
Jesus reveals the Father (14:5-14)
Jesus promises the Spirit, his abiding presence (14:15-21)
Jesus calls for discipleship
: love, obedience, Spirit, peace (14:23-27)
Jesus goes to the Father (14:28-31)
Jesus reveals himself as the “true vine” (i.e., Israel, 15:1)
Jesus invites his disciples into a cleansed (15:2-3), dependent (15:4-5), prayerful (15:7), obedient (15:9-10), joyful (15:11), loving (15:12-13), intimate (15:14-15), secure, fruitful (15:16), suffering relationship with himself (15:18-16:4)
Jesus predicts his departure, the coming of the Spirit, and his resurrection/return (16:5-33)
3. Jesus intercedes that the model and message may come into being (ch. 17)
Jesus prays for his glory (17:1-4).
Jesus prays for our good
: protection, sanctification, communion/union, destiny, and our filling with the Father’s love for the Son and his presence (17:5-26).
Identify-
Jesus models servant, self-giving, totally gracious
love
, and commands his followers to do the same
Jesus commands that his followers show
love
for him through obedience.
The secret to obedience is abiding in him and his
love
“
Love
each other as I have
loved
you”
The final secret to obedient love is that Jesus prays it into being.
"Love" is the trait that stands at the heart of a disciple.
Memorize and utilize John 20:21-23, in order to apply the four parts of Jesus’ commission to the disciples (in 4 paragraphs (sect 9.6))..”
1.1 How Jesus commissions his disciplesJesus prepares his disciples by giving them:
1.1.1 The confidence to go“Peace be with you!” (20:21)
1.1.2 The command to go“As the Father has sent me, I am sending you” (20:21).
1.1.3 The power to go“And with that he breathed on them and said, ‘Receive the Holy Spirit’” (20:22).
1.1.4 The authority to go“If you forgive anyone his sins, they are forgiven; if you do not forgive them, they are not forgiven” (20:23).
Recognize-
He witnesses to Jesus, as the disciples witness to Jesus
He convicts the world of sin, righteousness, judgment
the mission of the Holy Spirit
List (in one word each) the four key aspects of Jesus’ relationship with his Father (sect. 9.1).
1. Dependency
2. Obedience
3. Intimacy
4. Authority | https://www.freezingblue.com/flashcards/print_preview.cgi?cardsetID=150770 | CC-MAIN-2016-44 | refinedweb | 1,054 | 69.52 |
Visiting the Microsoft campus in Redmond, Washington in August, I asked a couple of developers what the difference is between using the thread class and using the thread pool. The answer I got was that there is no real difference. The thread pool is easier because it manages thread objects for you; when you create a thread object, you have to manage it yourself.
Using threads in the ThreadPool was referred to as "lightweight" threading, and creating an instance of the Thread class was referred to as "heavyweight" threading. The adjectives did not refer to their capability but rather to ease of use. The thread pool is easier to use, but when using the thread pool, you are multithreading just as assuredly as you are when creating instances of the Thread class. One developer said something to the effect of "Why wouldn't you always use the thread pool?"
In effect, identical end results can be achieved with lightweight threading or heavyweight threading. It's easy to use the thread pool, and a little harder to use the Thread class.
What Is the Thread Pool?
The thread pool is a class defined in the System.Threading namespace. The class is ThreadPool. What the ThreadPool class does is manage a few threads that are available for you to request work. If the pool has available threads, the work is completed on an available thread. If no thread is available in the pool, the thread pool creates another task or may wait for a thread to become available. For the most part, you do not care exactly how it proceeds.
Very simply, the thread pool uses an available thread or creates a new one, manages starting the task on the thread, and cleans up. The thread pool is a thread manager. A consequence is that if you use the thread pool, you do not need to create and keep track of individual thread objects, but you get the same benefit as if you had.
How Does the Thread Pool Work?
The thread pool works in much the same manner as creating and using an instance of the Thread class. You have a thread and you give it work by passing the thread a delegate. In the case of the thread pool, you give the pool a delegate and the pool manager assigns the work represented by the delegate to a thread. The result is the same.
Using the Thread Pool
You are familiar with keeping track of the time in a Windows application, so we will start there. (When you have the basics down, we will progress to more interesting tasks.)
There are three things we will need to use the thread pool in a Windows Form to implement a clock. We will need to define a procedure that interacts with the Windows Form on the same thread as the form. We will need to define a procedure that represents work occurring on a separate thread than the form, and we will need to request that the thread pool perform the work. Listing 14.2 demonstrates how straightforward this is.
Listing 14.2 Implementing a clock on a separate thread.
1: Imports System.Threading 2: 3: Public Class Form1 4: Inherits System.Windows.Forms.Form 5: 6: [ Windows Form Designer generated code ] 7: 8: Private Sub UpdateTime() 9: SyncLock Me.Name 10: Text = Now 11: End SyncLock 12: End Sub 13: 14: Private Sub TrackTime(ByVal State As Object) 15: 16: While (True) 17: Try 18: 'Invoke(New MethodInvoker(AddressOf UpdateTime)) 19: Invoke(CType(AddressOf UpdateTime, MethodInvoker)) 20: Catch 21: 22: End Try 23: Thread.CurrentThread.Sleep(500) 24: End While 25: 26: End Sub 27: 28: Private Sub Form1_Load(ByVal sender As System.Object, _ 29: ByVal e As System.EventArgs) Handles MyBase.Load 30: 31: ThreadPool.QueueUserWorkItem(AddressOf TrackTime) 32: 33: End Sub 34: End Class
UpdateTime on lines 8 through 12 updates the form's captionText propertyto display the current time. (We have dispensed with the StatusBar because it isn't relevant to the discussion.) We use SyncLock and End SyncLock to block any other thread from trying to update the text property, but what makes the code safe is that UpdateTime occurs on the same thread that the form is on. (We will inspect this hypothesis in a minute.)
TrackTime has the signature of a WaitCallback delegate. WaitCallback is initialized with a subroutine that takes a single Object argument. Line 16 begins an infinite loop. We know from experience, of course, that an infinite loop in our main thread would spell death in the form of unresponsiveness to our application. Because TrackTime runs on its own thread, infinite-loop death does not occur. Lines 18 and 19 are effectively identical. Lines 18 and 19 use the Invoke method (which all controls have), which allows you to invoke a process. Calling Invoke bumps the work over to the thread that the control is on. On line 18 we are indicating that we want to invoke the UpdateMethod on the form's thread. Implicit in the call on lines 18 and 19 is the Me object reference.
Finally, line 31 calls the shared method ThreadPool.QueueUserWorkItem passing a delegate returned by the AddressOf statement as the work item. Line 31 will place TrackTime on its own thread. Figures 14.1 through 14.3 show the threads running and the changing of contexts as the code runs. A brief explanation follows each figure.
Figure 14.1. Form1.TrackTime shown on a separate thread, thread ID 2460.
Figure 14.1 shows the debugger stopped on line 63 on the statement Thread.CurrentThread.Sleep(500). From the Threads windowwhich you can open by choosing Debug, Windows, Threads in the Visual Studio .NET IDEyou can see that the TrackTime method is running on thread 2460. We use the Step Into shortcut until the debugger reaches line 57 in the TrackTime method. We use Debug, Step Into twice more until the debugger reaches line 60, which contains an Invoke method call.
Figure 14.2. Form1.UpdateTime shown on the same thread as the Form itself, thread 2324.
From Figure 14.2, you can see that the Invoke method caused the debugger to switch threads. UpdateTime is running on thread 2324. If we continue stepping to the end of UpdateTime, we see that the thread switches back to 2460 after the debugger returns from UpdateTime (see Figure 14.3).
Figure 14.3. Form1.TrackTime shown after returning from UpdateTime and back on thread 2460.
But how do we know we are on the same thread as the form? There are two ways we can determine that UpdateTime is on the same thread as the form. When the Form.Load event occurs, we can use the QuickWatch window, accessed by pressing Shift+F9 and invoking the AppDomain.GetCurrentThreadID shared method. This method will indicate the form's thread and we can visually compare it to the thread ID in the Threads window when UpdateTime is processing. The second way we can know if the UpdateTime is on the form's thread is by calling Control.InvokeRequired.
Each control implements InvokeRequired. Calling InvokeRequired compares the control's thread with the thread on which the InvokeRequired method was called. If the threads are identical, InvokeRequired returns False.
Problems
There is a problem with the code example in Listing 14.2. What if the form is shutting down or disposed of and the code calls the form's Invoke method on line 18? Although the help indicates that Invoke is safe to call from any thread, you still can't call a method on an object that has been disposed of. You could write to check to see if the form is Disposing, but if the form is already disposed of, this will fail.
You could check the IsDisposed property. This property will return True if the form is disposed of, but the garbage collector has not cleaned up the memory yet. However, if the GC has cleaned up the form, you will still get an exception.
You could use a flag in the form that indicates that the form is being closed, but the Invoke method could be called after the flag is checked.
Resolutions
For this example I would make one of three decisions based on the importance of the task. One choice would be to consider the task simplistic enough that a silent exception handler around the Invoke call would catch calls after the form had been destroyed.
Try Invoke(CType(AddressOf UpdateTime, MethodInvoker)) Catch End Try
Where the form has been disposed of, this silent exception handler would provide blanket protection. Because there is nothing to corrupt here, this is a reasonable solution. I am not a big fan of silent exceptions but do use them on rare occasions. The relatively low importance of keeping time might warrant such an approach.
A second choice would be to create the thread myself and keep track of the thread, shutting down and disposing of the thread when the application shuts down. This solution is clean and demonstrates an instance when owning the thread helps.
A third choice would to consider the relatively low importance of the task and use a timer to get asynchronous background behavior. In a real-world application where the timer is simply providing a clock, this is the choice I would make.
Using a WaitHandle and Synchronizing Behavior
The WaitHandle class is a base class used to implement synchronization objects. AutoResetEvent, ManualResetEvent, and Mutex are subclassed from WaitHandle and define methods to block access to shared resources.
To demonstrate blocking and synchronization of shared resources, I will implement a class named Dice. Each Dice instance rolls on its own thread, but the total score of all of the dice cannot be obtained until all of the dice have finished rolling. WaitHandle objects are used in conjunction with the thread pool, so we will roll the dice using the threads in the pool.
Listing 14.3 implements Dice and DiceGraphic classes. The Dice class represents a single die and the DiceGraphic class supports painting the graphical view of one face of a die. Listing 14.3 contains the code that runs on a unique thread, contains the shared WaitHandle, and uses synchronization to determine when all dice have finished rolling. Listing 14.4 lists the form that contains the graphical representation of five dice. A synopsis of the code follows each listing.
Listing 14.3 Contains the threaded behavior, WaitHandle, and synchronized behavior.
1: Imports System.Threading 2: Imports System.Drawing 3: 4: Public Class Dice 5: 6: Private FValue As Integer = 1 7: Private Shared FRolling As Integer = 0 8: Private FColor As Color 9: Private FRect As Rectangle 10: Public Shared Done As New AutoResetEvent(False) 11: 12: Public Shared ReadOnly Property IsRolling() As Boolean 13: Get 14: Return FRolling > 0 15: End Get 16: End Property 17: 18: Public Sub New() 19: MyClass.New(New Rectangle(10, 10, 50, 50), Color.White) 20: End Sub 21: 22: Public Sub New(ByVal Rect As Rectangle, ByVal color As Color) 23: MyBase.New() 24: FRect = Rect 25: FColor = color 26: End Sub 27: 28: Public ReadOnly Property Value() As Integer 29: Get 30: Return FValue 31: End Get 32: End Property 33: 34: Public Sub Roll(ByVal State As Object) 35: 36: Interlocked.Increment(FRolling) 37: Try 38: DoRoll(CType(State, Graphics)) 39: Finally 40: If (Interlocked.Decrement(FRolling) = 0) Then 41: Done.Set() 42: End If 43: End Try 44: 45: End Sub 46: 47: Public Sub Draw(ByVal Graphic As Graphics) 48: DiceGraphic.Draw(Graphic, FValue, FRect, FColor) 49: End Sub 50: 51: Private Sub DoRoll(ByVal Graphic As Graphics) 52: Dim I As Integer = GetRandomNumber() 53: While (I > 0) 54: FValue = GetRandomDie() 55: Draw(Graphic) 56: Beep() 57: I -= 1 58: Thread.CurrentThread.Sleep(50) 59: End While 60: End Sub 61: 62: Private Shared Random As New Random() 63: 64: Private Shared Function GetRandomNumber() As Integer 65: Return Random.Next(30, 50) 66: End Function 67: 68: Protected Shared Function GetRandomDie() As Integer 69: Return Random.Next(1, 7) 70: End Function 71: End Class 72: 73: Public Class DiceGraphic 74: 75: Public Shared Sub Draw(ByVal Graphic As Graphics, _ 76: ByVal Value As Integer, _ 77: ByVal Rect As Rectangle, ByVal Color As Color) 78: 79: Graphic.FillRectangle(New SolidBrush(Color), Rect) 80: Graphic.DrawRectangle(Pens.Black, Rect) 81: DrawDots(Graphic, GetRects(Value, Rect)) 82: 83: End Sub 84: 85: 86: Private Shared Function GetRects(ByVal Value As Integer, _ 87: ByVal Rect As Rectangle) As Rectangle() 88: 89: Dim One() As Rectangle = {GetRectangle(Rect, 1, 1)} 90: Dim Two() As Rectangle = {GetRectangle(Rect, 0, 2), _ 91: GetRectangle(Rect, 2, 0)} 92: 93: Dim Three() As Rectangle = {GetRectangle(Rect, 0, 2), _ 94: GetRectangle(Rect, 1, 1), GetRectangle(Rect, 2, 0)} 95: 96: Dim Four() As Rectangle = {GetRectangle(Rect, 0, 0), _ 97: GetRectangle(Rect, 0, 2), GetRectangle(Rect, 2, 0), _ 98: GetRectangle(Rect, 2, 2)} 99: 100: Dim Five() As Rectangle = {GetRectangle(Rect, 0, 0), _ 101: GetRectangle(Rect, 1, 1), GetRectangle(Rect, 0, 2), _ 102: GetRectangle(Rect, 2, 0), GetRectangle(Rect, 2, 2)} 103: 104: Dim Six() As Rectangle = {GetRectangle(Rect, 0, 0), _ 105: GetRectangle(Rect, 0, 1), GetRectangle(Rect, 0, 2), _ 106: GetRectangle(Rect, 2, 0), GetRectangle(Rect, 2, 1), _ 107: GetRectangle(Rect, 2, 2)} 108: 109: Dim Rects As Rectangle()() = _ 110: {One, Two, Three, Four, Five, Six} 111: 112: Return Rects(Value - 1) 113: 114: End Function 115: 116: Protected Shared Function GetRectangle(ByVal Rect As Rectangle, _ 117: ByVal X As Integer, ByVal Y As Integer) As Rectangle 118: 119: Return New Rectangle(Rect.X + _ 120: (Rect.Width * X / 3), _ 121: Rect.Y + (Rect.Height * Y / 3), _ 122: GetDotSize(Rect).Width, GetDotSize(Rect).Height) 123: End Function 124: 125: 126: Protected Shared Function GetDotSize( _ 127: ByVal Rect As Rectangle) As Size 128: 129: Return New Size(Rect.Width / 3, Rect.Height / 3) 130: End Function 131: 132: Private Shared Sub DrawDot(ByVal Graphic As Graphics, _ 133: ByVal Rect As Rectangle) 134: 135: Graphic.SmoothingMode = _ 136: Drawing.Drawing2D.SmoothingMode.AntiAlias 137: 138: Rect.Inflate(-3, -3) 139: Graphic.FillEllipse(New SolidBrush(Color.Black), Rect) 140: 141: End Sub 142: 143: Private Shared Sub DrawDots(ByVal Graphic As Graphics, _ 144: ByVal Rects() As Rectangle) 145: 146: Dim I As Integer 147: For I = 0 To Rects.Length - 1 148: DrawDot(Graphic, Rects(I)) 149: Next 150: 151: End Sub 152: 153: End Class
Listing 14.3 implements the Dice class as a class that rotates a random number of times through the values 1 through 6. During each roll (see lines 51 through 60), a random value for the dice is obtained, Beep is used to simulate the sound of rolling dice, and the die is drawn. The drawing of the die's face is managed by the DiceGraphic class using GDI+ (see Chapter 17, "Programming with GDI+," for more information on using the Graphics object).
Transitioning to the topic of our discussion, the rolling behavior is run on its own thread invoked by an external source. Lines 34 through 45 implement the rolling behavior. Line 36 calls the shared Interlocked.Increment(FRolling) method to perform an atomic increment of the shared FRolling field. Dice are rolling when FRolling > 0, as implemented by the shared IsRolling property of the Dice class. A resource protection block is used to ensure that the FRolling property is decremented. The rolling behavior is called on line 38. From the typecast on line 38CType(State, Graphics))it is apparent that we will be passing in the Graphics object each time we roll the dice, because GDI+ is stateless. The Graphics object represents the device context, or canvas, of the control we are painting on, and its stateless implementation simply means that we do not cache Graphics objects. The Finally block ensures that the FRolling field is decremented, again using an atomic shared method Interlocked.Decrement. The new value of FRolling is evaluated. If FRolling = 0 after it has been decremented, all dice have stopped rolling and we can signal the WaitHandle that we are finished.
Done is instantiated on line 10 as an AutoResetEvent. AutoResetEvent is subclassed from WaitHandle, and it is created in an unsignaled state, represented by the False argument. Done is shared because one WaitHandle is shared by all instances of Dice. In summary, each Dice instance increments the shared FRolling field and decrements it when it is finished rolling. When FRolling is 0 again, we notify whoever is waiting that all dice are finished rolling. Listing 14.4 demonstrates a client that shows the dice (see Figure 14.4).
Figure 14.4. The threaded dice after they have been rolled on their own threads.
Listing 14.4 Each die rolls on its own thread, while waiting for all dice before scoring the roll.
1: Option Explicit On 2: Option Strict On 3: 4: Imports System.Threading 5: 6: Public Class Form1 7: Inherits System.Windows.Forms.Form 8: 9: [ Windows Form Designer generated code ] 10: 11: Private FDice(4) As Dice 12: 13: Private Sub Form1_Load(ByVal sender As System.Object, _ 14: ByVal e As System.EventArgs) Handles MyBase.Load 15: 16: Dim I As Integer 17: For I = 0 To FDice.Length - 1 18: FDice(I) = New Dice(New Rectangle(54 * I, 10, 50, 50), _ 19: Color.Ivory) 20: Next 21: End Sub 22: 23: Private Sub RollDice() 24: Dim I As Integer 25: For I = 0 To FDice.Length() - 1 26: ThreadPool.QueueUserWorkItem(AddressOf FDice(I).Roll, CreateGraphics) 27: Next 28: 29: Dice.Done.WaitOne() 30: End Sub 31: 32: Private Sub Score() 33: Dim I, Sum As Integer 34: For I = 0 To FDice.Length() - 1 35: Sum += FDice(I).Value 36: Next 37: 38: Text = String.Format("Scored: {0}", Sum) 39: End Sub 40: 41: Private Sub Button1_Click(ByVal sender As System.Object, _ 42: ByVal e As System.EventArgs) Handles Button1.Click 43: 44: RollDice() 45: Score() 46: 47: End Sub 48: 49: Private Sub Form1_Paint(ByVal sender As Object, _ 50: ByVal e As System.Windows.Forms.PaintEventArgs) _ 51: Handles MyBase.Paint 52: 53: Dim I As Integer 54: For I = 0 To FDice.Length - 1 55: FDice(I).Draw(CreateGraphics) 56: Next 57: 58: End Sub 59: 60: End Class
NOTE
Note: The threaded rolling behavior is cool, but it is worth noting that it took me about five times longer to write a threaded version of the rolling dice and get it to work correctly than simply rolling all dice on the same thread as the form.
Most of the code in Listing 14.4 is straightforward, so I won't itemize all of it. To review, the form is created. Five Dice are constructed in the form's Load event. The form's Paint event ensures that the dice are repainted if the form is repainted. (If the dice were user controls, they would receive their own paint message.) When the user clicks the button labeled Roll (refer to Figure 14.4), the RollDice and Score methods are called. The Score method simply sums the Value of each die. The interesting bit happens in the RollDice method.
The RollDice method on lines 23 through 30 iterates over each Dice in the FDice array declared on line 11. The Roll method of each Dice object is treated as the WaitCallback argument of the shared ThreadPool.QueueUserWorkItem method. Dice.Roll represents the work. The second argument is a Graphics object returned by the CreateGraphics factory method. After the loop exits, each dice is rolling on its own thread in the ThreadPool.
Resynchronizing occurs on line 29. The shared AutoResetEvent object is used to wait for all of the dice to stop rolling. Recall that the code does not call AutoResetEvent.Set until IsRolling is False, that is, until all dice have stopped rolling. By implementing the code this way, the message queue is filling up with input but not responding until AutoResetEvent.WaitOne (represented on line 29 by Done.WaitOne) returns.
NOTE
The first time you roll the dice, there is a brief delay between when the first die begins rolling and each subsequent die. This reflects the time it takes for the thread pool to construct additional thread objects. Subsequent rolls appear to start almost concurrently.
If you try to close the form, for example, the application will wait until the dice have stopped rolling before responding to an application shutdown. If you try to roll a second time before an ongoing roll is over, the application will respond after WaitOne returns. You would not want to be using the Graphics object passed to each die if the form object were being destroyed. Finally, because each die paints itself, you get a smooth graphic result without repainting the entire form, which would result in flicker.
ManualResetEvent
The ManualResetEvent is a WaitHandle that remains signaled until the Reset method is called, and remains unsignaled until the Set method is called.
Mutex
Mutex is a synchronization primitive that provides synchronized access to a shared resource. If one thread acquires a mutex, subsequent threads are blocked until the first thread releases its mutex.
Synchronization with the Monitor Class
Synchronizing critical sections of your code is essential when you may have multiple threads accessing a shared section of your code. For general synchronization, you can use the SyncLock...End SyncLock construct.
The SyncLock...End SyncLock construct is implemented using the Monitor class. You cannot create an instance of Monitor; all of the methods are shared anyway. Invoking Monitor.Enter(object) and Monitor.Exit(object) is identical to using the SyncLock...End SyncLock construct.
Monitor also contains methods Pulse, PulseAll, TryEnter, and Wait. Pulse notifies a single object in the waiting queue of a state change in the locked object. PulseAll notifies all waiting threads of a state change, and Wait releases the lock and waits until it reacquires the lock. The TryEnter method attempts to acquire an exclusive lock on an object.
Listing 14.5 demonstrates how to use the Monitor class to switch back and forth between two threads interacting with the same object.
Listing 14.5 Using the Monitor class.
1: Option Explicit On 2: Option Strict On 3: 4: Imports System 5: Imports System.Threading 6: 7: Class MonitorDemo 8: 9: Private Integers() As Integer 10: Private MAX As Integer = 1000 11: 12: Private I, J As Integer 13: 14: Public Sub FillArray() 15: Dim I As Integer 16: ReDim Integers(MAX) 17: Dim R As New Random() 18: 19: For I = 0 To Integers.Length - 1 20: Integers(I) = Integers.Length - 1 - I 21: Next 22: End Sub 23: 24: Public Sub SortArray(ByVal State As Object) 25: Monitor.Enter(Integers) 26: 27: For I = 0 To Integers.Length - 1 28: For J = I + 1 To Integers.Length - 1 29: If (Integers(I) > Integers(J)) Then 30: Dim T As Integer = Integers(I) 31: Integers(I) = Integers(J) 32: Integers(J) = T 33: End If 34: Next 35: 36: Monitor.Wait(Integers) 37: Console.Write("Sorted: ") 38: Monitor.Pulse(Integers) 39: Next 40: 41: Monitor.Exit(Integers) 42: End Sub 43: 44: Public Sub PrintArray(ByVal State As Object) 45: Static K As Integer = 0 46: 47: Monitor.Enter(Integers) 48: Monitor.Pulse(Integers) 49: 50: While (Monitor.Wait(Integers, 1000)) 51: 52: If (K <= I) Then 53: Console.WriteLine(Integers(K)) 54: K += 1 55: End If 56: 57: Monitor.Pulse(Integers) 58: End While 59: 60: Monitor.Exit(Integers) 61: End Sub 62: 63: Public Shared Sub Main() 64: 65: Dim Demo As New MonitorDemo() 66: Demo.FillArray() 67: 68: ThreadPool.QueueUserWorkItem(AddressOf Demo.SortArray) 69: ThreadPool.QueueUserWorkItem(AddressOf Demo.PrintArray) 70: 71: Console.ReadLine() 72: 73: End Sub 74: 75: End Class
Listing 14.5 uses Monitor.Enter and Monitor.Exit on lines 25 and 41 and again on lines 47 and 60. We would get the same result if we used the SyncLock...End SyncLock construct.
The Main subroutine is the starting point for this console application. An instance of the MonitorDemo class is created on line 65 and an array is filled with a thousand integers in reverse order. The ThreadPool is used on lines 68 and 69 requesting work from the SortArray and PrintArray methods. SortArray sorts the array of integers and PrintArray prints the integers in the array.
After each complete pass through the inner loop of the bubble sort, Monitor.Wait is called on line 36, giving the PrintArray method a chance to print the ordered ith element. Line 57 calls Monitor.Pulse notifying the SortArray method that the state has changed and allowing SortArray to reacquire the lock. The Monitor.Wait call on line 50 blocks the loop until the PrintArray method can reacquire the lock on the Integers object or one thousand milliseconds have elapsed. In summary, the code sorts each ith element and then prints the newly sorted element at the ith position.
Summary
The CLR supports asynchronous processing, lightweight threading using ThreadPool, and heavyweight threading by constructing instances of the Thread class. You are not limited to an all-or-nothing approach when implementing asynchronous or threaded behavior.
Choose the Timer control or Application.Idle event or BeginInvoke and EndInvoke for lightweight asynchronous behavior in Windows Forms. Consider using ThreadPool for many everyday multithreading tasks, and pull out the big gunthe Thread classif you need absolute control. Of course, when using the Thread class, you have to take complete ownership of the behavior of the thread, including creating, starting, and stopping the thread.
The CLR, and consequently Visual Basic .NET, support asynchronous and multithreaded behavior as well as a whole complement of synchronization and shared resource management by using the WaitHandle or Monitor classes. Consider all of the available resources for asynchronous and threaded behavior before selecting a particular implementation strategy. | http://www.informit.com/articles/article.aspx?p=25869 | CC-MAIN-2018-17 | refinedweb | 4,352 | 64.61 |
Hello,
I’m trying to write a utility to run an external process and capture
it’s stderr. It seems that IO.popen only lets me read the stdout. Any
tips for how to read stderr?
Mike
snippet of code…
def process_file(filename)
@filename = filename
puts "Processing: " + @filename
cmdline = "ffmpeg -i " + @filename
ffmpeg = IO.popen(cmdline, “w+”)
ffmpeg.close_write
result = ffmpeg.gets
result.each do |line|
puts "Line from ffmpeg: " + line
end
end
This code does not work because the good stuff I want from ffmpeg went
to stderr and not stdout. Please refrain from commenting on the merits
of ffmpeg. That could go on all day.
| https://www.ruby-forum.com/t/using-io-popen-to-capture-stderr/82155 | CC-MAIN-2021-43 | refinedweb | 107 | 78.45 |
#include "cache.h"
#include "sha1-lookup.h"
static uint32_t take2(const unsigned char *sha1)
{
return ((sha1[0] << 8) | sha1[1]);
}
/*
* Conventional binary search loop looks like this:
*
* do {
* int mi = lo + (hi - lo) / 2;
* int cmp = "entry pointed at by mi" minus "target";
* if (!cmp)
* return (mi is the wanted one)
* if (cmp > 0)
* hi = mi; "mi is larger than target"
* else
* lo = mi+1; "mi is smaller than target"
* } while (lo < hi);
*
* The invariants are:
*
* - When entering the loop, lo points at a slot that is never
* above the target (it could be at the target), hi points at a
* slot that is guaranteed to be above the target (it can never
* be at the target).
*
* - We find a point 'mi' between lo and hi (mi could be the same
* as lo, but never can be the same as hi), and check if it hits
* the target. There are three cases:
*
* - if it is a hit, we are happy.
*
* - if it is strictly higher than the target, we update hi with
* it.
*
* - if it is strictly lower than the target, we update lo to be
* one slot after it, because we allow lo to be at the target.
*
* When choosing 'mi', we do not have to take the "middle" but
* anywhere in between lo and hi, as long as lo <= mi < hi is
* satisfied. When we somehow know that the distance between the
* target and lo is much shorter than the target and hi, we could
* pick mi that is much closer to lo than the midway.
*/
/*
* The table should contain "nr" elements.
* The sha1 of element i (between 0 and nr - 1) should be returned
* by "fn(i, table)".
*/
int sha1_pos(const unsigned char *sha1, void *table, size_t nr,
sha1_access_fn fn)
{
size_t hi = nr;
size_t lo = 0;
size_t mi = 0;
if (!nr)
return -1;
if (nr != 1) {
size_t lov, hiv, miv, ofs;
for (ofs = 0; ofs < 18; ofs += 2) {
lov = take2(fn(0, table) + ofs);
hiv = take2(fn(nr - 1, table) + ofs);
miv = take2(sha1 + ofs);
if (miv < lov)
return -1;
if (hiv < miv)
return -1 - nr;
if (lov != hiv) {
/*
* At this point miv could be equal
* to hiv (but sha1 could still be higher);
* the invariant of (mi < hi) should be
* kept.
*/
mi = (nr - 1) * (miv - lov) / (hiv - lov);
if (lo <= mi && mi < hi)
break;
BUG("assertion failed in binary search");
}
}
}
do {
int cmp;
cmp = hashcmp(fn(mi, table), sha1);
if (!cmp)
return mi;
if (cmp > 0)
hi = mi;
else
lo = mi + 1;
mi = lo + (hi - lo) / 2;
} while (lo < hi);
return -lo-1;
}
int bsearch_hash(const unsigned char *sha1, const uint32_t *fanout_nbo,
const unsigned char *table, size_t stride, uint32_t *result)
{
uint32_t hi, lo;
hi = ntohl(fanout_nbo[*sha1]);
lo = ((*sha1 == 0x0) ? 0 : ntohl(fanout_nbo[*sha1 - 1]));
while (lo < hi) {
unsigned mi = lo + (hi - lo) / 2;
int cmp = hashcmp(table + mi * stride, sha1);
if (!cmp) {
if (result)
*result = mi;
return 1;
}
if (cmp > 0)
hi = mi;
else
lo = mi + 1;
}
if (result)
*result = lo;
return 0;
} | https://gitlab.com/pclouds/git/blame/5c2b4ca06ee2803bd5329cb0ccfc12cfaa40afe7/sha1-lookup.c | CC-MAIN-2019-35 | refinedweb | 498 | 80.04 |
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).
@m_adam Thank you for your answer. C++ documentation have a "Example" show how to use flags in CAMorph.SetMode, but python documentation not (at least in R21.022), i compared the C++ code with Python, then went back to the C++ documentation and found this.
I get it, CAMorph.SetMode(doc, tag, flags, mode) flags must include CAMORPH_MODE_FLAGS_EXPAND, i used to use CAMORPH_MODE_FLAGS_ALL because is marked with "ALL". it is Documentation error?
hi,
i try to convert my cpp code to python and find CAMorphNode.SetPointCount() always return false. Ensure CAMorphNode.GetInfo() == c4d.CAMORPH_DATA_FLAGS_POINTS (Pose Morph Tag is in Points mode) and can get correct number from CAMorphNode.GetPointCount(), but also not work. Do I need to do something different from cpp or is this a bug?
hope your answer!
@m_magalhaes thanks, looking forward to the next update
Hi,
GvNode.OperatorSetData(type, data, mode) invalid in R21 when attempt to add pose strength port on posemorph tag object node. The following script shows this problem. it's the same in C++, and mouse drag also can't add port too( I guess it also uses this API ).
import c4d
from c4d import gui
#project setting:
#1: create a baseobject, add posemorph tag, xpresso tag
#2: choose Points Mode in posemorph tag and switch to Animation Mode, select xpresso tag
#3: run script
def main():
doc = c4d.documents.GetActiveDocument()
tag = doc.GetActiveTag()
if not tag.IsInstanceOf(c4d.Texpresso):
return
master = tag.GetNodeMaster()
objectNode = master.CreateNode(master.GetRoot(), c4d.ID_OPERATOR_OBJECT)
if objectNode is None:
return
posemorphTag = tag.GetNext()
if posemorphTag is None or not posemorphTag.IsInstanceOf(c4d.Tposemorph):
return
if not objectNode.OperatorSetData(c4d.GV_ATOM, posemorphTag, c4d.GV_OP_DROP_IN_BODY):
return
descID = c4d.DescID(c4d.DescLevel(4000),c4d.DescLevel(1101)) # frist pose port DescID
data = {"did":descID, "arr":[posemorphTag]}
if not objectNode.OperatorSetData(c4d.GV_DESCID, data, c4d.GV_OP_DROP_IN_INDOCK):
print("Error")
return
c4d.EventAdd()
if __name__=='__main__':
main()
@m_adam disappointed , thank you for your answer.
And if i create my own GvOperatorData, can i get the message when change Port Index by mouse Drag?
@s_bach just a sudden thought when i use GvPort* GetInPort(Int32 index) go through all the InPorts. i attempt to change InPorts index but failed, is there a way to do that?
hi,
i noticed drag port can change the ports order,but haven't find any message about how to resort the GvNode Port index in SDK, is this possible by code?
hope your help.
@m_magalhaes Thank you, is all right. and sorry for my negligence, I will pay attention next time.
Hello,
I m confuse about how to use BaseDraw::DrawObject/DrawPolygonObject draw constant color like Display Tag Constant Shading mode?
hope for your help! | https://plugincafe.maxon.net/user/jmelon | CC-MAIN-2022-27 | refinedweb | 489 | 60.72 |
Bummer! This is just a preview. You need to be signed in with a Pro account to view the entire video.
Build Fast and Beautiful Native Apps with Web Tech Using PhoneGap and TopCoat56:47 with Brian LeRoux
Everyone knows you can build an app for many platforms using HTML, CSS, and JavaScript but the jury has been out as to whether you can build a beautiful, responsive, lighting fast app. Complete with disaster defying demos and legit hand coding, Brian will guide you through the history, direction, and HOW to build an app using web tech for iOS, Android and other platforms.
- 0:00
[BLANK_AUDIO].
- 0:05
Do we have any PhoneGap developers in the room?
- 0:07
Oh, shit, that's awesome.
- 0:11
There used to be zero, so, I'm stoked about that.
- 0:14
All right, so let's dig in.
- 0:17
The, thing I hate the most about software conferences, is that you'll
- 0:21
have someone come here and they will talk to you for an hour.
- 0:23
And they won't show you a single line of code.
- 0:26
I'm not gonna do that.
- 0:26
I'm gonna try and show you guys, like how
- 0:28
this stuff works and so, let's build an app.
- 0:33
Anybody here building apps?
- 0:37
Right on.
- 0:38
Native apps, like iOS?
- 0:40
Android?
- 0:42
Okay, Firefox OS?
- 0:48
Nothing?
- 0:49
It's sweet, dude.
- 0:50
You should check it out.
- 0:51
Okay so I, I work on the PhoneGap project.
- 0:55
We've got a bunch of toys to play with today.
- 0:58
I just bumped my phone a little bit.
- 1:01
So, PhoneGap is at the moment a command line utility.
- 1:06
That you download and install.
- 1:08
It's a node module, and so if I, if I need it, I need to have node.
- 1:11
And then to install it I just do MPMI G PhoneGap, and I'd get it.
- 1:15
That would download the Internet and eventually install PhoneGap.
- 1:19
And then I can run it, on the command line by typing in PhoneGap.
- 1:25
This in itself is not all that exciting.
- 1:28
The command line isn't all that scary either.
- 1:30
Something that's interesting about PhoneGap once you run it once
- 1:33
it's gonna give you this little grid as a helper.
- 1:38
So you know which platforms you can build for.
- 1:40
On your current situation.
- 1:42
And you'll see, it's like local, environment and remote environment.
- 1:46
If you want, you can configure PhoneGap to work remotely.
- 1:48
I'm not gonna do that.
- 1:50
And then it gives you like all the
- 1:52
various, you know, commands that you can run.
- 1:54
So, cuz I'm lazy and hung over, I'm gonna do PhoneGap create, Foobaz.
- 2:05
And would I create a project called FooBaz.
- 2:07
So we're gonna jump into FooBaz, and we're gonna take a look at, I use Bem.
- 2:12
I'm old, you don't have to, it's not a prerequisite to doing this stuff.
- 2:16
I think Bem's useful, You know, pick your
- 2:19
text editor of choice, it doesn't really matter.
- 2:21
PhoneGap.
- 2:21
Super does not care.
- 2:22
This is just web development.
- 2:23
And so, one of the, big things that we wanna first
- 2:27
take note of is a PhoneGap project has a www folder.
- 2:30
Very much like Apache, this is where your web assets go, so
- 2:34
you can put HTML, CSS, JavaScript in here to your heart's desire.
- 2:39
We've got a couple of other folders, I'm gonna get into those later.
- 2:42
You don't have to look at them right now and in fact none of these are mandatory.
- 2:45
This is the only one that counts and so if you, walk away
- 2:48
from this situation knowing anything you know we can deal with web stuff.
- 2:53
So, let's take a look at this.
- 2:56
We're an Apache software project.
- 2:57
I'll talk more about that in a bit.
- 2:59
Right now I'm just gonna totally fodge a license.
- 3:02
I'm gonna get rid of this because I don't care about iOS7.
- 3:05
And let's take a look at like what we got here.
- 3:07
So we've got some really basic markup, you
- 3:09
know, typical title, we've got these two, Paragraph elements.
- 3:16
One says, connecting device.
- 3:17
The other says, device is ready.
- 3:18
You'll have to take my word for it but the CSS in this
- 3:23
will, blank out device is ready until the device itself is actually ready.
- 3:29
We've got some hyper enthusiastic JavaScript developer in
- 3:31
here who decided that they would add this type.
- 3:34
I just wanna let you know that that is no longer necessary.
- 3:38
And, it's HTML5.
- 3:41
So I don't give a fuck about these quotes.
- 3:45
They can go away.
- 3:47
I totally just ruined everything.
- 3:52
Okay.
- 3:52
[SOUND] So now I can go PhoneGap Run iOS.
- 4:00
[LAUGH] Really?
- 4:07
[SOUND] I think I had a
- 4:12
demo project there.
- 4:18
So now I'm gonna jump into, under the hood into Xcode, do a bunch of crazy stuff,
- 4:23
in a compiler application and then we're gonna
- 4:26
launch it and we're gonna see the device's ready.
- 4:31
So, I type two commands, I'm on, iOS, that's kind of neat.
- 4:38
Everyone's like is Brian full of shit or not.
- 4:41
Let's just, go take a look back at that code.
- 4:47
I think I was editing, a sub project at that time.
- 4:51
So let's just change this to [SOUND]
- 4:57
says device it's ready, let's go like,
- 5:03
[SOUND] I have a Vegas level hangover.
- 5:08
All right.
- 5:15
[SOUND] Same business, kicks out the Xcode.
- 5:18
Under the hood.
- 5:20
We're trying to install our own device.
- 5:21
No device exists.
- 5:22
So then we find that we've got a simulator.
- 5:25
We launch it and I have a Vegas level hangover.
- 5:30
Cool.
- 5:31
That's interesting.
- 5:32
We're not quite living up to the promise of PhoneGap at this point.
- 5:36
So, I'm gonna plug in my phone.
- 5:40
Which is a Nexus 5.
- 5:46
[SOUND] and,
- 5:52
[SOUND] oh, no.
- 6:00
That's super uncool if you don't work.
- 6:02
[LAUGH] I
- 6:06
swear to God the phones plugged in.
- 6:09
Why Android why?
- 6:10
It's like it can detect when I'm presenting.
- 6:15
it's like I'm gonna screw with you.
- 6:18
Okay.
- 6:20
Does anyone have a, a mini USB cable, on them, by any chance?
- 6:26
This has to be the cable.
- 6:27
[BLANK_AUDIO].
- 6:33
You're a good man, I owe you a beer.
- 6:37
To your peril.
- 6:38
[LAUGH] All right, let's see if this works.
- 6:47
If this doesn't work, I even.
- 6:51
Oh, it did.
- 6:52
It was the cable.
- 6:53
That's super crazy.
- 6:54
Okay, so we'll, launch Photo Booth.
- 6:57
So you know I'm not a liar, I'm gonna go back
- 7:02
to my command line, and we'll do PhoneGap > Run Android.
- 7:06
[SOUND] And so, PhoneGap's gonna detect that I've got an Android device here.
- 7:13
It's gonna compile.
- 7:14
It's gonna dump a bunch of Java bullshit to my terminal.
- 7:18
Once that's done, [SOUND] it's gonna try and install it on the device.
- 7:24
Hm.
- 7:29
And
- 7:36
so, we're on.
- 7:38
Two platforms now with a grand total of three commands.
- 7:41
[SOUND] So there you go, there's your Hello World.
- 7:45
That's kinda how it works when you're
- 7:47
looking to build for multiple platforms with PhoneGap.
- 7:52
I'm
- 7:55
Aging, open source software developer.
- 7:57
And one of the things when.
- 7:59
So, open source is sorta like adopting kittens.
- 8:03
They're beautiful and you love them at first.
- 8:05
And then you own a cat.
- 8:05
And so [LAUGH].
- 8:09
It's the same thing.
- 8:10
I mean when you're, when you're adopting a technology
- 8:12
eventually you're gonna have to deal with it right.
- 8:14
And so, in order to understand whether or not
- 8:16
you think this technology is appropriate for your business,
- 8:20
your business drivers, you have to understand where it
- 8:22
came from and you have to understand where it's going.
- 8:25
Everybody jumped on, the rails bandwagon and they were super stoked.
- 8:29
Rails was great.
- 8:30
And then Rails went through a lot of change over time.
- 8:34
So understand where open source comes from helps you understand where it's going.
- 8:41
PhoneGap just like every other open source project
- 8:43
has a lot of weird mythology surrounding it.
- 8:46
So, I wanna clear some of that up.
- 8:48
In 2008.
- 8:50
Oh, actually it started in 2007, so in
- 8:51
2007 I used to work at this software company
- 8:53
in Vancouver called Nitobi, and we did a
- 8:56
lot of Blackberry development because we're Canadian, I guess.
- 9:00
I don't know why and we, we were really stoked
- 9:04
like the, the early I think it was called the Curve.
- 9:08
It was the first device with a GPS.
- 9:10
And we're like, this is, this is gonna be something.
- 9:12
This mobile thing.
- 9:13
And then Steve Jobs comes out and he walks on the stage, and
- 9:16
he holds up the iPhone, and he says you're gonna build web apps.
- 9:19
And we squealed like little girls, and we jumped in our cars, and we
- 9:22
drove down to Seattle because they didn't sell them in Canada at the time.
- 9:25
And we bought a shitload of iPhones, and we started building apps.
- 9:29
We love that model, that was, that was the right model,
- 9:32
Apple was like, you're going to build apps, we're like yes!
- 9:34
Exactly that, one year later, he's like sike!
- 9:38
You're building objective C apps.
- 9:40
We're like, oh, okay.
- 9:42
[LAUGH] And we checked it out, objective C is actually a pretty cool language.
- 9:47
I totally recommend learning it by the way, I'm not gonna tell you that you
- 9:50
shouldn't learn a new software language or
- 9:53
how to program a particular platform, you absolute.
- 9:56
Should be a better programmer, and you need to learn multiple languages.
- 10:00
That said, objective C is horrific.
- 10:02
So.
- 10:02
[LAUGH] We jumped in and we're like, okay, you know, there's probably some merit
- 10:08
to this ancient language, with, array syntax for accessing properties.
- 10:13
Maybe, maybe it can be useful.
- 10:15
And then we discovered that it's, it's got a web view.
- 10:17
And we were like oh, okay, well that's interesting,
- 10:19
so we can substantiate a web view, but can
- 10:21
we create some kind of like, binding where we
- 10:23
can call, you know, the JavaScript code from native?
- 10:27
And it turns out you super can.
- 10:29
With terribly named syntax, it's like execute string by evaluating string,
- 10:36
you can call in, but can you call back the other way?
- 10:39
And, it turns out that this just wasn't a supported
- 10:42
thing, at all, and a couple of our dudes went
- 10:45
down to, ironically, Adobe at the time, and they went
- 10:49
to this thing called iPhone dev camp and they're like.
- 10:51
They met some app developers and, hey, can
- 10:54
we call from the JavaScrip to the native site.
- 10:56
And this Apple developers are like, nope, not possible.
- 10:59
Well, I mean, you could pull the URL, that'll be crazy.
- 11:02
So, that's what they did.
- 11:04
So, PhoneGap ultimately creates it's bridge between
- 11:08
native code, and the web view that you're
- 11:10
sitting in, and then we do it in very of different ways for every single platform.
- 11:12
But, the original way we did it, and we don't do this any more, but you.
- 11:16
Could still do this if you wanted to.
- 11:18
Was polling on what the URL.
- 11:20
So we pass a message in the URL and we then set that protocol
- 11:23
handler and we'd be like, oh, okay, I'm actually looking for a native call.
- 11:26
And we'd execute some native code.
- 11:27
And then we could call into the JavaScript the other way.
- 11:31
Now everyone's thinking, oh my God that must be super slow, and you're right.
- 11:35
We only get about 400 hertz which would be
- 11:37
400 operations a second on that particular type of call.
- 11:41
Slow but I ask you do you need to get your geolocation 400 times a second?
- 11:49
Probably not.
- 11:50
So [LAUGH] it's really good for doing a lot of stuff.
- 11:53
Not everything.
- 11:54
So in 2008 we figured this out Rob and Barack, guys I used to
- 11:58
work with, and they had an iPhone and they had Super Mario on it.
- 12:03
And they would, tilt around this phone.
- 12:05
That big thick old first version iPhone, and
- 12:08
he would, Mario would react to the accelerometer.
- 12:11
At the time there was no device motion API.
- 12:13
This was, this was a big deal.
- 12:14
We're like, oh my God we figured out how to do this.
- 12:17
And then we didn't care.
- 12:18
We, went to the bar and got drunk like good Canadian kids do.
- 12:22
Dave Johnson, one of the guys that we work with,
- 12:24
was like hey wait guys I can do it with Blackberry.
- 12:27
Still, no one cared.
- 12:28
And then [LAUGH] another dude that we work with, Joe Bowser,
- 12:32
and do you remember that old, that first generation Android, that big
- 12:36
brick phone, the thing with the keyboard that made like a
- 12:39
fucking sound when you were, like, dealing with credit cards, like [SOUND]?
- 12:43
So he had that, and he's like, hey guys,
- 12:45
check it out, this is Android, this is the future.
- 12:47
And we're like [LAUGH] yeah, right, that's bullshit,
- 12:50
that thing's a piece of shit, there's no way.
- 12:53
So we were wrong about that.
- 12:54
But [LAUGH] he got, PhoneGap working on that.
- 12:58
And then we realized, we're like, oh my God, actually, wait a second.
- 13:03
We've got something that could be cross-platform.
- 13:05
So we threw it on GitHub and it really didn't matter.
- 13:08
Thousands and thousands of people started using it, and it still didn't matter.
- 13:12
No one cared.
- 13:12
It was kind of just a thing, it was a hack project.
- 13:15
And suddenly Apple started rejecting PhoneGap applications from the app
- 13:18
store, which was the best thing ever to happen to us.
- 13:21
[SOUND] We didn't care.
- 13:22
We thought, whatever.
- 13:24
We were building apps, and we liked them.
- 13:26
And they got into the app store sometimes.
- 13:28
And all of a sudden, boom, we're getting rejected.
- 13:31
And we had no idea why.
- 13:33
And we actually we're, like, well, you know?
- 13:35
Maybe this was like, dodgy on the acceptance rules or whatever.
- 13:38
So, it turns out [LAUGH] so the ReadWriteWeb
- 13:42
did an article, and they're like, PhoneGap being rejected!
- 13:45
Apple hates the web!
- 13:46
[LAUGH] And the internet like, rallied,
- 13:48
and they're like, help those PhoneGap guys!
- 13:51
None of this was true.
- 13:52
So what actually happened was, when you used to
- 13:55
create a PhoneGap project, it would name it PhoneGap.
- 13:59
Which made sense for us at the time.
- 14:00
And so Apple is getting thousands of apps submitted
- 14:03
to them called PhoneGap and they thought we were spammers.
- 14:05
So when they, when this article blew up and we finally talked
- 14:09
to them, they're like, oh, well can you just call it like, untitled?
- 14:12
And we're like yeah, we could do that.
- 14:15
And so, since PhoneGap in 0.8 in 2009.
- 14:19
We've been okay with Apple.
- 14:20
That's actually what kind of probably launched us.
- 14:24
In 2010 we were at OSCON cuz it's in Portland which is super close
- 14:29
to Vancouver and we would go there just cuz Portland's awesome.
- 14:34
They've got good craft beer and single origin coffee.
- 14:37
But we'd also go fo the open source stuff.
- 14:39
And we were hanging out with IBM guys.
- 14:41
And they're, like, hey, we're gonna throw a big team on PhoneGap.
- 14:43
And we're like, why [LAUGH] would you do that?
- 14:48
We had no idea what was going on.
- 14:50
They were like, no, no, no.
- 14:50
We think this is a legit project, and we wanna contribute to it.
- 14:53
And they started to teach us a lot about how open source probably should work.
- 14:56
Not how we thought it worked.
- 14:58
At that same time I started to you use PhoneGap as a vehicle to get
- 15:02
myself to travel to different places like Las
- 15:04
Vegas and [LAUGH] I ended up in Amsterdam.
- 15:08
And I was at a coffee shop and, we had
- 15:11
done a long day of training with all these different people.
- 15:16
And, basically, a PhoneGap training means that I have to teach you how, the
- 15:20
iOS SDK works, how the Android SDK works, how the Windows Phone SDK works.
- 15:25
And we're gonna install all that junk, and then we're gonna install Node.
- 15:28
And then hopefully, if we've got that Rube Goldberg machine
- 15:31
of things working, you're gonna be able to compile an app.
- 15:33
But it's a huge starting process.
- 15:35
So, literally [LAUGH] at a coffee shop while
- 15:38
I'm hanging out, I coded up a thing that,
- 15:41
we now call PhoneGap Build, which is a hosted
- 15:44
service where you can upload HTML, CSS and JavaScript.
- 15:49
Either a zip file or give us a Git repo and we'll compile
- 15:52
an app for you and give you a QR code to install it.
- 15:57
So, I wrote that, and we thought that was kind of funny and awesome.
- 16:03
Now we didn't need to install a bunch of SDKs, all you
- 16:05
needed was a, machine that was interconnected and you could build apps.
- 16:10
And we had like 80,000 sign ups in the first month,
- 16:12
so it went, it went pretty viral and people were stoked.
- 16:16
In 2011, we hit 1.0.
- 16:19
We finally started to find, kind of, our stride, and we were acquired by Adobe.
- 16:24
At that time, PhoneGap had what's called a CLA or a contributor license agreement.
- 16:30
CLA, it's open to debate if this thing matters or not.
- 16:35
Generally what it is, it's a license agreement where you say that the
- 16:39
outbound license, the license that everyone uses
- 16:41
your code, is the same as the
- 16:43
inbound license so you as the creator of some code, you then copyright that,
- 16:47
you would assign that copyright to, the
- 16:50
project that you're, you are contributing to.
- 16:52
So we had a CLA and that's a really normal thing to have in open source.
- 16:56
Most, probably almost all open source projects
- 16:59
have it, short of the Linux Kernel.
- 17:01
So, we had a CLA, but, it named named a
- 17:04
company called Nitobi Software, which just got acquired by Adobe.
- 17:09
And suddenly a lot of other companies that were contributing to
- 17:12
PhoneGap, including IBM, were like oh well so, I'm completely cool
- 17:16
you know, assigning my copyright and IP over to a small
- 17:20
company called Nitobi, totally not cool doing that to Adobe, weird.
- 17:26
So, [LAUGH] we decided at that time the best thing we could do
- 17:30
was to donate the source code of PhoneGap back to the Apache Software Foundation.
- 17:36
And I'm gonna talk a lot more about that.
- 17:39
Apache's a huge project and so in 2012 We started working
- 17:45
at Adobe full time on PhoneGap and it, it got a lot of adoption after that.
- 17:51
2013 I say optionally opinionated because we started
- 17:55
to carve PhoneGap up into two different pieces.
- 17:59
So there's the Apache Cordova project and then there's PhoneGap.
- 18:03
So PhoneGap is the thing I'm talking
- 18:05
about, it's a, thing for creating native apps.
- 18:08
Apache Cordova is the guts of that, it's the open source project.
- 18:12
Now, the difference between these two things
- 18:13
is actually nothing, they're the same thing.
- 18:17
Why is there something like that?
- 18:18
Well it's the same as like WebKit versus Safari or Linux versus Red Hat.
- 18:24
It's a downstream distribution.
- 18:28
I'm gonna, I'm gonna hold off on telling you what happens next.
- 18:31
Okay so, what, what is actually the difference between these two things.
- 18:35
So PhoneGap CLI, the thing showed you earlier
- 18:37
to build apps, has a remote build capability.
- 18:41
And that remote build capability hooks into.
- 18:44
PhoneGap build.
- 18:46
This thing here, so.
- 18:47
[SOUND] I can get
- 18:52
PhoneGap remote
- 18:58
build, iOS.
- 19:03
If I didn't have the iOS SDK installed.
- 19:07
It would default back to this.
- 19:10
[LAUGH] Oh, no.
- 19:12
Terrible demo.
- 19:13
Do I have connectivity?
- 19:18
[SOUND] PhoneGap
- 19:23
remote, run Android.
- 19:30
[SOUND] Cool, okay.
- 19:32
So, I'm not sure what I did wrong there.
- 19:38
More of the story being you can build, for
- 19:42
what ever platform on what ever computer your on.
- 19:45
So if your on a netbook.
- 19:46
You know, on a potentially, better connection than I have here.
- 19:52
[LAUGH] You'll be able to, build for iOS say, from a Windows machine.
- 19:59
That's kinda the point and this is our fun parlor trick.
- 20:05
Possibly the only cool use of a QR code ever is to dump that into your terminal,
- 20:11
using Antsy also.
- 20:16
It took us, like, months to do properly.
- 20:18
[LAUGH].
- 20:19
We super didn't care because we're like, this is rad.
- 20:24
>> So Apache Cordova.
- 20:25
>> Apache Cordova is phone gap that is the same thing.
- 20:29
>> And Apache Cordova is a little bit different and interesting.
- 20:34
>> So, let me show it to you.
- 20:39
>> I showed you a phonegap.
- 20:41
>> And all I had to was run phone gap on the command line and I got you know?
- 20:47
The sort of output where I can do stuff.
- 20:49
That's cool.
- 20:50
Cordova.
- 20:55
Really?
- 20:58
Well, we get to see the whole experience then, I guess.
- 21:01
Oh.
- 21:01
I'm going to install Cordova.
- 21:05
Totally to plan.
- 21:11
So NPM is the package manager for OJS.
- 21:15
Right now I'm downloading in the internet and possibly installing Cordova.
- 21:19
And at the bottom here we're linking into an
- 21:23
executable that's globally available which was that -G flag.
- 21:29
Cool.
- 21:30
So if I run Cordova, I get this output which is kinda nasty and big and weird.
- 21:35
Cordova's really low level.
- 21:38
Cordova is what we compose phone gap out of.
- 21:40
That's how we build phone gap.
- 21:42
You don't have to ever use Cordova if
- 21:44
you're not interested in it, it's just a tool.
- 21:47
So I can do Cordova create fubar.
- 21:54
And the first time I do this, it's going to have to download.
- 21:58
The platforms that I'm building for.
- 22:02
Cordova's lower level and so everything is kind of composable and you
- 22:05
can cut and paste little bits and pieces of it, treat everything differently.
- 22:10
So,
- 22:14
oh, fubar.
- 22:16
So again, totally the same thing, I've got an index.html, a www folder.
- 22:25
I have got these completely unnecessary type declarations.
- 22:31
So I am gonna go at HTML5 and kill that.
- 22:35
I hate that.
- 22:36
I don't know why.
- 22:37
But if I do, like, Cordova run ios, it's gonna yell at me.
- 22:42
It's gonna be like, oh, you can't do that.
- 22:44
So Cordova doesn't have any knowledge or try and help you.
- 22:49
Again it's low level and you can pose apps
- 22:51
out of it so I have to do Cordova platform.
- 22:54
Add IOS Android Firefox OS, whatever.
- 22:59
And it's gonna install and create those projects for me.
- 23:01
And in case of phone gap it just does that stuff automatically.
- 23:05
So these are the subtle differences between the two.
- 23:07
A lot of people build on top of Cordova and we didn't really
- 23:10
wanna like lock Cordova into a particular work flow because it's an upstream.
- 23:16
It's kinda like a gnarly, composable situation.
- 23:20
Now you as a developer, you may want to utilize that, though.
- 23:25
So earlier I glossed over this but there's this www
- 23:29
folder and we've got index.html in there and some assets.
- 23:33
We also have this platforms folder.
- 23:35
So inside of platforms you noticed earlier that I added Android Firefox OS in an IOS.
- 23:41
Each of these is a native project to that platform.
- 23:45
And this is sorta one of the others misconceptions about
- 23:49
PhoneGap people are like, oh, PhoneGap projects they are not native.
- 23:53
Yeah, they super are.
- 23:54
That's how we do it, that's how it actually works.
- 23:57
So this is a native Android project with native code and everything.
- 24:02
You can instrument if you would be so interested in doing that.
- 24:07
This is a part of your project we don't dictate whether or not you
- 24:12
wanna get in there and do native
- 24:13
development but it's your option to do that.
- 24:16
And that's how it works.
- 24:18
So I added those platforms whatever and then I can do like cord overrun IOS.
- 24:24
For example, and very much like phone gap,
- 24:26
it's gonna run that command for me eventually, probably.
- 24:30
Dump a bunch of ex-code garbage out to my terminal.
- 24:33
Try and find a simulator, didn't find one, some ugly guy,
- 24:41
not my company, slack.
- 24:43
There we go.
- 24:43
So, Cordova, different branding, same gig, if that makes sense.
- 24:53
So Cordova's at the Apache Software Foundation.
- 24:57
Apache is this non-for-profit open source foundation where code can live happily in
- 25:04
a neutral territory free of legal woe from other companies or any company, really.
- 25:10
Apache owns the trademark to Cordova.
- 25:12
That means that all the source code of Cordova is free and will remain free.
- 25:16
That's kind of important.
- 25:18
Apache came from the Apache web server, so it's got good web roots.
- 25:22
Apache claims that individuals compose the ASF.
- 25:25
I am inclined to believe this because you have to sign
- 25:28
an individual contributor license agreement or
- 25:31
the contribute code back to Apache.
- 25:33
However truthfully, a lot of organizations work with Apache.
- 25:37
So, the ASF, as we like to call it has a lot of
- 25:40
different principles and these principles are sort
- 25:42
of interesting and we are talking about.
- 25:44
The ASF believes in collaborative software development.
- 25:47
We believe in a commercially friendly license.
- 25:49
This is hugely important and different than most other free software foundations.
- 25:56
We believe in high quality software and we
- 25:58
try and get there by having continuous integration.
- 26:00
We believe in respectful, technical, honest based interaction.
- 26:04
At least that's what we say on this slide.
- 26:06
And we believe in a faithful implementation standards.
- 26:08
This was one of the reasons that we ended up at Apache.
- 26:11
The Apache web server was obviously instrumental
- 26:14
in the net as we see it today.
- 26:15
And phone gap in Cordova had an initial goal of ceasing to exist.
- 26:20
Sounds contrary and weird.
- 26:21
Why would we want that?
- 26:22
Well actually we don't want to build native apps.
- 26:24
We don't wanna dive into proprietary traps.
- 26:27
We really want is to build web apps.
- 26:30
Unfortunately, mobile isn't going that way and
- 26:33
so that's why there's something called phone gap,.
- 26:36
And ultimately, the reason we chose the Apache Software Foundations is
- 26:39
because it was a web believer, security is a mandatory feature.
- 26:45
And that comes back to how we do things.
- 26:47
Apache has all these sorta arcane and weird
- 26:50
rules about incubation and is actually, like, a
- 26:52
22-year-old organization believe it or not and so
- 26:54
open source has been happening for a long time.
- 26:57
To get into Apache is one thing and then to actually
- 26:59
become called a Top Level Project is another thing all together.
- 27:02
So when we first joined Apache we had to
- 27:05
go through an incubation process, which thankfully we survived.
- 27:09
So earlier I said individuals compose the ASF and that's totally true
- 27:14
but actually a lot of organizations sponsor software development at the ASF.
- 27:18
And the big reason for that is
- 27:19
the Apache software license is very commercially friendly.
- 27:22
And so all these company's can collaborate and donate code back to the
- 27:27
Apache software foundation ultimately Cordova without
- 27:30
any kind of legal ambiguity around patenting.
- 27:33
And so we've got Adobe, BlackBerry, Google, Microsoft,
- 27:39
IBM, Intel, Mozilla, and believe it or not LG, all working towards this end.
- 27:46
Which is great.
- 27:48
I think there's 67 sponsored full-time developers now
- 27:51
working on the thing called phone gap, ultimately Cordova.
- 27:57
So we used to have this sort of bad habit where we were shipping a lot of software
- 28:01
all the time but we weren't versioning it, we
- 28:03
weren't doing proper releases really and that was okay.
- 28:09
And it went on for a long time.
- 28:11
We actually sat on 0.8 for, I shit you not, almost a year and a half.
- 28:15
And so people would file bugs and we'd be like, oh it's weird, it works for me.
- 28:19
What version?
- 28:20
Oh, right, you're on the same version I am.
- 28:23
And so versioning we realized was actually just creating a window for bugs.
- 28:28
And so we adopted some people call this rolling releases or some I don't really
- 28:36
it, but some people call it like the agile release train, I just hate the word agile.
- 28:40
It sounds really like I'm trying to sell you something, but I'm not.
- 28:43
So, I like to call it the heartbeat of the cadence and
- 28:46
by the way, these slides are all online and this is a link.
- 28:49
Or I did a long probably kind of boring blog post about
- 28:56
why we ship software the way we ship it, a few years back.
- 29:01
Effectively, we try and ship it every month.
- 29:03
And so, we close the window on where the bugs could possibly be.
- 29:07
Sometimes, people don't love this.
- 29:08
So they go, you guys ship too much.
- 29:10
Like, I have actually heard that.
- 29:12
Shipping is the actually the only goal that open source project.
- 29:15
And by closing that window for bugs that means
- 29:17
that we can get consistently higher quality software releases.
- 29:22
If you're in one of those projects, where you're shipping once a year.
- 29:26
You've just created a one year window of bugs.
- 29:28
That's totally not actually helping your ultimate goal of
- 29:32
getting out there and having consistently high quality software.
- 29:35
Shipping more often is a good thing.
- 29:39
We've got rules about how to contribute effectively.
- 29:41
We're a GitHub project.
- 29:43
I'm gonna show this to you just for morbid curiosity.
- 29:46
If we go to github.com/apache.
- 29:48
You're gonna see that there's a buttload of Apache projects.
- 29:55
But if I filter in on Cordova you can see that we've got a lot of reposts.
- 30:02
I think we're at something like 50 or more reposts of good software so.
- 30:14
How do you contribute.
- 30:14
Well, you use GitHub basically.
- 30:17
Contributing's different than committing.
- 30:19
So commit rights are when you can
- 30:22
contribute without basically someone else merging that commit.
- 30:25
To become a committer is an honor in an open source project.
- 30:30
And it's not very hard and so, some projects have a high
- 30:33
bar of entry and we didn't really see the point in that.
- 30:36
You could have certain projects where you have to have multi-years of contributing
- 30:41
before you can become a committer and get commit rates and get that trust.
- 30:44
We sort of figured this whole internet thing's got legs and you
- 30:48
know, there's an audit trail built in, so we don't really care.
- 30:51
If you land a single commit we will
- 30:54
eventually give you commit rights to the entire project.
- 30:58
What that means is, you get a shiny Apache
- 31:00
- 31:02
And lowering up our entry is actually just enabled us
- 31:05
just to move even faster and we've got a bunch of
- 31:08
rules about how that works, so Apache's is cool because once
- 31:11
you get a commit rights at Apache you don't even need
- 31:14
commit rights then you become a part of bigger family and
- 31:17
there is a whole lot interesting projects at work in Apache
- 31:21
not just phone gap there's couch TO, Dupe, OpenOffice and many
- 31:24
many more including the web server so once you get involved
- 31:28
in this sort of open source community.
- 31:31
You really open up your opportunities as a software developer.
- 31:34
You can learn a lot of different stuff and you
- 31:36
can contribute back to the commons which is kind of cool.
- 31:39
Probably not a surprise, we really do love Apache and
- 31:42
things have worked out quite well by us being there.
- 31:46
So Cordova is low level and kind of hard to use,
- 31:49
it's not really for the faint of heart and this is
- 31:52
getting into the guts of how software projects work and we
- 31:55
also have this sort of concept of project level versus platform level.
- 31:58
So project level would be this guy.
- 32:04
Where I've got this project.
- 32:05
And platform level would be one of these guys.
- 32:09
Where I'm building a project right on the middle.
- 32:12
In the case of Android, I've got this assets www
- 32:16
folder, in the case of iOS it's in the root.
- 32:21
In the case of Firefox I believe it's in the root as well.
- 32:24
So that's the thing that they all have in common.
- 32:27
We don't stop you from working at the platform
- 32:33
level if you want to.
- 32:34
If you just want to build an iOS project,
- 32:36
you can super do that and it's totally cool.
- 32:38
You can even go so far as to ignore our command line tooling.
- 32:42
And do a painful search to find Cordova iOS and inside of Cordova
- 32:47
iOS we actually have what's called these bin scripts.
- 32:53
And so these include the ability to create
- 32:56
projects, emulate them and do whatever you want.
- 33:00
This is another kind of, interesting thing.
- 33:02
We, we initially built PhoneGap as this fancy web view that we stretched to
- 33:06
100% width and height but truly it's become more of a workflow tooling thing.
- 33:10
And so, it probably doesn't come as a surprise but building
- 33:14
projects for iOS is semantically completely
- 33:18
different than building projects for Android.
- 33:20
Like creating a project is totally different.
- 33:23
Android we need ant or possibly gradle.
- 33:25
In the case of iOs we have to use
- 33:28
XCode which is sort of like iTunes but it's Eclipse.
- 33:34
And it doesn't really matter once you
- 33:36
learn those things, but moving between those platforms
- 33:39
becomes this massive, kind of cognitive overhead
- 33:42
where you're like, how do I compile again?
- 33:44
Oh I've got to run ant.
- 33:45
And so, one of the things that we ended up doing was painting over the
- 33:48
differences so compiling emulating and logging is all
- 33:52
a bit normalized into a set of scripts.
- 33:57
We have another tool called plugman aptly named awesome
- 34:01
dude, plugman gives us the ability to deal with plugins.
- 34:04
And so this is where we get into kind of
- 34:06
the guts and the interesting things that phone gap can do.
- 34:09
Phone gaps not just a thing to create a fancy
- 34:12
web view that stretches to one hundred percent width and height,
- 34:15
it also gives you access to all of the native
- 34:17
features of the device that you happen to be running on.
- 34:19
So if you got our docks we used to have these like long API docks and.
- 34:29
Nowadays we don't, we just have what are called plugin APIs.
- 34:32
I'm sorry if this is hard to read.
- 34:33
But there are all these various plugins like,
- 34:36
I don't know, let's go to something fun.
- 34:39
Dialog, sure.
- 34:42
So.
- 34:44
If you go to plugins.cordova.io, you can see the current listing of all
- 34:49
the plugins that we've written, and other people in the community have written.
- 34:53
And these plugins expose native features, whatever they might be.
- 34:58
We turn the web view into something more powerful.
- 35:02
In the earliest versions of Phone Gap, when
- 35:04
we figured out that we could actually hook
- 35:06
up the web view to native events, one of the first things we did was Accelerometer.
- 35:10
One of the later things we did was Geolocation.
- 35:12
But we made up an API.
- 35:14
And we were like, well that's cool except that it's
- 35:17
not really scalable and it's not going to last, right.
- 35:19
If we make up some API from version to version it's not going to go anywhere.
- 35:23
And so we started to look through the W3C and how they built things.
- 35:26
And anything that has word Apache in its namespace will be an API that
- 35:35
probably has been sort of blessed by the W3C in some way.
- 35:39
Dialogues is a bad example but a good example would be geolocation.
- 35:43
So in Phone Gap 0.8 we implemented the GeoLocation spec.
- 35:48
We were the first implementors of it, we did it before the browser did it.
- 35:52
So early Phone Gap, you could get your geolocation.
- 35:54
And now that's not a normal thing to have in an
- 35:57
app but at that time that was exciting and new and different.
- 35:59
Having, like, the ability to access, you know, GPS was huge.
- 36:03
Interestingly, apps built for Phone Gap 0.8 run today
- 36:08
in your web browser because we targeted those standards.
- 36:12
And so implementing web standards turns out to
- 36:14
be a really good thing for all of us.
- 36:16
It ran on iOS, it ran on Android and now it runs on the regular web.
- 36:19
And that was kind of the goal.
- 36:21
That was sort of what we were going for.
- 36:24
So Plugman allows us to find these plugins, install them and remove them.
- 36:29
And you know what actually I should probably show that in action.
- 36:32
So I'm gonna go back.
- 36:38
Let's take a look at this registry.
- 36:39
So actually what I'll do, we'll do some fun live coding.
- 36:44
I'm in my app ready for Firefox OS.
- 36:48
Everyone's excited.
- 36:50
Is anyone, has anyone even seen a Firefox OS phone here?
- 36:56
Cool.
- 36:57
If anybody wants to see one I've got a few.
- 37:00
They're pretty rare.
- 37:03
It's a phone that's HTML, CSS and
- 37:05
JavaScript, so you can't be bummed about that.
- 37:07
So I'm a web developer and I'm going to do some debugging.
- 37:17
Hardcore Java developers would laugh once I
- 37:19
did that but this is how debug sometimes.
- 37:23
And you'll notice that I'll
- 37:29
phone gap run it, oh, really?
- 37:36
Huh.
- 37:39
Fubaz?
- 37:44
Well.
- 37:56
No!
- 38:00
Okay.
- 38:00
Okay, let's try that again.
- 38:05
Okay, I'm gonna alert, cause I'm a
- 38:07
JavaScript developer and that's how I debug.
- 38:10
PhoneGap run iOS.
- 38:15
Find it, we're gonna compile.
- 38:19
Eventually, it's gonna try and find a simulator.
- 38:22
It does.
- 38:27
Okay.
- 38:29
So cool.
- 38:30
I alerted which is a totally normal thing to
- 38:32
have to do to send a notification however you
- 38:35
may notice that there might be a giveaway in
- 38:37
this alert that I am not a native application.
- 38:41
And that super bums out your client, right?
- 38:44
He's not gonna be stoked about that.
- 38:46
Index HTML also probably doesn't build confidence in
- 38:49
your security of your app, whatever it might be.
- 38:52
And there's a good reason for that.
- 38:53
So PhoneGap applications run on the file protocol.
- 38:57
So file:// that's how we run everything.
- 39:00
We just look a www folder and we load what's in there.
- 39:03
And that's totally sweet.
- 39:04
Except for alerts are going to tell us that they're running from index.html.
- 39:12
Not all is lost cause we can run this little puppy here cordova.plugin.add.
- 39:20
You can also do phonegap.plugin.add.
- 39:23
To install our dialogue's plugin.
- 39:26
Which, I shit you not is going to install Native Code for Native Dialogues.
- 39:32
Do not look at my slack.
- 39:34
So I've got this, slightly different interface.
- 39:39
[BLANK_AUDIO]
- 39:41
Just gonna copy and paste cause I'm a
- 39:43
lazy bastard, software developer like the rest of you.
- 39:48
And underneath this hi, we're gonna create an alert.
- 39:55
We're gonna give it a message.
- 39:57
We are going to just.
- 40:00
Not allowed to call back.
- 40:02
Oops.
- 40:04
Give it a title and a button name.
- 40:06
Let's see if that works [SOUND].
- 40:13
A recompile.
- 40:19
Remember, we alerted once already.
- 40:20
[BLANK_AUDIO]
- 40:30
[SOUND] Macbook Air's, not super sweet for memory.
- 40:35
Let's try that again.
- 40:36
If
- 40:39
you're compiling stuff.
- 40:41
A lot, on these machines.
- 40:44
It's not always, compassionate to that.
- 40:49
There we go.
- 40:50
So index html.
- 40:51
The first time, oh, oh no.
- 40:53
My
- 40:56
demo failed.
- 41:02
Hm, did I save?
- 41:10
Nah we'd get a notification blurb, oh,
- 41:14
you know what it is.
- 41:16
Document at [INAUDIBLE] [LAUGH].
- 41:20
[INAUDIBLE].
- 41:29
>> So, yeah?
- 41:29
>> I think [INAUDIBLE] semicolon [INAUDIBLE].
- 41:30
>> Oh, no, that's not it.
- 41:37
That's totally fine.
- 41:38
It's because I forgot to, bind to a callback on device ready.
- 41:44
So, phone gaps asking for device ready.
- 41:48
Semicolons actually don't matter that much.
- 41:50
Douglas Crockford hates me for saying that, but it's true.
- 41:54
So, what are you gonna do?
- 41:58
I think you might have misspelled [INAUDIBLE].
- 42:01
>> Did I?
- 42:02
It's very
- 42:07
possible.
- 42:13
I did.
- 42:16
Add Event.
- 42:17
List.
- 42:19
[LAUGH]
- 42:22
[BLANK_AUDIO]
- 42:26
[LAUGH].
- 42:29
>> Wait a second.
- 42:32
Did I get that right?
- 42:33
[LAUGH] Yeah.
- 42:36
That's right.
- 42:37
Okay
- 42:37
[BLANK_AUDIO]
- 42:41
Sorry, it was a long night at the casino.
- 42:45
[LAUGH]
- 42:48
[BLANK_AUDIO]
- 42:54
Maybe.
- 42:56
Yeah.
- 42:57
So what happened there.
- 42:59
Let's take a look at that code.
- 43:02
If you go to GitHub.
- 43:04
Actually you can look in the browser, it's a, it's a
- 43:12
different plugin but it'll give you the same sense.
- 43:19
So [UNKNOWN] plugins are just like regular [UNKNOWN] kind of
- 43:22
apps in that we have a www folder where we put.
- 43:25
A little bit of JavaScript.
- 43:27
And that's where we define our interface, ultimately.
- 43:30
For the platform we might happen to be running on.
- 43:33
Most of this is totally uninteresting, except for this little bit right here.
- 43:39
Where you have this thing called exec.
- 43:40
And exec is how we do the binding back to the native code.
- 43:44
And so.
- 43:45
Oops.
- 43:46
Whoa, that was crazy.
- 43:47
If I take a look at this plugin code, I've
- 43:51
got a ww folder but I also have a source folder.
- 43:53
And in that source folder I have all the different platforms I support.
- 43:57
Including Amazon Fire OS, which is a phone you can't quite get yet.
- 44:02
And Firefox OS in other phones.
- 44:04
And if I jump into each one of these, I have native code.
- 44:07
Oh my God, super crazy!
- 44:10
And so, phone gap provides us plugin API, where
- 44:13
we can write native code, and we can plug
- 44:15
it in to any particular platform that we're dealing
- 44:17
with, and we can abstract that away and hide it.
- 44:19
And yes, this is how much code in
- 44:21
Objective C it takes, to show a fucking alert.
- 44:23
[LAUGH] [UNKNOWN] it's, it's an awesome language.
- 44:28
[BLANK_AUDIO]
- 44:30
So real talk.
- 44:32
I, I've shown you a whole bunch of hello worldy type of stuff.
- 44:36
Like I've shown you how to, basically just build something really quickly.
- 44:39
But is it actually possible to build an app using HTML, CSS, and JavaScript.
- 44:44
It is and we, we had doubts too.
- 44:48
Let's be really clear about this, it's not easy.
- 44:50
It takes, takes work and it's hard.
- 44:52
Your first inclinations gonna be to grab Twitter Bootstrap which
- 44:55
is terrible for mobile honestly, it's not designed for it all.
- 44:58
It's a megabyte of CSS for fuck's sakes, it's huge.
- 45:02
[UNKNOWN] pretty good.
- 45:03
And so, it's a better answer.
- 45:05
We created a top code as a way to look
- 45:07
at this problem, and to look at it very discreetly.
- 45:09
If we look at things like Twitter Bootstrap and
- 45:11
[UNKNOWN] Foundation, these are all in one, [UNKNOWN] massive frameworks,
- 45:15
with a ton of CSS and a ton of JavaScript, and a ton of images and a ton of fonts.
- 45:19
And you probably only use it for buttons.
- 45:21
And [LAUGH] it doesn't load well on mobile.
- 45:25
Weird.
- 45:26
So we decided to create something that was just
- 45:28
discreet and just CSS and addresses particular performance consideration.
- 45:33
When we look at performance.
- 45:35
You know, the network is bad.
- 45:36
We don't know, if we're online or offline even.
- 45:39
If we look at the execution runtime, it's kinda bad, you know?
- 45:43
We're on like, now we, we, we see quad-core phones, it does happen.
- 45:47
But, they're crummy.
- 45:48
[COUGH] >> Quad-core phones.
- 45:50
Layout and the Rendering, with the web.
- 45:52
I mean, we can't even fucking, vertically center stuff, it's terrible.
- 45:55
And so you look at the web and you go like wow, this totally sucks, so [UNKNOWN]
- 46:01
who I believe is doing a talk tomorrow, and is brilliant and is
- 46:07
worth your time to listen to and to learn from proposed the idea of Mobile First.
- 46:13
And we love this.
- 46:13
We're like, yeah, built for Mobile First.
- 46:15
And then everything's gonna be super easy.
- 46:17
Except, we don't even know what the fuck mobile means anymore.
- 46:20
It's mobile, like a computer that's on my face.
- 46:23
Is it like a watch, actually, there was a [UNKNOWN]
- 46:25
image on Twitter the other day, when someone, was like,
- 46:28
I invented a new smart watch, and they just drew
- 46:30
a watch on a wrist that said, you always have email.
- 46:34
Which I liked a lot.
- 46:35
[LAUGH] >> So what's mobile?
- 46:37
We don't know, and so I was throwing out the
- 46:39
idea that we, what we actually need is performance first.
- 46:42
What we need to do is think about
- 46:43
performance as like, kind of your fundamental idea.
- 46:45
When you're building your applications, we need to be fast.
- 46:47
Except if, if we really take performance first to its absolute
- 46:52
conclusion, we're gonna start writing assembler, she's not actually efficient.
- 46:58
That's not what people wanna do, so I was like you
- 47:00
know, performance first is actually kinda, not, not a cool way to
- 47:03
look at it, and what we, what we really need to think
- 47:05
about is like the people building applications, like who are these people?
- 47:08
Like, we need to think about the developers, is it maintainable?
- 47:11
Is it reuseable?
- 47:12
You know, can we build apps truly?
- 47:16
And that wasn't actually tenable either, and I
- 47:18
wanted all this goals and so I took all
- 47:20
of my new founded Adobe management experience and I
- 47:23
brainstormed really hard, and I came up with this.
- 47:27
What we need is mobile performance people first,
- 47:30
until [UNKNOWN] with you I didn't actually think that.
- 47:33
So it was productivity is an important part of this and reuse is an
- 47:36
important part, when you're building the applications,
- 47:38
you end up with, a dogpile situation.
- 47:41
You end up with a bunch of CSS that you included from a framework.
- 47:45
[LAUGH] Come on in.
- 47:47
It's cool.
- 47:48
So, so you use Twitter Bootstrap, great.
- 47:51
But you need a button that's slightly different in the Twitter Bootstrap button.
- 47:54
So, what do we all do?
- 47:56
We copy and paste the old button and then we change it a little bit.
- 48:00
Maybe we'll throw an important on there in a zed index of 999 just to be safe.
- 48:04
And then somebody else needs a button and so we end up with
- 48:06
this dogpile that is totally not actually productive, for what we're trying to do.
- 48:12
Lyza Danger Gardner wrote an amazing article on
- 48:15
a list apart called, Do as little as possible.
- 48:17
And being a burned out stoner skateboarder,
- 48:20
I am super stoked on this philosophy.
- 48:23
I think doing as little as possible is not
- 48:25
actually a way of saying I don't wanna do anything.
- 48:27
It's saying let's do what counts, right?
- 48:30
Fastest code is no code.
- 48:32
We had a client come to us once, by Toby, and they were
- 48:34
like imagine Facebook, but with like ten times as many features, on your phone.
- 48:41
Wouldn't that be awesome?
- 48:42
I'm like no, [LAUGH] that's terrible.
- 48:44
That's an awful idea.
- 48:46
We don't want that at all.
- 48:47
We want like the simplest thing that could possibly work.
- 48:51
A part of building performing apps is also measuring absolutely everything.
- 48:54
So these tools are now maturing a, a while ago this
- 48:59
was not really possible but now we can get into actual.
- 49:01
Performance and window timing metrics.
- 49:04
So, we are looking like okay, we hear everyone has performance problems.
- 49:08
We know that the maintenance of these things is terrible because everyone
- 49:11
dogpiles CSS and we also found that between Twitter, Bootstrap and three.
- 49:15
Did anyone do that upgrade?
- 49:17
No you didn't, because it sucked.
- 49:18
You just built other apps.
- 49:20
It's really [LAUGH] hard to do.
- 49:22
We also had other motivations in Adobe, where
- 49:25
we wanted to see if we could build apps.
- 49:27
We built a thing called reflow and a thing called brackets using
- 49:30
HTML, CSS and JavaScript and we wanted to build discreet small reusable components.
- 49:34
So our first cut at topcoat was the CSS library that gave us
- 49:37
lists and buttons and that sort of thing we built the Adobe MAX
- 49:40
application, but we didn't tell anyone that we built it, and everyone was
- 49:44
like, man this thing is awesome, you guys should have built a PhoneGap app.
- 49:49
We're like no it, it is.
- 49:50
And they're like no, no, this is really fast.
- 49:52
[LAUGH] We're like no it really is.
- 49:55
So Top Code's got some basic design goals.
- 49:58
It's discreet, it's modular, it's
- 50:00
extensible, it's friendly, it's open source.
- 50:04
I don't have time to show it to you but you can check it out at topcode.io.
- 50:10
If you're interested there is zero prerequisite to even try it out.
- 50:15
It's kind of interesting.
- 50:16
We built it with benchmarking in, in mind where we would take every commit and
- 50:22
we would measure the speed of that commit
- 50:24
on frames per second, layout and execution time.
- 50:27
All that code actually is now kinda in the browser and reusable.
- 50:31
And then we generate a style guide for you.
- 50:33
Depending on like what platform you're on and
- 50:35
we give you a bunch of reuse, reusable components.
- 50:38
We give you little code snippets where you can copy and paste from.
- 50:41
We had some good advice from a software developer who is much smarter than me.
- 50:45
He's like listen Brian, everyone is copy and pasting anyways, so
- 50:49
you may as well give them something good to copy and paste.
- 50:52
Which is, probably really smart.
- 50:57
So the question that I've asking lately if you look at Chrome OS, Win JS,
- 51:03
Firefox OS, Samsung and Intel's Tyzen and even WebOS which is owned by LG.
- 51:10
All of these are web based operating systems.
- 51:13
We think about it, Google, Microsoft, Mozilla, Intel, Samsung, and LG are
- 51:19
all betting on the future, of operating systems being a web based kind of future.
- 51:25
In the meantime, you can hit all these bad boys with PhoneGap if you want to.
- 51:29
Interestingly also, all these app stores are embedded web views themselves.
- 51:35
There's some perceived competition out there.
- 51:37
I don't think that's actually useful, it's an
- 51:38
open source project, we learn from each other.
- 51:40
That's sort of my take away on that one.
- 51:42
But we've got a bunch of tools and
- 51:44
outputs that you can check out if you're interested.
- 51:48
We're very empirical, we have the idea of performance built into what we're doing.
- 51:52
You can use all of it or none of it.
- 51:56
And, you should just go and build a kickass app.
- 51:58
[APPLAUSE]
- 52:04
We maybe have like a minute for questions, or you could just buy me a beer later.
- 52:09
Or I'll buy you a beer really.
- 52:12
And I owe Cable guy a beer.
- 52:15
So thanks.
- 52:16
Does anyone have a question?
- 52:19
Do like one or two.
- 52:20
Yeah.
- 52:20
>> I already have an app.
- 52:23
How much work.
- 52:23
I wasn't planning on going mobile, but I want to know
- 52:27
how much work will I have to do to get ready
- 52:31
>> Is, is it a single page web app?
- 52:32
>> It's, it is.
- 52:34
It's a media app.
- 52:36
>> Yeah, it will work.
- 52:38
You'll have to be responsive to a handset form factor or
- 52:42
possibly tablet if that's what you're going for, but that's it.
- 52:46
Yeah, one of the interesting fun things
- 52:48
that we learned by stretching that web view.
- 52:50
Whereas, you know, a web view that stretches
- 52:52
so any kind of responsive design programming style will
- 52:56
work inside a PhoneGap the same way it would
- 52:58
work as you were building for a regular browser.
- 53:01
Yeah, it's, it's, it's literally ten minutes to figure it out.
- 53:06
We have an app in the app store which
- 53:08
I should have mentioned If you go to app.phonegap.com.
- 53:14
And you install, one of these apps for one of these platforms.
- 53:18
You compare it to your local machine and try PhoneGap without installing anything.
- 53:23
It'll take you like two minutes.
- 53:25
So, maybe you can figure out if it works.
- 53:27
Yeah.
- 53:28
>> If you have a mobile website like.
- 53:29
[INAUDIBLE] our app in the mobile.
- 53:32
Is there any [INAUDIBLE] in using PhoneGap to make [INAUDIBLE].
- 53:36
>> It depends.
- 53:36
I, I don't like people doing that truly but my opinion is extreme and
- 53:40
harsh, but I know, I think these app stores are an aberration and a mistake.
- 53:45
I don't like the idea that I have to pay $100 to
- 53:48
Apple to build something to a device I already fucking own, but.
- 53:52
You know, the app store is a discovery channel.
- 53:54
So, is, is it worth it?
- 53:58
Probably we've got examples of PhoneGap apps that I, you know, I would preferred
- 54:04
they didn't exist but they, they do like 5,000 downloads a day or more.
- 54:09
So, yeah.
- 54:10
It's probably worth wrapping.
- 54:12
It's a discovery channel.
- 54:14
I don't like it, but that's how it works.
- 54:16
I used to, I used to say device APIs
- 54:18
and offline were important, but the web has caught up.
- 54:20
Sorry.
- 54:21
Yeah.
- 54:22
[INAUDIBLE].
- 54:26
>> Yeah.
- 54:26
So we, we work with all [UNKNOWN] earlier I was sort of joking about how
- 54:34
Like, here's my project fubar, and I've got platforms
- 54:37
iOS, I can jump in there and launch Xcode.
- 54:40
If you haven't seen Xcode, it's basically
- 54:43
like, imagine if Eclipse looked like iTunes.
- 54:49
It's just a native project so you can totally
- 54:51
use all the native tools that you want to use.
- 54:54
There's nothing stopping you.
- 54:55
And we can compile from here.
- 54:56
>> Nothing?
- 54:58
>> Debugging, everything, yeah.
- 54:59
[BLANK_AUDIO]
- 55:05
>> Yeah, Eclipse, or Android Studio if you hate yourself.
- 55:08
You can use all those tools.
- 55:10
[LAUGH].
- 55:11
>> Yeah?
- 55:12
[INAUDIBLE].
- 55:14
>> Sorry?
- 55:15
[INAUDIBLE] >> yeah, yeah.
- 55:20
So there's, there's plugins to do that for various platforms.
- 55:26
Totally.
- 55:26
In fact PayPal uses PhoneGap.
- 55:29
So [INAUDIBLE].
- 55:32
[INAUDIBLE].
- 55:34
>> You would, and you would have to do that
- 55:36
if were writing native code too, so, there's no difference there.
- 55:40
Yeah.
- 55:41
[INAUDIBLE].
- 55:46
>> We have an upgrade command it's not always compassionate, truly we play
- 55:51
cat and mouse right, like we are, we are always chasing whoever updates last.
- 55:56
And iOS 8 is, you know, our latest bug bearer that we are dealing with.
- 56:00
we, the upgrade command probably will work between
- 56:05
versions of an operating system, but in a major
- 56:08
upgrade, like iOS 7 to iOS 8, you'll
- 56:10
probably just be able to reuse the ww folder.
- 56:12
The platform folder you will probably have to blow away and re, re-add.
- 56:16
[INAUDIBLE]
- 56:19
>> Again, we keep those all updated, and it's the same situation.
- 56:21
You'll have to blow them away and add them again.
- 56:24
But I, we try and treat platforms and plugins as build artifacts.
- 56:28
We let people still modify that because we don't wanna get too, into it.
- 56:32
Yeah.
- 56:35
You can, keep those around and upgrade them if you want to.
- 56:37
Oh, I'm getting kicked off.
- 56:41
Thanks everyone.
- 56:43
[LAUGH].
- 56:45
[APPLAUSE] | https://teamtreehouse.com/library/build-fast-and-beautiful-native-apps-with-web-tech-using-phonegap-and-topcoat | CC-MAIN-2018-17 | refinedweb | 11,398 | 83.15 |
I need to calculate the average of values that are between 2 indices. Lets say my indices are 3 and 10, and i would like to sum up all the values between them and divide by the number of values.
Easiest way would be just using a for loop starting from 3, going until 10, summing 'em up, and dividing. This seems like a really non-pythonic way and considering the functionalities Numpy offers, i thought maybe there is a shorter way using some Numpy magic. Any suggestion is much appriciated
To access all elements between two indices
i and
j you can use slicing:
slice_of_array = array[i: j+1] # use j if you DO NOT want index j included
and the average is calculated with
np.average, but in your case you want to weight with the number of elements, so you can just use the
np.mean:
import numpy as np mean_of_slice = np.mean(slice_of_array)
or all in one go (using your indices):
i = 3 j = 10 np.mean(array[i: j+1]) | https://codedump.io/share/Y5z5K7OBd3ni/1/numpy--calculating-the-average-of-values-between-two-indices | CC-MAIN-2016-44 | refinedweb | 175 | 67.59 |
A set of plugins for setuptools_scm to enable better version tracking
Project description
A set of plugins for setuptools_scm to enable better version tracking
Installation
pip install pygitversion
Usage
The usage is almost exactly the same as using setuptools_scm, so follow those guidelines. This package merely adds a couple of plugin functions to make the versioning a bit better (eg. having the branch name in the version if applicable).
To summarise: create a pyproject.toml and include (at least) the following lines:
# pyproject.toml [build-system] requires = ["setuptools>=30.3.0", "wheel", "setuptools_scm", "pygitversion"]
Then in your setup.py, add the following to the call to setup():
# setup.py from setuptools import setup from pygitversion import branch_scheme setup( ... use_scm_version={ "local_scheme": branch_scheme }, )
You can now print the version of the package simply by doing:
$ python setup.py --version
To set the version of your code, make your __init__.py have the following:
from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed pass
And that’s it!
Development
To run the all tests run:
tox
Changelog
1.0.0
- Move to setuptools_scm
0.1.0 (2019-09-04)
- First release on PyPI.
Project details
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/pygitversion/ | CC-MAIN-2022-27 | refinedweb | 220 | 51.75 |
Extract and count countries and cities (+their synonyms) from text
Project description
flashgeotext :zap::earth_africa:
Extract and count countries and cities (+their synonyms) from text, like GeoText on steroids using FlashText, a Aho-Corasick implementation. Flashgeotext is a fast, batteries-included (and BYOD) and native python library that extracts one or more sets of given city and country names (+ synonyms) from an input text.
documentation:
introductory blogpost:
Usage
from flashgeotext.geotext import GeoText geotext = GeoText() input_text = '''Shanghai. The Chinese Ministry of Finance in Shanghai said that China plans to cut tariffs on $75 billion worth of goods that the country imports from the US. Washington welcomes the decision.''' geotext.extract(input_text=input_text, span_info=True) >> { 'cities': { 'Shanghai': { 'count': 2, 'span_info': [(0, 8), (45, 53)] }, 'Washington, D.C.': { 'count': 1, 'span_info': [(175, 185)] } }, 'countries': { 'China': { 'count': 1, 'span_info': [(64, 69)] }, 'United States': { 'count': 1, 'span_info': [(171, 173)] } } }
Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.
Installing
for usage:
pip install flashgeotext
for development:
git clone cd flashgeotext/ poetry install
Running the tests
poetry run pytest . -v
Authors
See also the list of contributors who participated in this project.
License
This project is licensed under the MIT License - see the LICENSE.md file for details
Demo Data cities from licensed under the Creative Commons Attribution 3.0 License.
Acknowledgments
Project details
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/flashgeotext/0.3.0/ | CC-MAIN-2021-25 | refinedweb | 255 | 53.81 |
, implement the valueBound() and valueUnBound() method. The valueUnbound() method will
be trigger if this object being unbound (This happen when the object is being replaced or session is invalid). In here, you can get the invalid session and delete away the record from the database.
public class BoundObj implements HttpSessionBindingListener
public BoundObj() {}
public void valueBound(HttpSessionBind
// Will be trigger when this object being bound.
}
public void valueUnBound(HttpSessionBi
HttpSession hs = be.getSession();
String userid = hs.getAttribute("userid");
String sessionid = hs.getID();
....
// Delete database record.
}
}
At the time the user login which you create a new session, put the bound object in that session.
session.setAttribute("boun
Sam | https://www.experts-exchange.com/questions/20285032/Question-for-coreyit.html | CC-MAIN-2018-22 | refinedweb | 107 | 51.85 |
In this post we will build a Serverless Microservice that exposes create, read, update, delete (CRUD) operations on a fully managed MongoDB NoSQL database. We will be using the newly release Lambda Layers to package the 3rd party libraries needed to integrate with MongoDB. We will use Amazon API Gateway to create, manage and secure our REST API and it’s integration with AWS Lambda. The Lambda will be used to parse the request and perform the CRUD operations. I’m using my own open sourced code and scripts, and AWS Serverless Application Model to test, package and deploy the stack.
Serverless is gaining more and more traction and can complete or complement containers. In serverless there are still servers, it’s just that you don’t manage them, you pay per usage and it auto scales for you. It’s also event-driven in that you can focus more on business logic code, and less on inbound integration thanks to growing number of Lambda event sources triggers such as Alexa, S3, DynamoDB and API Gateway built and maintained by AWS.
To make it more interesting, in this post I’m using a simplified version and subset of the pattern that I presented at AWS re:Invent 2016 and in the AWS Big Data Blog post you could use to implement real-time counters at scale with DynamoDB, from billions of web analytics events in Kinesis Streams as used in our in-house RAVEN Data Science Platform. Here the focus will be creating the front end for that rather than backend, i.e. a serverless CRUD REST API using API Gateway, Lambda and MongoDB.
MongoDB and my History with it
There are many NoSQL databases out there, such as Amazon DynamoDB which is a key-value and document store and integrates easily with the rest of the serverless stacks in AWS for which there are many blog posts, books, documentation and video courses including my own. As we have covered DynamoDB before lets talk about using MongoDB instead. If we look at some of the DB rankings it is doing very well at number 5 overall and number 1 for document-stores databases, and has some big names using it.
I’ve had some history with MongoDB. When we begun our journey of deploying machine learning in production in 2013 at JustGiving, a tech-for-good crowdfunding and fundraising platform that raised over $5 billion for good causes from 26 million users, and acquired for $121M by Blackbaud in 2017. I chose to call the product PANDA, and the second system we built was an offline batch training and inference engine (back then embedding data science in product was extremely rare and it was more local data science on a laptop, no Apache Spark, serverless or stable docker either). Those batch scores, inference or predictions would then be inserted at regular intervals in to MongoDB, and we would serve the predictions, recommendations and suggestions via our PANDA REST API that our front end services and mobile app would call. The beauty of this architecture, I came up with, was that we decoupled data science serving from frontend products, allowing us to move at different speeds and update the backends without them noticing.
At the time I chose MongoDB for the backend data store as it was a NoSQL database giving us flexibility to store data in JSON, retrieve it at very low latency, and could easily scale out through sharding. This was a great AI success story at JustGiving, and was the start of many subsequent case studies, keynotes, books, and recognitions. We no longer use MongoDB but PANDA is still used and new exciting features and experiments being added regularly. I got inspired to write this post from reading Adnan Rahić’s post on building a serverless API using node.js and MongoDB but here I’m using the more up to date serverless features from Re:Invent, my current favourite language Python, and the open-source AWS Serverless Application Model (SAM).
MongoDB Setup
MongoDB Atlas is what we will be using as it has a free tier with no credit card, and is a fully managed service.
Setting up a New Cluster
1. In your browser, go to the MongoDB web interface
2. Choose Start free
3. Type your email, first name, last name, password
4. Check I agree to the terms of service.
5. Choose Get started free
7. Choose Off for Global Cluster Configuration
6. Choose AWS for Cloud Provider & Region
7. Choose a region with the free tier available
* For those in America choose us-east-1
* For those in Europe choose eu-central-1
* For those in Asia chose ap-southeast-1 or ap-south-1
8. For Cluster Tier leave it at M0 (Shared RAM, 512 MB Storage)
9. For Additional Settings leave defaults
10. For Cluster Name type
user-visits
11. Choose Create cluster
* You will get captcha too
* This will begin creating the cluster
Configuring and Connecting to your Cluster
Lets now create a database user that the Lambda function can use, allow the Lambda to access the database by whitelisting the IP range and connect to the cluster.
1. Choose the Security tab and MongoDB Users
2. Choose Add New User sub-tab
3. In the SCRAM Authentication
* For username type
lambdaReadWriteUser
* For password type a secure password
* For User privilege choose Read and write to any databases
4. Choose IP Whitelisting sub-tab
5. Choose Add IP Address
6. Choose Allow access from Anywhere
* Security risk — you will see that CIDR
0.0.0.0/0 has been added allowing any system to access the database, generally a very bad security practice but fine for a proof of concept with demo data here.
7. Choose Confirm
8. Choose the Overview tab
9. Choose Connect in the Sandbox window
10. Choose Short SRV connection string under Copy the connection string compatible with your driver
11. Install the Python dependent packages
pymongo,
dnspythonand
bson
$ sudo pip install pymongo dnspython bson
or with
sudo pip install -r requirements.txt
Connecting to MongoDB Locally using Python
Create a Python script called
mongo_config.py and type or paste the following which stores the
db_username = "lambdaReadWriteUser"
db_password = "<my-super-panda-password>"
db_endpoint = "user-visits-abcde.mongodb.net/test?retryWrites=true"
db_port = "27017"
The
db_endpointis the host in the Short SRV, i.e. the part after the
@symbol. Here
testis going to be the name of the database, replace it with the desired name.
Security recommendations
There are some security risks with the above, so for production deployments I recommend:
* Use MongoDB AWS VPC peering Peering Connection (you will need to used payed M10+ instances)
* Do not use
0.0.0.0/0in the IP white list, rather launch the Lambda in a VPC and restrict it to that Classless Inter-Domain Routing (CIDR) or IP Range
* Do not use
mongo_config.py to store the password instead use KMS to encrypt it and store it in the Lambda environment variables.
Lets now create the four CRUD methods.
Creating the PUT Method
Create and run Python script called
mongo_modify_items.pyand type or paste the following
Here I use the repository design pattern and create a
class MongoRepositorythat abstracts and centralizes all the interactions with MongoDB including the connection and insertion of JSON records. When the
MongoRepositoryis instantiated we create the Short SRV connection string we saw earlier using the variables in
mongo_config.pyand parameters
mongo_db,
table_name.
In the
insert_mongo_event_counter_json() method I first shape the check the data has an
EventId then create an
entity_id entity_id with
EventId and
EventDay to serve as update filter similar to a primary key. The
{“$set”:{‘EventCount’: event_data.get(‘EventCount’, 1)}}is the update action, here we overwrite the existing
EventCount value for the update filter as it’s a PUT so should be idempotent — calling it many time has the same effect. Here I’m using
update_one()to show you the
$set operator but you could equally use simpler
insert_one() to add the JSON document to a MongoDB collection, see Mongo documentation.
When you run this you should get the following in the console
{'n': 1, 'nModified': 0, 'opTime': {'ts': Timestamp(946684800, 2), 't': 1}, 'electionId': ObjectId('7fffffff0000000000000001'), 'ok': 1.0, 'operationTime': Timestamp(1546799181, 2), '$clusterTime': {'clusterTime': Timestamp(946684800, 2), 'signature': {'hash': b'~\n\xa5\xd9Ar\xa5 \x06f\xbd\x8e\x9d\xc39;\x14\x85\xb6(', 'keyId': 6642569842735972353}}, 'updatedExisting': True}
Process finished with exit code 0
Notice the
’ok’: 1.0 meaning that the update was successful and
’n’: 1, ‘nModified’: 0 indicating that one record was added and no others modified.
13. In your browser, go back to the MongoDB web interface
14. Choose user-visits under Clusters on the left navigation bar
15. Choose Collections tab
You should see something like this
Run it again and you will see that the
EventCount : 1 which is the expected behavior.
Creating the GET Method
Let’s now add another two method called
query_mongo_by_entityid() and
query_mongo_by_entityid_date() to
class MongoRepository
def query_mongo_by_entityid(self, entity_id):
results = self.event_collection.find({'EventId': entity_id})
print("Query: %s found: %d document(s)" % (entity_id, results.count()))
return dumps(results.sort("EventDay", pymongo.ASCENDING))
def query_mongo_by_entityid_date(self, entity_id, entity_date):
entity_id = {'EventId': entity_id, 'EventDay': {"$gt": int(entity_date)}}
results = self.event_collection.find(entity_id)
print("Query: %s found: %d document(s)" % (entity_id, results.count()))
return dumps(results.sort("EventDay", pymongo.ASCENDING))
query_mongo_by_entityid()queries MongoDB by
EventIdand sorts the results by
EventDayin ascending order.
query_mongo_by_entityid_date()queries MongoDB by
EventIdand for
EventDategreater than the specified parameter, and sorts the result by
EventDayin ascending order.
Creating the POST Method
Let’s now add another method called
upsert_mongo_event_counter_json() to
class MongoRepository
def upsert_mongo_event_counter_json(self, event_data):
entity_id = {'EventId': event_data.get('EventId', ''),
'EventDay': int(event_data.get('EventDay', 0))}
if event_data.get('EventId', '') != '':
self.event_collection.update_one(entity_id,
{"$inc":{"EventCount":
event_data.get('EventCount',1)}},
upsert=True).raw_result
else:
print("No EventId, skipping record")
and call it in the main with
def main():
print(mongo_repo.upsert_mongo_event_counter_json(event_sample))
you will now see that the
EventCount : 2 run it again and you will see that the
EventCount will increase by
1. This is because the
$inc increments the
EventCount by the
EventCount value in the
event_sample dict if it is specficied otherwise it defaults to
1.
Creating the DELETE Method
Finally we need a method to delete the data too.
def delete_mongo_event_counter_json(self, entity_id):
return dumps(self.event_collection
.delete_many({'EventId': entity_id})
.deleted_count)
Here we chose to delete the records that match the given
entity_idparameter.
We now know how to connect locally and update records in MongoDB, lets now create the Lambda function with the same Mongo CRUD code as well as additional code needed for parsing the request, forming the response, and controlling the execution flow based on the HTTP Method. Before that let’s create the Role and policies needed by the Lambda.
Creating the Serverless Configuration
I assume that you have AWS CLI installed and with the keys, and if you have to be on Windows you are running a Linux Bash shell. You also have Python 3.6+ setup.
Creating Environment Variables
First I create config file called
common-variables.sh for storing all the environment variables. I like to do this is later on I can configure these in a CI/CD tool and it makes it easier to port to different AWS accounts.
Here I determine the AWS Account ID using the CLI, but you can also hardcode it as shown in comments, you can do the same with the region. You will also see that I have some Layers variables we will be using shorty to create the layer with the MongoDB packages that the Lambda will need for CRUD access to MongoDB.
Creating a Lambda Execution Role
First lets create a Lambda IAM Role than will allow the Lambda to write to CloudWatch.
Create a file called
assume-role-lambda.json with the following JSON content
Then we create a shell script called
create-role.sh with the following
Here we create a new Role called
lambda-mongo-data-api with the AWS Managed Policy
AWSLambdaBasicExecutionRole attached. This will allow us to store the logs in CloudWatch for any debugging and monitoring.
Run the shell script with
./create-role.sh to create the Lambda execution role and attach the policy.
Creating the SAM Template
AWS Serverless Application Model (SAM) is a framework that allows you to build serverless applications on AWS, that includes creating IAM Roles, API Gateway and Lambda resources. I prefer SAM over other popular frameworks like Serverless which is the frontrunner, as SAM is supported by AWS and not based on node.js but Python. It uses SAM Templates to define the serverless applications and uses AWS CLI to build and deploy it, which is based on CloudFormation.
Create a file called
lambda-mongo-data-api.yaml with the following
From top to bottom, I first define the type of SAM template with a description, then we define a set of parameters that are passed in at deploy time from
common-variables.sh. If the values are no passed in then they fall back to a default value:
*
PythonVersion default to python3.6
*
AccountId to the default value specified as
000000000000
*
AWSRegion the region
*
LayerName the name we will give to the layer
*
LayerVersion as each layer has a version each time you publish a new version
Each of these parameters is a placeholder that is replaced in the YAML with the
!Sub CloudFormation function.
We then have the CORS settings, Lambda configuration handler, code, name and other settings.
Then use the IAM Role we just created. I prefer to create the Roles separate from SAM as they can be reused more easily as they will not get deleted with the serverless stack. I also have an environment variable called
demo. I’m then listing the full
GET POST PUT DELETE methods explicitly for security reasons, but you could shorten it to
Method: ANY.
Creating the Lambda Function
Next lets create the Lambda function called
lambda_crud_mongo_records.py with the following:
There are three classes here from top to bottom.
* The
class HttpUtils is a set of utility methods for parsing the query string, body and returning a response.
* The
class MongoRepository we talked about earlier which abstracts and centralizes all the MongoDB interactions.
* The
class Controller controls the main flow and calls different Mongo methods based on the method, request parameters, and request body. Here the methods are
GET,
DELETE,
PUT. For the
GET method there are two types of queries we can do on Mongo depending if a
startDate is provided or not.
I’ve coded most of it defensively, so things like dealing with invalid JSON and non-numbers in the request, will not bring down the Lambda.
Creating the Packages
Once deployed to AWS, the Lambda will need the Python dependent packages
pymongo,
dnspython and
bson.
These need to be packaged and deployed for it to work. There are two ways this can be done. The first is using a
virtualenv to create the dependent packages and add the Lambda code, and compress them all together as a Zip package. The second and newer way, is the use Lambda Layers which is to have one package with the dependent packages as a Zip, and another one for the Lambda source code itself.
Create a Layer with MongoDB Depend Packages
What are Layers? They were introduced at RE:Invent 2018 and one of the most useful features for Lambda package and dependency management. In the past any non standard Python library or boto3 packages, had to be packaged together with the Lambda code. This made the package larger than it needed to be and also prevented reuse between Lambdas. With Layers any code can be packaged and deployed separately from the Lambda function code itself. This allows a layer to be reused for different Lambdas and for a smaller Lambda package with your code. Each Lambda function supports up to 5 Layers allowing you to abstract 3rd party dependency packages but also your own organization’s code.
Here lets create a package with the three dependent Python packages we need for the Lambda to connect and perform CRUD operations on MongoDB.
Create a file called
lambda-requirements.txt with the following
bson>=0.5.6
dnspython>=1.15.0
pymongo>=3.6.1
this contains the dependent packages that will be packaged in the Layer. I’ve added this as I don’t want to include other testing packages that are not needed which are in the
requirements.txt.
Create a script called
create-dependent-layer.sh with the following
All the environment variables are created from the `common-variables.sh` shell script we ran above.
This script first creates a virtualenv and installs the packages we specified in the
lambda-requirements.txt using
pip3 several options to minimize the amount of code and time it takes to install the dependent packages we are after.
The script then copies the dependent packages installed the a virtualenv into a directory
${packages_path}/${python_version}/site-packages/ which here is
../../build/python3.6/site-packages/ folder. Here I list the package folders explicitly as I found that sometimes the packages you pip install have different folder names so get missed out. For example the package
dnspython is actually stored under the
dns folder and not
dnspython like you would expect. I iterate over a list
${packages_array[@]} of packages and use
rsync to copy the files and directories. Note that for the Layer to work it need to follow a directory convention as shown here:
The convention for the
Python3.6 folder structure is
python/lib/python3.6/site-packages/.
We then create the Zip archive with packages. Here the
${target_package_folder#../} is used to strip off the leading
../ prefix as we only want to go up one level, and create the Zip archive under the
package folder. This create a
mongodb-layer.zip archive with the 3rd party packages in the correct folder structure
python/lib/python3.6/site-packages/.
We then copy the Zip archive to S3 using
aws s3 cp so that it can be used added as a Layer.
Finally we run
aws lambda publish-layer-version to publish this as a layer, again using the environment variables we created in the
common-variables.sh.
Run the script
./create-dependent-layer.sh to create the
mongodb-layer.zip
You will notice that each time you run this script, it will create a new Layer Version. The current version that the Lambda will use is specified in the
common-variables.sh.
There are other ways to create the packages used in a Layer such as using a docker container or EC2, but essentially the process is similar also using
virtualenv and
pip. At moment of writing AWS only has a
SciPy available, but I expect more to be added in the future.
Now that we have the Layer we need to build the Lambda archive.
Create a Package with Lambda
We then Zip the Lambda and packages using
create-lambda-package.sh
Here we create a Zip archive of the two python scripts
lambda_crud_mongo_records.py which has the Lambda code and
mongo_config.py which has the MongoDB credentials.
Run the script
./create-lambda-package.sh to check that the Zip archive get created.
We now have a Zip file with both the Lambda as
lambda-mongo-data-api.zip and it’s 3rd party dependent packages as reusable Layer
mongodb-layer.zip that has already been deployed. This layer can be used by any other Lambda in the account! Lets now look at how we can deploy API Gateway and the Lambda function using SAM.
Alternatively you can have SAM create the Zip file, but I prefer to control this process as for example a CI/CD step could create the Zip as an artifact that could be rolled back, and you could also introduce further optimizations to reduce the size or use byte code for example.
Building and Deploying the Serverless Microservice
Now that we have the Zip packages, either as one fat Zip with the Lambda and it’s 3rd party packages (as it would have been done in 2018 prior to AWS RE:Invent), or one Lambda Zip archive and one Zip for the Layers that we already deployed, lets deploy the full stack.
Building and Deploying the Lambda and packages as one Zip
Here are the contents of shell script
build-package-deploy-lambda-mongo-data-api.sh
*
aws cloudformation package packages the artifacts that the AWS SAM template references, creates a `lambda-mongo-data-api-output.yaml` template and uploads them to S3.
*
aws cloudformation deploy deploys the specified AWS SAM / CloudFormation template by creating and then executing a change set. Here that is the API Gateway and Lambda function. You can see that I can passing in some parameters that we saw earlier in the SAM YAML Template:
AccountId,
LayerName,
LayerVersion,
PythonVersion which we specified in the
common-variables.sh.
Now we just need to run the script to create the Lambda Zip, package, and deploy it along with the API Gateway.
$ ./build-package-deploy-lambda-mongo-data-api.sh
Testing the Deployed API
Now that you understand how to deploy the serverless stack and you could test the API Gateway and Lambda in the AWS Management Console or do automated testing on the API or Lambda, but here let’s focus on using an API testing tool called Postman to manually test it is behaving as expected. For the GET or DELETE methods we could use the browser, but we need a tool like Postman or insomnia because to test the PUT and POST methods we need to provide a JSON Body in the request.
1. Sign in to the AWS Management Console and open the API Gateway console
2. Choose Stages under APIs/apigateway-dynamo in the Amazon API Gateway navigation pane
3. Select PUT under Prod/visits/PUT to get the invoke URL
* The invoke URL should look like `https://{restapi_id}.execute-api.{region}.amazonaws.com/Prod/visits`
* We will use the invoke URL next
4. Download and install Postman
5. Launch Postman
6. Choose Request from Building Blocks or New > Request from the menu
7. In new Save Request Window
* In request name Type
put-api-test
* In Select a collection or folder to save to: Type
api-test
* Choose Create Collection “api-test” and select it in the list
* Choose Save to api-test
Testing the Deployed API PUT Method
1. Open a New Postman Tab
2. Choose PUT from the methods dropdown
3. In Enter Request URL type your deployed PUT URL, e.g. ``
* Choose PUT under APIs > user-comments > Stages
4. Choose Body tab
5. In the row under body select raw from the radio buttons and JSON (application/json) to it’s right
6. Type the following
{
"EventId": "2011",
"EventDay": "20171013",
"EventCount": 2
}
7. Choose Send
8. Check the response body, if it is
{“n”: 1, […] then it has been added otherwise you will get an exception message, check the URL, JSON body and method is correct.
9. Choose Send again twice, this should have no effect lets now look at the GET response.
Testing the Deployed API GET Method
1. Open the same tab in Postman
2. Change the method to GET
3. Append
/2011 to the URL
4. Choose Send
You should get the following response body:
[
{
"_id": {
"$oid": "5c3281a1b816a500d6a85afc"
},
"EventDay": "20171013",
"EventId": "2011",
"EventCount": 2
}
]
With the PUT method, the
EventCount value remains constant no matter how many times you call it, what is known as an idempotent operation.
Testing the Deployed API POST Method
Now let’s test the POST method that increments a counter by the specified value each time it is called, i.e. not idempotent operation. This could be useful for implementing counters such as real-time page views or scores.
1. Open the same tab in Postman
2. Change the method to POST
3. Remove
/2011 from the URL
* Like the original PUT URL
4. Choose Body tab
5. In the row under body select raw from the radio buttons and JSON (application/json) to it’s right
6. Type the following:
{
"EventId": "2011",
"EventDay": "20171013",
"EventCount": 2
}
7. Choose Send
8. Choose GET on the left and Send
[
{
"_id": {
"$oid": "5c3282c6b816a500d6a88210"
},
"EventDay": 20171013,
"EventId": "2011",
"EventCount": 4
}
]
Run it several times and you will see
EventCount increment, you can also increment it by less or more than
2 if you modify the request JSON body
EventCount value.
Testing the Deployed API DELETE Method
1. Open the same tab in Postman
2. Change the method to DELETE
3. Append
/2011 to the URL (like the GET)
4. Choose Send
You can also check MongoDB Console and you will see that there are no records
1. Open the MongoDB Console
2. In the navigation Select Clusters
3. In the Overview tab select user-visits
4. In user-visits select Collections
5. Under Namespace choose Dev > user-vists
* Mongo will run a query
6. You should get Query Results 0
Cleaning up
As we have used SAM to deploy the serverless API, to delete it simply run
./delete-stack.sh here are the contents of the shell script:
The
aws cloudformation delete-stack deletes API Gateway and Lambda. The Layers are deleted one at a time with the for loop. Here the
${layer_version} is fixed from the environment variables declared in
common-variables.sh but could easily be made dynamic by finding the current layer version.
1. Open the MongoDB Console
2. In the navigation Select Clusters
3. In the Overview tab select user-visits
4. In user-visits select Collections
5. Next to Dev > user-vists select Delete Icon
6. In the Drop Collection window type `user-visits`
Final Remarks
Well done you have deployed a serverless microservice with a full CRUD RESTful API with a MongoDB NoSQL backend. We have used the newly released Layers to package the MongoDB dependencies and tested it using Postman. I will be adding the full source code on GitHub shortly.
If you want to find out more on Serverless microservices and have more complex use cases, please have a look at my video courses and so support me in writing more free technical blog posts.
Additional implemented Serverless pattern architecture, source code, shell scripts, config and walkthroughs are provided with my video courses. For beginners and intermediates, the full Serverless Data API code, configuration and a detailed walk through
For intermediate or advanced users, I cover the implementation of 15+ serverless microservice patterns with original content, code, configuration and detailed walk through.
Feel free to connect and message with me on LinkedIn Medium or Twitter. | https://hackernoon.com/building-a-serverless-microservice-crud-restful-api-with-mongodb-6e0316efe280 | CC-MAIN-2019-39 | refinedweb | 4,467 | 63.29 |
money 1.1.0
Python Money Class
Money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange solution.
All code examples use Python 3.x.
Contents
Installation
This package is compatible with Python 2.7, 3.3, 3.4, but there are important Differences between Python versions.
pip install money
For locale-aware formatting, also install Babel:
pip install babel
Basic usage
>>> from money import Money >>> m = Money(amount='2.22', currency='EUR') >>> m EUR 2.22
amount can be any valid value for decimal.Decimal(value) and currency should be a three-letter currency code. You can perform most arithmetic operations between money objects and/or numbers (int, float, Decimal).
>>> from money import Money >>> m = Money('2.22', 'EUR') >>> m / 2 EUR 1.11 >>> m + Money('7.77', 'EUR') EUR 9.99
Formatting
Money objects are printed by default with en_US formatting and the currency code.
>>> m = Money('1234.567', 'EUR') >>> str(m) 'EUR 1,234.57'
Use format(locale=DEFAULT_LC_NUMERIC, pattern=None) for locale-aware formatting with currency expansion. format() emulates babel.numbers.format_currency(), and requires Babel to be installed:
>>> m = Money('1234.567', 'USD') >>> m.format('en_US') '$1,234.57' >>> m.format('es_ES') '1.234,57\xa0US$'
The character \xa0 is an unicode non-breaking space (chicken-good). If no locale is passed, Babel will use your system’s locale. You can also provide a specific pattern to format():
>>> m = Money('-1234.567', 'USD') >>> # Regular US format: >>> m.format('en_US', '¤#,##0.00') '-$1,234.57' >>> # Custom negative format: >>> m.format('en_US', '¤#,##0.00;<¤#,##0.00>') '<$1,234.57>' >>> # Round, Spanish format, full currency name: >>> m.format('es_ES', '0 ¤¤¤') '-1235 dólares estadounidenses'
Learn more about the formatting syntax:.
Currency exchange
Currency exchange works by “installing” a backend class that implements the abstract base class (abc) money.exchange.BackendBase. Its API is exposed through money.xrates, along with setup functions xrates.install(pythonpath), xrates.uninstall(), and xrates.backend_name.
A simple proof-of-concept backend money.exchange.SimpleBackend is included:
from decimal import Decimal from money import Money, xrates xrates.install('money.exchange.SimpleBackend') xrates.base = 'USD' xrates.setrate('AAA', Decimal('2')) xrates.setrate('BBB', Decimal('8')) a = Money(1, 'AAA') b = Money(1, 'BBB') assert a.to('BBB') == Money('4', 'BBB') assert b.to('AAA') == Money('0.25', 'AAA') assert a + b.to('AAA') == Money('1.25', 'AAA')
You can use a subclass of Money, XMoney if you prefer automatic conversion between different currencies on binary operations. The currency of the leftmost object has priority.
from money import XMoney # Register backend and rates as above... a = XMoney(1, 'AAA') b = XMoney(1, 'BBB') assert a + b == XMoney('1.25', 'AAA')
Differences between Python versions
Design decisions
There are several design decisions in money that differ from currently available money class implementations:
Localization
Do not keep any kind of locale conventions database inside this package. Locale conventions are extensive and change over time; keeping track of them is a project of its own. There is already such a project and database (the Unicode Common Locale Data Repository), and an excellent python API for it: Babel.
Currency
There is no need for a currency class. A currency is fully identified by its ISO 4217 code, and localization or exchange rates data are expected to be centralized as databases/services because of their changing nature.
Also:
- Modulo operator (%): do not override to mean “percentage”.
- Numeric type: you can mix numbers and money in binary operations, and objects evaluate to False if their amount is zero.
- Global default currency: subclassing is a safer solution.
Contributions
Contributions are welcome. You can use the regular github mechanisms.
To be forward-compatible, and given the small size of the package, Python 2.7 is supported in a different source “branch” at src-py2.
To test your changes you will need tox and python 2.7, 3.3, and 3.4. Simply cd to the package root (by setup.py) and run tox.
License
money is released under the MIT license, which can be found in the file LICENSE.
- Downloads (All Versions):
- 138 downloads in the last day
- 996 downloads in the last week
- 3714 downloads in the last month
- Author: Carlos Palol
- License: MIT
- Categories
- Development Status :: 4 - Beta
- Intended Audience :: Developers
- License :: OSI Approved :: MIT License
- Programming Language :: Python :: 2
- Programming Language :: Python :: 2.7
- Programming Language :: Python :: 3
- Programming Language :: Python :: 3.3
- Programming Language :: Python :: 3.4
- Topic :: Software Development :: Libraries
- Package Index Owner: carlospalol
- DOAP record: money-1.1.0.xml | https://pypi.python.org/pypi/money/1.1.0 | CC-MAIN-2015-27 | refinedweb | 753 | 52.66 |
Orange Widgets Reference Guide for Developers¶
Channels Definitions, Data Exchange¶
Input and output channels are defined anywhere within the __init__ function of a main widget class. The definition is used when running a widget, but also when registering your widget within Orange Canvas. Channel definitions are optional, depending on what your widget does.
Output Channels¶
Following is an example that defines two output channels:
self.outputs = [("Sampled Data", orange.ExampleTable), ("Learner", orange.Learner)]
self.outputs should thus be a list of tuples, within each the first element is a name of the channel, and the second the type of the tokens that will be passed through. Token types are class names; most often these are some Orange classes, but they can also be anything you may define as class in Python.
Widgets send the data by using self.send call, like:
self.send("Sampled Data", mydata)
Parameters of send are channel name and a token to be send (e.g., a variable that holds the data to be send through the channel).
When tokens are send around, the signaling mechanism annotates them with a pointer to an object that sent the toke (e.g., a widget id). Additionally, this annotation can be coupled with some name passed to send, in case you have a widget that can send few tokens one after the other and you would like to enable a receiving widget recognize these are different tokens (and not updates of the same one):
id = 10 self.send("Sampled Data", mydata, id)
Input Channels¶
An example of the simplest definition of an input channel is:
self.inputs = [("Data", orange.ExampleTable, self.receiveData)]
Again, self.inputs is a list of tuples, where the elements are the name of the channel, followed by a channel type and a Python function that will be called with any token received. For the channel defined above, a corresponding receiving function would be of the type (we would most often define it within the widget class defintion, hence self for the first attribute):
def receiveData(self, data): # handle data in some way
Any time our widget would receive a token, receiveData would be called. Notice there would be no way of knowing anything about the sender of the token, hence widget would most often replace the previously received token with the new one, and forget about the old one.
Widgets can often clear their output by sending a None as a token. Also, upon deletion of some widget, this is the way that Orange Canvas would inform all directly connected downstream widgets about deletion. Similar, when channels connecting two widgets are deleted, Orange Canvas would automatically send None to the receiving widget. Make sure your widget handles None tokens appropriately!
There are cases when widget would like to know about the origin of a token. Say, you would like to input several learners to the evaluation widget, how would this distinguish between the learners of different origins? Remember (from above) that tokens are actually passed around with IDs (pointers to widgets that sent them). To declare a widget is interested about these IDs, one needs to define an input channel in the following way:
self.inputs = [("Learners", orange.Learner, self.learner, Multiple)]
where the last argument refers if we have a “Single” (default if not specified) or a “Multiple” channel. For the above declared channel, the receiving function should include an extra argument for the ID, like:
def learner(self, learnertoken, tokenid): # handle learnertoken and tokeid in some way
Widgets such as OWTestLearners and alike use such schema.
Finally, we may have input channels of the same type. If a widget would declare input channels like:
self.inputs = [("Data", orange.ExampleTable, self.maindata), ("Additional Data", orange.ExampleTable, self.otherdata)]
and we connect this widget in Orange Canvas to a sending widget that has a single orange.ExampleTable output channel, Canvas would bring up Set Channels dialog. There, a sending widget’s channel could be connected to both receiving channels. As we would often prefer to connect to a single (default) channel instead (still allowing user of Orange Canvas to set up a different schema manually), we set that channel as the default. We do this by the using the fourth element in the channel definition list, like:
self.inputs = [("Data", orange.ExampleTable, self.maindata, Default), ("Additional Data", orange.ExampleTable, self.otherdata)] | http://orange.biolab.si/docs/latest/extend-widgets/rst/api/ | CC-MAIN-2014-10 | refinedweb | 726 | 55.13 |
Running PyTorch code on GPU - neural network programming guide
In this episode, we will learn how to use GPU and PyTorch. We will see how to use the general methods of GPU, and we will see how to apply these general techniques to train our neural networks.
Deep learning using GPU
If you haven't seen the episode about why deep learning and neural networks use GPU, be sure to review that episode with this episode to get the best understanding of these concepts.
Now, we will use an example of PyTorch GPU to lay the foundation.
PyTorch GPU example
PyTorch allows us to seamlessly move data into or out of the GPU when calculating inside the program.
When we enter the GPU, we can use the cuda() method. When we enter the CPU, we can use the cpu() method.
We can also use the to() method. When we go to GPU, we write ('cuda '). When we go to CPU, we write ('cpu'). The to() method is the preferred method, mainly because it is more flexible. We will see an example of using the first two methods, and then we will always use the to() variant by default.
In the training process, there are two basic requirements to use our GPU. These requirements are as follows:
1. Data must be moved to GPU
2. The network must be moved to the GPU.
By default, when creating PyTorch tensor or PyTorch neural network module, the corresponding data will be initialized on the CPU. Specifically, these data exist in the memory of the CPU.
Now, let's create a tensor and a network to see how we move from CPU to GPU.
Here, we create a tensor and a network:
t = torch.ones(1,1,28,28) network = Network()
Now, we call the cuda () method to reassign the tensor and network to the return value copied to the GPU:
t = t.cuda() network = network.cuda()
Next, we can get a prediction from the network, and see that the device attribute of the prediction tensor confirms that the data is on cuda, which is GPU:
> gpu_pred = network(t) > gpu_pred.device device(type='cuda', index=0)
Similarly, we can do the opposite:
> t = t.cpu() > network = network.cpu() > cpu_pred = network(t) > cpu_pred.device device(type='cpu')
In short, this is how we take advantage of PyTorch's GPU capabilities. We should now focus on some important details hidden under the surface of the code we just saw.
For example, although we have used cuda() and cpu() methods, they are not actually our best choice. In addition, what is the difference between the method of network instance and tensor instance? After all, these are different object types, that is, the two methods are different. Finally, we will integrate this code into a working example and do a performance test.
General idea of using GPU
The main conclusion is that our network and data must exist on the GPU in order to use the GPU to perform computing, which is applicable to any programming language or framework.
As we will see in the next demonstration, this is also true for CPUs. GPU and CPU are computing devices that calculate on data, so any two values directly used in calculation must exist on the same device.
PyTorch tensor calculation on graphics processor (GPU)
Let's take a closer look by demonstrating some tensor calculations.
We first create two tensors:
t1 = torch.tensor([ [1,2], [3,4] ]) t2 = torch.tensor([ [5,6], [7,8] ])
Now, we will check which device these tensors are initialized on by checking the device properties:
> t1.device, t2.device (device(type='cpu'), device(type='cpu'))
As we would expect, we see that, in fact, both tensors are on the same device, the CPU. Let's move the first tensor t1 to the GPU.
> t1 = t1.to('cuda') > t1.device device(type='cuda', index=0)
We can see that the tensor device has been changed to cuda, or GPU. Notice the use of the to () method here. Instead of calling a specific method to move to the device, we call the same method and pass a parameter specifying the device. Using the to () method is the preferred way to move data between devices.
In addition, please note the redistribution. The operation is not in place and needs to be reassigned.
Let's do an experiment. I want to know that we are trying to perform different calculations on the two devices t1 and t2.
Because we expect an error, we wrap the call in a try and catch an exception:
try: t1 + t2 except Exception as e: print(e) expected device cuda:0 but got device cpu
By reversing the order of operations, we can see that the errors have also changed:
try: t2 + t1 except Exception as e: print(e) expected device cpu but got device cuda:0
Both errors tell us that binary addition expects the second parameter to have the same device as the first parameter. Understanding the meaning of this error can help debug these types of device mismatches.
Finally, to complete, let's move the second tensor to the cuda device to see if the operation is successful.
> t2 = t2.to('cuda') > t1 + t2 tensor([[ 6, 8], [10, 12]], device='cuda:0')
PyTorch nn. Calculation of module on GPU
We just saw how to move tensors into and out of the device. Now, let's see how to use pytorch NN Module instance to achieve this.
In short, we are interested in understanding what it means for the network to run on devices such as GPU or CPU. PyTorch aside, this is the basic problem.
We place the network on one device by moving the parameters of the network to the device. Let's create a network:
network = Network()
Now let's look at the parameters of the network:
for name, param in network.named_parameters(): print(name, '\t\t', param.shape) conv1.weight torch.Size([6, 1, 5, 5]) conv1.bias torch.Size([6]) conv2.weight torch.Size([12, 6, 5, 5]) conv2.bias torch.Size([12]) fc1.weight torch.Size([120, 192]) fc1.bias torch.Size([120]) fc2.weight torch.Size([60, 120]) fc2.bias torch.Size([60]) out.weight torch.Size([10, 60]) out.bias torch.Size([10])
Here, we create a PyTorch network and traverse the parameters of the network. As we can see, the parameters of the network are the weights and deviations within the network.
In other words, as we have seen, these are just tensors that exist on the device. Let's verify this by checking the device for each parameter.
for n, p in network.named_parameters(): print(p.device, '', n) cpu conv1.weight cpu conv1.bias cpu conv2.weight cpu conv2.bias cpu fc1.weight cpu fc1.bias cpu fc2.weight cpu fc2.bias cpu out.weight cpu out.bias
This indicates that all parameters in the network are initialized on the CPU by default.
An important consideration is that it explains why. Module instances like the network actually have no devices. It is not a network on the device, but a tensor within the network on the device.
Let's see what happens when we ask a network to move to the GPU:
network.to('cuda') Network( (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1)) (conv2): Conv2d(6, 12, kernel_size=(5, 5), stride=(1, 1)) (fc1): Linear(in_features=192, out_features=120, bias=True) (fc2): Linear(in_features=120, out_features=60, bias=True) (out): Linear(in_features=60, out_features=10, bias=True) )
Please note that there is no need to reassign here. This is because for network instances, the operation is performed in situ. However, this operation can be used as a reassignment operation. In order to make NN The module instance is consistent with PyTorch tensors, which is the best way.
We can see that all network parameters now have cuda devices.
for n, p in network.named_parameters(): print(p.device, '', n) cuda:0 conv1.weight cuda:0 conv1.bias cuda:0 conv2.weight cuda:0 conv2.bias cuda:0 fc1.weight cuda:0 fc1.bias cuda:0 fc2.weight cuda:0 fc2.bias cuda:0 out.weight cuda:0 out.bias
Deliver samples to the network
Let's complete this demonstration by passing an example to the network.
sample = torch.ones(1,1,28,28) sample.shape torch.Size([1, 1, 28, 28])
This gives us a sample tensor, which we can pass:
try: network(sample) except Exception as e: print(e) Expected object of device type cuda but got device type cpu for argument #1 'self' in call to _thnn_conv2d_forward
Since our network is on the GPU and the newly created sample is on the CPU by default, we get an error. This error tells us that the CPU tensor is expected to be GPU tensor when calling the forward method of the first volume layer. This is exactly what we saw when we added two tensors directly before.
We can send our samples to GPU like this to solve this problem:
try: pred = network(sample.to('cuda')) print(pred) except Exception as e: print(e) tensor([[-0.0685, 0.0201, 0.1223, 0.1075, 0.0810, 0.0686, -0.0336, -0.1088, -0.0995, 0.0639]] , device='cuda:0' , grad_fn=<AddmmBackward> )
Finally, everything went as expected and we got a prediction.
Write PyTorch code unknown to the device
Before concluding, we need to talk about writing device agnostic code. The term device agnostic means that our code does not depend on the underlying device. You may encounter this term when reading the PyTorch documentation.
For example, suppose we write code that uses the cuda() method everywhere, and then we give the code to a user without a GPU. This will not work. don't worry. We have other options!
Remember the cuda () and cpu () methods we saw earlier?
One of the reasons we prefer the to () method is that the to () method is parameterized, which makes it easier to change the device we choose, that is, it is flexible!
For example, the user can use cpu or cuda as parameters of the deep learning program, which will allow the program to be device independent.
Allowing the user of the program to pass a parameter that determines the behavior of the program may be the best way to make the program device independent. However, we can also use PyTorch to check the supported GPU s and set up our devices.
torch.cuda.is_available() True
If cuda is available, use it!
PyTorch GPU training performance test
Now let's see how to add the use of GPU to the training cycle. We will use the code we have developed so far in this series to do this addition.
This will enable us to easily compare time, CPU VS GPU.
Refactoring RunManager class
Before updating the training cycle, we need to update the RunManager class. In begin_ In the run () method, we need to modify it and pass it to add_ Image tensor device of graph method.
It should be like this:
def begin_run(self, run, network, loader): self.run_start_time = time.time() self.run_params = run self.run_count += 1 self.network = network self.loader = loader self.tb = SummaryWriter(comment=f'-{run}') images, labels = next(iter(self.loader)) grid = torchvision.utils.make_grid(images) self.tb.add_image('images', grid) self.tb.add_graph( self.network ,images.to(getattr(run, 'device', 'cpu')) )
Here, we use the built-in getattr () function to get the value of the device on the running object. If the running object has no device, the cpu is returned. This makes the code backward compatible. If we don't specify a device for our operation, it can still work.
Note that the network does not need to be moved to devices because its devices are set up before incoming. However, the image tensor is obtained from the loader.
Reconstruct training cycle
We will set our configuration parameters to have a device. The two logical options here are cuda and cpu.
params = OrderedDict( lr = [.01] ,batch_size = [1000, 10000, 20000] , num_workers = [0, 1] , device = ['cuda', 'cpu'] )
As these device values are added to our configuration, they will now be accessible in our training cycle.
At the top of our running, we will create a device to deliver in the running and training cycle.
device = torch.device(run.device)
This is the first time we use the device to initialize the network.
network = Network().to(device)
This will ensure that the network is moved to the appropriate device. Finally, we will update the image and label tensor, package them separately and send them to the device as follows:
images = batch[0].to(device) labels = batch[1].to(device)
That's it. We're ready to run this code and see the results.
Here, we can see that cuda devices are significantly two to three times larger than CPUs. The results may vary.
| https://algorithm.zone/blogs/pytorch-on-gpu-training-neural-network-with-cuda-pytorch-series-30.html | CC-MAIN-2022-27 | refinedweb | 2,156 | 67.04 |
Macro at Startup
Introduction
This documentation will explain how to set up a macro to automatically run at FreeCAD startup.
Before starting, following things shall be considered :
- Automatically running macro at startup can be considered a security risk. You should only run macro that you trust and that you previously tested
- You probably need some Python and coding notions to follow this procedure
- When user folders ('Mod', 'Macro', ...) are referred to, they are located in your user FreeCAD folder. You can locate them at Start up and Configuration → User related information
- This shouldn't be done for macros dealing with part modeling. This is rather appropriate for macros that add features, improve the UI, ...
How to
Prepare the macro
Generally, it will happen that a macro isn't directly compatible with a startup launch and shall be fine-tuned
Consider the below macro that you downloaded from somewhere and is stored in your 'Macro' folder with name 'MySuperMacro.FCMacro' :
## Import section ## from PySide import QtGui ## Definition section (classes, functions, ...) class MyMsgBox(QtGui.QMessageBox): def __init__(self): super(MyMsgBox, self).information(None, "MyTitle", "MyText") ##Main instruction section MyMsgBox()
All macros will generally present a similar structure with first import section, then definition section and finally main instruction section. We will focus on this latter because main instructions (they are quite easy to spot because they start at the full beginning of the line) are actually the ones that 'execute' the macro. For later step, we'll need to programmatically import the macro then execute it. This can't be done with the actual structure of the macro. To be able to do so, we need to enclose the main instructions in a function --eg. run()-- then ensure this function is still called when the macro is manually run by the user. If you're not totally sure of what you're doing, it is advised to work on a copy of the macro (or you may just want to keep the original macro as is). The original file shall be modified as follow :
from PySide import QtGui ##The 2 below lines shall be added if not already present to ensure FreeCAD modules are imported import FreeCAD as App import FreeCADGui as Gui class MyMsgBox(QtGui.QMessageBox): def __init__(self): super(MyMsgBox, self).information(None, "MyTitle", "MyText") ##Enclose the main instructions in a function def run(): MyMsgBox() ##Ensure main instructions are still called in case of manal run if __name__ == '__main__': run()
Of course if the function 'run()' already exists in the macro, you can choose any other convenient name Now the macro is ready to be integrated in FreeCAD startup.
Integrate into FreeCAD startup
First create a new folder in your user 'Mod' folder, let's say called 'MacroStartup'. Copy the modified macro into this newly created folder and rename it with a '.py' extension if this isn't yet the case (notice that if you develop the macro by yourself, it can be named with '.py' extension also in the 'Macro' folder so that you don't need to rename when copying). Finally create in the same folder a file called 'InitGui.py' which contains the following code :
def runMacroStartup(name): #Do not run when NoneWorkbench is activated because UI isn't yet completely there if name != "NoneWorkbench": #Run macro only once by disconnecting the signal at first call FreeCADGui.getMainWindow().workbenchActivated.disconnect(runMacroStartup) ##Following 2 lines shall be duplicated for each macro to run import MySuperMacro MySuperMacro.run() ##Eg. if a second macro shall be launched at startup #import MyWonderfulMacro #MyWonderfulMacro.run() ##The following 2 lines are important because InitGui.py files are passed to the exec() function... ##...and the runMacro wouldn't be visible outside. So explicitly add it to __main__ import __main__ __main__.runMacro = runMacro ##Connect the function that runs the macro to the appropriate signal FreeCADGui.getMainWindow().workbenchActivated.connect(runMacro)
Notice that it shall be done only once. If you want to run more than one macro, you can just add the others in the same file (look at the comments on the above code).
We are over. Your macro should automatically run at next FreeCAD launch.
Notice that if the original macro was downloaded through the Addon Manager, it will be overwritten on update and thus you have to follow again the steps here.
Related
- Extra_python_modules#LazyLoader LazyLoader is a python module that allows deferred loading,
> | https://wiki.freecadweb.org/Macro_at_Startup | CC-MAIN-2020-50 | refinedweb | 731 | 53.51 |
Re: "pointers" in /clr
- From: beginthreadex <beginthreadex@xxxxxxxxxxx>
- Date: Wed, 16 Nov 2005 17:09:11 +0000
I really liked what you said Tom. It gives me great pause and I'll have to
think about some of the things you have said. With that, you have a
perspective that I am only starting to understand by reading your article.
Honestly, I have hated the new c++.net because of some many reasons. When
you approach this new language from the perspective of your statements I
must say that it does compell me to finally give c++.net a SERIOUS look.
And as any titilated programmer I will start my personal review today ...
thinking from your perspective. Interesting. Different. Not competing.
Thanks again for your time and all that you have said. I plan on printing
this out and re-reading over your words in detail.
> beginthreadex wrote:
>
>> Persons that have been developing in VC++ for many years might run into
>> the same issues that I do with my teams. If MS knows that the classes are
>> collected then the syntax should not matter. There should be no reason
>> for ^ instead of * or % instead of &. Just stick to what's already
>> trained into people so we don't need to keep rewritting things but use
>> all the tools.
>
> Unfortunately there are substantial differences between the native and
> the managed OOP paradigm. The .NET framework doesn't support global
> variables and functions at all, it only knows methods and properties.
> Although C++/CLI has stack syntax, the framework only supports pointer
> (handle) syntax for ref classes, and value classes are severely limited.
> In the managed world, there's no concept for const (in particular,
> global constants, const member functions), which is IMHO is a very big
> problem, but this is what we have. Heck, even the concept of destructors
> doesn't exist in the managed world, and C++/CLI destructors are not 100%
> compatible with the standard ones. The concept of default argument
> doesn't exist either. Should I go on? Virtual functions must be
> explicitly declared "override" if they override an existing one. There
> is no operator overloading either.
>
> On the other hand, native C++ doesn't have the concept of properties,
> delegates, events, and most importantly, the concept of public and
> private classes. Every class that's #include'ed is public, what's not in
> the headers is private.
>
> Even though it sounds nice in theory to be able to share the same code
> base between the native and the managed worlds, it's almost never
> technically possible. You can't write anything more than trivial that
> you could share between native C++ and managed C++. I agree that the old
> MC++ syntax looked like you could share trivial code between the two,
> but I don't think it was practical in real-world applications or
> libraries. You would have to be very careful to use only that narrow
> common feature set that both worlds have, and even then you have to deal
> with the class visibility issue. "public class" doesn't compile under
> std C++, but a simple "class" means private in old MC++, which is not
> what you want. The old MC++ syntax may give you a false sense of
> security that you can theoretically write code for both worlds, when in
> practice it almost never happens.
>
> I question myself if it would have made sense to create C++/CLI so that
> you could share code between the two world. When you could really write
> it once and compile standard native C++ code into pure managed
> assemblies. Such as disregarding the const keyword in managed mode.
> Setting up the default class visibility using a #pragma class public, or
> something similar. Automatically inserting the "override" keyword for
> virtual methods that override existing ones. Keeping the * and & symbols
> for managed handles and references. Automatically substituting static
> const members with read-only properties. Automatically substituting
> default arguments with function overriding for .NET. Automatically
> substitute getter and setter functions with properties. And so on and so
> forth. But C++ is a low-level language, and these hidden translations in
> the background would certainly mean losing control. You still wouldn't
> be able to do everything, you'd still need to #ifdef a whole bunch of
> lines. You still wouldn't be able to use events in native C++ the exact
> same way as delegates work in .NET, even though similar concepts
> (boost::function) now exist in standard C++. It's impossible to
> translate every unmanaged C++ code to .NET anyway.
>
> Quite frankly, I don't think this was their goal with C++/CLI. They
> wanted a language where you
>
> 1) have low-level, but full support for almost every .NET framework
> feature, with a language as similar to C++ as possible
>
> 2) can freely intermix managed and unmanaged code, and for that it was a
> very good idea to introduce the ^ and % symbols. It's way less confusing
> than __gc * and __nogc *. I love that T ^ is managed and U * is
> unmanaged, and I can tell that in an instant.
>
> But I'm hearing you, sometimes it would be very nice to compile native
> C++ code into pure managed, without having to rewriting a single line,
> even if there are severe restrictions with that. Maybe someone will
> write a standard C++ to C++/CLI code converter. After all, Borland
> created a mechanism for automatically generating a C++ header file from
> a Pascal input, and with few limitations it works perfectly (only Pascal
> is trivial to parse, C++ is far from it). I can imagine an automated
> native to managed converter would work with restrictions, so we could
> write once and reuse the code twice. I could imagine converting
> boost::shared_ptr<T> to T^, and boost::function to delegates, and so on.
> The question is how much market it has, because it's quite some work to
> write such a compiler.
>
> In practice, when you program for .NET you use framework types and
> functions, such as Drawing::Color, Rectangle, String, and .NET
> collections. How far are you willing to go with the automatic type
> substitution? I don't think it's feasable to really write your code once
> and reuse it for native C++ and .NET at the same time. You're pretty
> much forced to rewrite it, or to wrap unmanaged code into managed classes.
>
> Tom
.
- Follow-Ups:
- Re: "pointers" in /clr
- From: Tamas Demjen
- References:
- "pointers" in /clr
- From: Peter Oliphant
- Re: "pointers" in /clr
- From: Nishant Sivakumar
- Re: "pointers" in /clr
- From: beginthreadex
- Re: "pointers" in /clr
- From: William DePalo [MVP VC++ ]
- Re: "pointers" in /clr
- From: beginthreadex
- Re: "pointers" in /clr
- From: Tamas Demjen
- Prev by Date: a subtle change in behavior...
- Next by Date: Re: HELP dogs & cats in China please! [MUST SEE]
- Previous by thread: Re: "pointers" in /clr
- Next by thread: Re: "pointers" in /clr
- Index(es): | http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.vc/2005-11/msg00345.html | crawl-002 | refinedweb | 1,152 | 63.19 |
The Portal Zone is closed for business
Today is my last day in Sun Portal.
This blog will no longer be active, but I would continue to blog on my old java.net blog. You can catch me here: Navaneeth Krishnan's Blog
[update] Check out the new and improved Portal Zone.
Posted at 02:45AM Mar 02, 2007 by Navaneeth Krishnan in General | Comments[3]
Youtube Portlet - Adding videos to your portal
Not too long ago, we added a Video Portlet to the Portlet Repository project. This portlet application utilizes the REST API exposed by Youtube for it's functionality. You can find out more about the portlet on our brand new wiki site: Video Portlet documentation.
And here is a quick screenshot:
The user interface is a little primitive and I would like to blame it on my lack of UI skills ;-). I am still working on it (if you are interested in helping out, please leave a comment or send me an email). I am also trying to figure out what other functionality is worth adding
Posted at 12:53AM Feb 16, 2007 by Navaneeth Krishnan in Portlet |
Understanding Portlet 2.0 (JSR 286) - Part 2
In my previous blog entry (Part 1), I mentioned that one of the key limitations of the Portlet 1.0 spec was that it did not provide a mechanism for one portlet to "notify" another portlet that it's state has changed. Thankfully, Portlet 2.0 provides (not one but two!) mechanisms by which portlets can communicate with each other.
For the sake of illustration consider a portal page with two portlets : A user profile portlet (Profile portlet) which stores the personal details of the logged in user and a Weather portlet which shows the weekly weather forecast for a particular location. Our usecase is that when the user updates her profile address to a new location, the Weather portlet needs to show the weather forecast for that particular location.
In Portlet 1.0, developers are left with no choice but to use a shared memory space. When the first portlet is being acted upon , in this case the Profile Portlet is clicked, it stores the data that needs to be communicated into a shared memory space. When the portlet that needs to receive this data is being rendered, it is programmed to read the data from the same shared memory. Here is a quick illustration.
In processAction() of ProfilePortlet, data is written to shared memory:
During render() of WeatherPortlet, data is read from the shared memory:
So, what is this shared memory space ? Well, if you bundle these two portlet into a single portlet application (i.e a single war file sharing the same portlet.xml) there are two easy choices: The PortletSession and the PortletContext.
Here, the notion of sessions and context is very similar to (you could even say copied from :) the Servlet world. A PortletSession exists per user per portlet application (like HttpSession exists per user per web application) and a PortletContext is shared between all users and all portlets for a given portlet application (ServletContext is shared between all users and servlets in a web application). However, Portlets additionally possess a mechanism to conveniently namespace an attribute that is placed in the session. This mechanism is called "scoping". The scoping mechanism helps a portlet to easily differentiate between data that is used exclusively by itself (referred to as Portlet-scoped data) and data that is shared between it and other portlets in the application (referred to a Application-scoped data).
While both the PortletSession and PortletContext can be used to solve the interportlet communication problem, this scenario occurs most frequently in the context of a user accessing a portal. Hence it is typical to use the PortletSession.( And though PortletContext can be used when you want the data to be propagated to *all* users – there might be a better way of handling such a case).
The source code would look like this:
In processAction of ProfilePortlet :
portletSession.setAttribute("location", newLocation, PortletSession.APPLICATION_SCOPE);
In render of WeatherPortlet:
currentLocation = (String) portletSession.getAttribute("location",PortletSession.APPLICATION_SCOPE);
showWeatherForThisLocation(currentLocation);
There are a bunch of problems with this approach. Firstly, using the PortletSession (or PortletContext) is only possible when the portlets are packaged as a part of the same portlet application. For portlets that are part of different portlet applications, this won't work -since the sessions and contexts are different. Hence, in such cases, you need to resort to other standard communication mechanisms JMS (messaging), JNDI etc. And such solutions are far from tirvial and sometime becomes an overkill for the problem we are trying to address.
Secondly, the Weather Portlet is limited by the semantics of the portlet programming model, on how it can respond to the communicated data. This is because portlets are not allowed to change their states during a render()(as rendering is defined as idempotent). And the Weather Portlet is only rendered and never acted upon. Hence it will not be able to change it's window state, mode or preferences during the above interaction. This is seriously limiting.
Thirdly, there is no way for the Weather portlet to communicate back to the Profile portlet (or any other portlet), if at all it wants to. The above communication is one-time and unidirectional.
Finally, from a design perspective, this is probably not what a session (or context ) is meant to be used for. And this could lead to bad code. (As developers might develop the tendency to put all transient data into the HttpSession just because it is easier to share it between multiple portlets)
Portlet 2.0 introduces a full-fledged interportlet communication mechanism called Eventing. Eventing can be described as a loosely coupled, brokered means of communication between portlets. It is loosely coupled because portlets that send events need not have any compile-time or runtime dependency on the portlets that receive that event (or vice versa). It is brokered because the portal/portlet container acts as a conduit for these events.
The simplest way to understand eventing is to consider the portlet-container as an "event bus". Portlets that need to send notifications to other portlets publish events. Portlets that are interested in receiving notifications from others subscribe to events.
To illustrate eventing, let's take the same example as above and see how we would implement a Portlet 2.0 solution. First step, the user clicks on the Profile portlet and changes her location.This triggers a processAction() on the Profile portlet and the`portlet updates it's state.At the end of this processAction() phase, the portlet does something different. Instead of writing to a`shared memory, like the previous example, it requests the portlet-container to send a "location changed" event.
The next phase is called the eventing phase. This is when the portlet-container determines which other portlets needs to receive this event and routes it appropriately. In this case, we assume that the Weather portlet was configured to consume this event, hence the event sent to the Weather Portlet.
The next is the render phase. Notice that in this case, the portlet doesn't need to do anything special. It just needs to render itself, according to it's current state.
In the above illustration, it is pretty easy to notice that Portlet 2.0 has solved the problem by introducing a separate new lifecycle phase - the eventing phase. So our original lifecycle diagram can be modified to this now:
Eventing always occurs after processAction(). It also always occurs before the render(). And eventing can modify state (i.e it is a non-idempotent operation). This solves most of the shortcomings we noticed in the Portlet 1.0 implementation.
Since eventing does not rely on any shared memory space, even portlets from different portlet applications can communicate with each other. Also, since eventing is defined as a state-modifying operation, the portlet is free to make an any persistent change to it's state including changing it's mode or window state, storing user preferences or modifying a database backend. Changes to it's UI will be reflected in the rendering phase that follows.
Another interesting aspect is that the Weather Portlet is free to respond to the "location changed" event by sending it's own new event. And if the Profile portlet is configured to receive it, it will. In other words, a first generation event can trigger a second generation event can trigger a third generation event... and so on.
Posted at 04:21PM Feb 14, 2007 by Navaneeth Krishnan in Portlet | Comments[5]
Understanding]
Portlet and WSRP resources
Here is a dump of my bookmarks on Portlets and WSRP. I hope to keep this blog entry updated periodically
Posted at 12:08PM Jan 30, 2007 by Navaneeth Krishnan in Portlet |
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 2.5 License. | http://blogs.sun.com/nav/ | crawl-002 | refinedweb | 1,490 | 54.42 |
Hi gradlebrains!
I’m working on migrating our entire build environment to Gradle; build, test, deploy, backup, restore, the whole shebang. I’m having trouble with restore of a MySQL dump.
I made the backup work like this:
task backupdb(dependsOn: 'setupBackup') << { exec { commandLine mysqldump, 'db_name', '--host=localhost', '--user=user', '--password=pwd', '--single-transaction', '--quick', "--result-file=db_dump.sql" } }
Unfortunately, I find myself unable to get restore of a dump working I Gradle.
Command line restore is a no brainer:
mysql --user=user --password=pwd --quick db_name < db_dump.sql
Unfortunately the “<” does not seem to work in Gradle (Groovy) - I had the same problem with the dump, but there I can use “result-file=…” - so I cannot get it to work in a build script.
I’ve tried several ways unsuccessful: 1)
exec { commandLine mysql, '-uuser', '-ppwd', '-q', '-Ddb_name', db_dump.sql }
def proc = ["mysql", "-uuser", "-ppwd", "-Ddb_name"].execute() proc.withWriter { writer -> writer << “db_dump.sql” } proc.waitFor()
3…10) Several other ways (mostly permutations of above)…
Please, oh wise collective, help me.
Regards, Brian.
Environment: Gradle 1.0 Gradle build time: 12. juni 2012 00:56:21 UTC Groovy: 1.8.6 Ant: Apache Ant™ version 1.8.2 compiled on December 20 2010 Ivy: 2.2.0 JVM: 1.6.0_25 (Sun Microsystems Inc. 20.0-b11) OS: Windows 7 6.1 x86 | https://discuss.gradle.org/t/restore-mysql-database-dump/4509 | CC-MAIN-2018-51 | refinedweb | 223 | 52.46 |
Question :
I’d simply like to convert a base-2 binary number string into an int, something like this:
'11111111'.fromBinaryToInt() 255
Is there a way to do this in Python?
Answer #1:
You use the built-in
int function, and pass it the base of the input number, i.e.
2 for a binary number:
int('11111111', 2) 255
Here is documentation for python2, and for python3.
Answer #2:
Just type 0b11111111 in python interactive interface:
0b11111111 255
Answer #3:
Another way to do this is by using the
bitstring module:
from bitstring import BitArray b = BitArray(bin='11111111') b.uint 255
Note that the unsigned integer is different from the signed integer:
int -1b.
The
bitstring module isn’t a requirement, but it has lots of performant methods for turning input into and from bits into other forms, as well as manipulating them.
Answer #4:
Using int with base is the right way to go. I used to do this before I found int takes base also. It is basically a reduce applied on a list comprehension of the primitive way of converting binary to decimal ( e.g. 110 = 2**0 * 0 + 2 ** 1 * 1 + 2 ** 2 * 1)
add = lambda x,y : x + y reduce(add, [int(x) * 2 ** y for x, y in zip(list(binstr), range(len(binstr) - 1, -1, -1))])
Answer #5:
If you wanna know what is happening behind the scene, then here you go.
class Binary(): def __init__(self, binNumber): self._binNumber = binNumber self._binNumber = self._binNumber[::-1] self._binNumber = list(self._binNumber) self._x = [1] self._count = 1 self._change = 2 self._amount = 0 print(self._ToNumber(self._binNumber)) def _ToNumber(self, number): self._number = number for i in range (1, len (self._number)): self._total = self._count * self._change self._count = self._total self._x.append(self._count) self._deep = zip(self._number, self._x) for self._k, self._v in self._deep: if self._k == '1': self._amount += self._v return self._amount mo = Binary('101111110')
Answer #6:
A recursive Python implementation:
def int2bin(n): return int2bin(n >> 1) + [n & 1] if n > 1 else [1]
Answer #7:
If you are using python3.6 or later you can use f-string to do the
conversion:
Binary to decimal:
f'{0b1011010:#0}') 90 bin_2_decimal = int(f'{0b1011010:#0}') bin_2_decimal 90print(
binary to octal hexa and etc.
f'{0b1011010:#o}' '0o132' # octal f'{0b1011010:#x}' '0x5a' # hexadecimal f'{0b1011010:#0}' '90' # decimal
Pay attention to 2 piece of information separated by colon.
In this way, you can convert between {binary, octal, hexadecimal, decimal} to {binary, octal, hexadecimal, decimal} by changing right side of colon[:]
:#b -> converts to binary :#o -> converts to octal :#x -> converts to hexadecimal :#0 -> converts to decimal as above example
Try changing left side of colon to have octal/hexadecimal/decimal.
Answer #8:
For large matrix (10**5 rows and up) it is better to use a vectorized matmult. Pass in all rows and cols in one shot. It is extremely fast. There is no looping in python here. I originally designed it for converting many binary columns like 0/1 for like 10 different genre columns in MovieLens into a single integer for each example row.
def BitsToIntAFast(bits): m,n = bits.shape a = 2**np.arange(n)[::-1] # -1 reverses array of powers of 2 of same length as bits return bits @ a | https://discuss.dizzycoding.com/convert-base-2-binary-number-string-to-int/ | CC-MAIN-2022-33 | refinedweb | 566 | 57.87 |
by blockstack
GitHub Readme.md
This document describes the high-level design and implementation of the Gaia storage system. It includes specifications for backend storage drivers and interactions between developer APIs and the Gaia service.
Developers who wish to use the Gaia storage system should see the
blockstack.js APIs
documented here and here.
If you would like to deploy your own hub, there are instructions available here
Instructions on setting up and configuring a Gaia Hub can be found in this readme.
Gaia works by hosting data in one or more existing storage systems of the user's choice. These storage systems are typically cloud storage systems. We currently have driver support for S3 and Azure Blob Storage, but the driver model allows for other backend support as well. The point is, the user gets to choose where their data lives, and Gaia enables applications to access it via a uniform API..
Gaia's approach to decentralization focuses on user-control of data and storage. If a user can choose which gaia hub and which backend provider to store data with, then that is all the decentralization required to enable user-controlled applications.
In Gaia, the control of user data lies in the way that user data is accessed. When an application
fetches a file
data.txt for a given user
alice.id, the lookup will follow these steps:
alice.id, and read her profile URL from that zonefile
alice.id's key) out of the profile
Because
alice.id controls her zonefile, she can change where her profile is stored,
if the current storage of the profile is compromised. Similarly, if Alice wishes to change
her gaia provider, or run her own gaia node, she can change the entry in her profile.
For applications writing directly on behalf of Alice, they do not need to perform this lookup. Instead, the blockstack authentication flow provides Alice's chosen application root URL to the application. This authentication flow is also within Alice's control, because the authentication response must be generated by Alice's browser.
While it is true that many Gaia hubs will use backend providers like AWS or Azure, allowing users to easily operate their own hubs, which may select different backend providers (and we'd like to implement more backend drivers), enables truly user-controlled data, while enabling high performance and high availability for data reads and writes.
A performance and simplicity oriented guarantee of the Gaia
specification is that when an application submits a write to a URL, the application is guaranteed to
be able to read from a URL. While the
prefix of the read-from URL may change between the two, the suffix
must be the same as the write-to URL.
This allows an application to know exactly where a written file can be read from, given the read prefix. To obtain that read prefix, the Gaia service defines an endpoint:
GET /hub_info/
which returns a JSON object with a
read_url_prefix.
For example, if my service returns:
{ ..., "read_url_prefix": "" }
I know that if I submit a write request to:
That I will be able to read that file from:
Access control in a gaia storage hub is performed on a per-address
basis. Writes to URLs
/store/<address>/<file> are only allowed if
the writer can demonstrate that they control that address. This is
achieved via an authentication token, which is a message signed by
the private-key associated with that address. The message itself is a
challenge-text, returned via the
/hub_info/ endpoint.
The V1 authentication scheme uses a JWT, prefixed with
v1: as a
bearer token in the HTTP authorization field. The expected JWT payload
structure is:
{ 'type': 'object', 'properties': { 'iss': { 'type': 'string' }, 'exp': { 'type': 'IntDate' }, 'iat': { 'type': 'IntDate' }, 'gaiaChallenge': { 'type': 'string' }, 'associationToken': { 'type': 'string' }, 'salt': { 'type': 'string' } } 'required': [ 'iss', 'gaiaChallenge' ] }
In addition to
iss,
exp, and
gaiaChallenge claims, clients may
add other properties (e.g., a
salt field) to the payload, and they will
not affect the validity of the JWT. Rather, the validity of the JWT is checked
by ensuring:
iss
issmatches the address associated with the bucket.
gaiaChallengeis equal to the server's challenge text.
expis greater than the server's current epoch time.
iat(issued-at date) is greater than the bucket's revocation date (only if such a date has been set by the bucket owner).
The association token specification is considered private, as it is mostly used for internal Gaia use cases. This means that this specification can change or become deprecated in the future.
Often times, a single user will use many different keys to store data. These keys may be generated on-the-fly. Instead of requiring the user to explicitly whitelist each key, the v1 authentication scheme allows the user to bind a key to an already-whitelisted key via an association token.
An association token is a JWT signed by a whitelisted key that, in turn,
contains the public key that signs the authentication JWT that contains it. Put
another way, the Gaia hub will accept a v1 authentication JWT if it contains an
associationToken JWT that (1) was sigend by a whitelisted address, and (2)
identifies the signer of the authentication JWT.
The association token JWT has the following structure in its payload:
{ 'type': 'object', 'properties': { 'iss': { 'type': 'string' }, 'exp': { 'type': 'IntDate' }, 'iat': { 'type': 'IntDate' }, 'childToAssociate': { 'type': 'string' }, 'salt': { 'type': 'string' }, }, 'required': [ 'iss', 'exp', 'childToAssociate' ] }
Here, the
iss field should be the public key of a whitelisted address.
The
childtoAssociate should be equal to the
iss field of the authentication
JWT. Note that the
exp field is required in association tokens.
In more detail, this signed message is:
BASE64({ "signature" : ECDSA_SIGN(SHA256(challenge-text)), "publickey" : PUBLICKEY_HEX })
Currently, challenge-text must match the known challenge-text on the gaia storage hub. However, as future work enables more extensible forms of authentication, we could extend this to allow the auth token to include the challenge-text as well, which the gaia storage hub would then need to also validate..
A configuration JSON file should be stored either in the top-level directory
of the hub server, or a file location may be specified in the environment
variable
CONFIG_PATH.
An example configuration file is provided in (./hub/config.sample.json) You can specify the logging level, the number of social proofs required for addresses to write to the system, the backend driver, the credentials for that backend driver, and the readURL for the storage provider.
A private hub services requests for a single user. This is controlled via whitelisting the addresses allowed to write files. In order to support application storage, because each application uses a different app- and user-specific address, each application you wish to use must be added to the whitelist separately.
Alternatively, the user's client must use the v1.
An open-membership hub will allow writes for any address top-level directory, each request will still be validated such that write requests must provide valid authentication tokens for that address. Operating in this mode is recommended for service and identity providers who wish to support many different users.
In order to limit the users that may interact with such a hub to users who provide social proofs of identity, we support an execution mode where the hub checks that a user's profile.json object contains social proofs in order to be able to write to other locations. This can be configured via the config.json.
Gaia hub drivers are fairly simple. The biggest requirement is the ability to fulfill the write-to/read-from URL guarantee.
A driver can expect that two modification operations to the same path will be mutually exclusive. No writes, renames, or deletes to the same path will be concurrent.
As currently implemented a gaia hub driver must implement the following functions:
interface DriverModel { /** * Return the prefix for reading files from. * a write to the path `foo` should be readable from * `${getReadURLPrefix()}foo` * @returns the read url prefix. */ getReadURLPrefix(): string; /** * Performs the actual write of a file to `path` * the file must be readable at `${getReadURLPrefix()}/${storageToplevel}/${path}` * * @param options.path - path of the file. * @param options.storageToplevel - the top level directory to store the file in * @param options.contentType - the HTTP content-type of the file * @param options.stream - the data to be stored at `path` * @param options.contentLength - the bytes of content in the stream * @param options.ifMatch - optional etag value to be used for optimistic concurrency control * @param options.ifNoneMatch - used with the `*` value to save a file not known to exist, * guaranteeing that another upload didn't happen before, losing the data of the previous * @returns Promise that resolves to an object containing a public-readable URL of the stored content and the objects etag value */ performWrite(options: { path: string; storageTopLevel: string; stream: Readable; contentLength: number; contentType: string; ifMatch?: string; ifNoneMatch?: string; }): Promise<{ publicURL: string, etag: string }>; /** * Deletes a file. Throws a `DoesNotExist` if the file does not exist. * @param options.path - path of the file * @param options.storageTopLevel - the top level directory * @param options.contentType - the HTTP content-type of the file */ performDelete(options: { path: string; storageTopLevel: string; }): Promise<void>; /** * Renames a file given a path. Some implementations do not support * a first class move operation and this can be implemented as a copy and delete. * @param options.path - path of the original file * @param options.storageTopLevel - the top level directory for the original file * @param options.newPath - new path for the file */ performRename(options: { path: string; storageTopLevel: string; newPath: string; }): Promise<void>; /** * Retrieves metadata for a given file. * @param options.path - path of the file * @param options.storageTopLevel - the top level directory */ performStat(options: { path: string; storageTopLevel: string; }): Promise<{ exists: boolean; lastModifiedDate: number; contentLength: number; contentType: string; etag: string; }>; /** * Returns an object with a NodeJS stream.Readable for the file content * and metadata about the file. * @param options.path - path of the file * @param options.storageTopLevel - the top level directory */ performRead(options: { path: string; storageTopLevel: string; }): Promise<{ data: Readable; lastModifiedDate: number; contentLength: number; contentType: string; etag: string; }>; /** * Return a list of files beginning with the given prefix, * as well as a driver-specific page identifier for requesting * the next page of entries. The return structure should * take the form { "entries": [string], "page"?: string } * @returns {Promise} the list of files and a possible page identifier. */ listFiles(options: { pathPrefix: string; page?: string; }): Promise<{ entries: string[]; page?: string; }>; /** * Return a list of files beginning with the given prefix, * as well as file metadata, and a driver-specific page identifier * for requesting the next page of entries. */ listFilesStat(options: { pathPrefix: string; page?: string; }): Promise<{ entries: { name: string; lastModifiedDate: number; contentLength: number; etag: string; }[]; page?: string; }>; }
The Gaia storage API defines the following endpoints:
GET ${read-url-prefix}/${address}/${path}
This returns the data stored by the gaia hub at
${path}.
The response headers include
Content-Type and
ETag, along with
the required CORS headers
Access-Control-Allow-Origin and
Access-Control-Allow-Methods.
HEAD ${read-url-prefix}/${address}/${path}
Returns the same headers as the corresponding
GET request.
HEAD requests
do not return a response body.
POST ${hubUrl}/store/${address}/${path}
This performs a write to the gaia hub at
${path}.
On success, it returns a
202 status, and a JSON object:
{ "publicURL": "${read-url-prefix}/${address}/${path}", "etag": "version-identifier" }
The
POST must contain an authentication header with a bearer token.
The bearer token's content and generation is described in
the access control section of this
document.
Additionally, file ETags and conditional request headers are used as a
concurrency control mechanism. All requests to this endpoint should contain
either an
If-Match header or an
If-None-Match header. The three request
types are as follows:
Update existing file: this request must specify an
If-Match header
containing the most up to date ETag. If the file has been updated elsewhere
and the ETag supplied in the
If-Match header doesn't match that of the file
in gaia, a
412 Precondition Failed error will be returned.
Create a new file: this request must specify the
If-None-Match: *
header. If the already exists at the given path, a
412 Precondition Failed
error will be returned.
Overwrite a file: this request must specify the
If-Match: * header.
Note that this bypasses concurrency control and should be used with
caution. Improper use can cause bugs such as unintended data loss.
The file ETag is returned in the response body of the store
POST request, the
response headers of
GET and
HEAD requests, and in the returned entries in
list-files request.
Additionally, a request to a file path that already has a previous ongoing
request still processing for the same file path will return with a
409 Conflict error. This can be handled with a retry.
DELETE ${hubUrl}/delete/${address}/${path}
This performs a deletion of a file in the gaia hub at
${path}.
On success, it returns a
202 status. Returns a
404 if the path does
not exist. Returns
400 if the path is invalid.
The
DELETE must contain an authentication header with a bearer token.
The bearer token's content and generation is described in
the access control section of this
document.
GET ${hubUrl}/hub_info/
Returns a JSON object:
{ "challenge_text": "text-which-must-be-signed-to-validate-requests", "read_url_prefix": "${read-url-prefix}" "latest_auth_version": "v1" }
The latest auth version allows the client to figure out which auth versions the gaia hub supports.
POST ${hubUrl}/revoke-all/${address}
The post body must be a JSON object with the following field:
{ "oldestValidTimestamp": "${timestamp}" }
Where the
timestamp is an epoch time in seconds. The timestamp is written
to a bucket-specific file (
/${address}-auth). This becomes the oldest valid
iat timestamp for authentication tokens that write to the
/${address}/ bucket.
On success, it returns a
202 status, and a JSON object:
{ "status": "success" }
The
POST must contain an authentication header with a bearer token.
The bearer token's content and generation is described in
the access control section of this
document.
POST ${hubUrl}/list-files/${address}
The post body can contain a
page field with the pagination identifier from a previous request:
{ "page": "${lastListFilesResult.page}" }
If the post body contains a
stat: true field then the returned JSON includes file metadata:
{ "entries": [ { "name": "string", "lastModifiedDate": "number", "contentLength": "number", "etag": "string" }, { "name": "string", "lastModifiedDate": "number", "contentLength": "number", "etag": "string" }, // ... ], "page": "string" // possible pagination marker }
If the post body does not contain a
stat: true field then the returned JSON entries will only be
file name strings:
{ "entries": [ "fileNameExample1", "fileNameExample2", // ... ], "page": "string" // possible pagination marker }
The
POST must contain an authentication header with a bearer token.
The bearer token's content and generation is described in
the access control section of this
document.
The gaia specification requires that a gaia hub return a URL that a user's client will be able to fetch. In practice, most gaia hubs will use URLs with DNS entries for hostnames (though URLs with IP addresses would work as well). However, even though the spec uses URLs, that doesn't necessarily make an opinionated claim on underlying mechanisms for that URL. If a browser supported new URL schemes which enabled lookups without traditional DNS (for example, with the Blockstack Name System instead), then gaia hubs could return URLs implementing that scheme. As the Blockstack ecosystem develops and supports these kinds of features, we expect users would deploy gaia hubs that would take advantage.
Some service providers may wish to provide hub services to a limited set of different users, with a provider-specific method of authenticating that a user or address is within that set. In order to provide that functionality, our hub implementation would need to be extensible enough to allow plugging in different authentication models.
.storageNamespace
Gaia nodes can request data from other Gaia nodes, and can store data to other Gaia nodes. In effect, Gaia nodes can be "chained together" in arbitrarily complex ways. This creates an opportunity to create a decentralized storage marketplace.
For example, Alice can make her Gaia node public and program it to store data to her Amazon S3 bucket and her Dropbox account. Bob can then POST data to Alice's node, causing her node to replicate data to both providers. Later, Charlie can read Bob's data from Alice's node, causing Alice's node to fetch and serve back the data from her cloud storage. Neither Bob nor Charlie have to set up accounts on Amazon S3 and Dropbox this way, since Alice's node serves as an intermediary between them and the storage providers.
Since Alice is on the read/write path between Bob and Charlie and cloud storage, she has the opportunity to make optimizations. First, she can program her Gaia node to synchronously write data to local disk and asynchronously back it up to S3 and Dropbox. This would speed up Bob's writes, but at the cost of durability (i.e. Alice's node could crash before replicating to the cloud).
In addition, Alice can program her Gaia node to service all reads from disk. This would speed up Charlie's reads, since he'll get the latest data without having to hit back-end cloud storage providers.
Since Alice is providing a service to Bob and Charlie, she will want compensation. This can be achieved by having both of them send her money via the underlying blockchain.
To do so, she would register her node's IP address in a
.storage namespace in Blockstack, and post her rates per gigabyte in her node's
profile and her payment address. Once Bob and Charlie sent her payment, her
node would begin accepting reads and writes from them up to the capacity
purchased. They would continue sending payments as long as Alice provides them
with service.
Other experienced Gaia node operators would register their nodes in
.storage, and
compete for users by offerring better durability, availability, performance,
extra storage features, and so on.
Our deployed service places some modest limitations on file uploads and rate limits. Currently, the service will only allow up to 20 write requests per second and a maximum file size of 5MB. However, these limitations are only for our service, if you deploy your own Gaia hub, these limitations are not necessary.
Here's how Gaia stacks up against other decentralized storage systems. Features that are common to all storage systems are omitted for brevity.Features Gaia Sia Storj IPFS DAT SSB User controls where data is hosted X Data can be viewed in a normal Web browser X X Data is read/write X X X Data can be deleted X X X Data can be listed X X X X X Deleted data space is reclaimed X X X X Data lookups have predictable performance X X Writes permission can be delegated X Listing permission can be delegated X Supports multiple backends natively X X Data is globally addressable X X X X X Needs a cryptocurrency to work X X Data is content-addressed X X X X X | https://elements.heroku.com/buttons/blockstack/gaia | CC-MAIN-2021-04 | refinedweb | 3,181 | 53.41 |
Friday 26 May 2017
Martin Duhem, Guillaume Massé and Denys Shabalin
It has been a little bit more than two months since Scala Native 0.1 has been released. What’s new in Scala Native? What should you expect for future releases?
Scala Native 0.2
In April, Scala Native 0.2 was released. The main focus of this release was to increase the coverage of classes from the JDK, such that more programs can be ported to Scala Native without any further effort. What parts of Java do we now support in Scala Native? Lots! We’ve added support for IO and regular expressions, among others:
Improvements to the standard library
Support for file I/O APIs from
java.iowas added by @Duhemm from the Scala Center with help from @cedricviaccoz and @Korf74 in #574. Scala Native now supports enough to read and write files. Doing I/O with Scala Native feels just the same as in normal Scala or Java:
import java.io.{DataInputStream, File, FileInputStream} val fis = new FileInputStream(new File("hello.txt")) val dis = new DataInputStream(fis) println(dis.readLine())
In #588, @MasseGuillaume from the Scala Center added support for regular expressions. This implementation relies on Google’s RE2 engine and uses a syntax slightly different from the JDK. Using regular expressions with Scala Native works similarly as it does on the JVM:
import java.util.regex._ val m = Pattern.compile("a+(b+)(a+)").matcher("aaabbba") assert(m.find()) println(m.group(1)) // prints "bbb" println(m.group(2)) // prints "a"
@densh added initial support for Scala’s
Futures in #618, using an implementation similar to that of Scala.js, where
Futures will be completed after the
mainmethod is executed. Here’s an example using Scala’s
Futures with Scala Native. Of course, the same code works as well on the JVM:
import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global object Test { def main(args: Array[String]): Unit = { println("Start") Future { println("Hello from the Future") }.foreach(_ => ()) println("End") } }
Scala Native now supports pointer subtraction. This work has been contributed by @jonas in #624. Pointer subtraction is useful, for instance, to determine how many elements there are between two elements of the same array:
val carr: Ptr[CChar] = toCString("abcdefg") val cptr: Ptr[CChar] = string.strchr(carr, 'd') println(cptr - carr) // prints '3'
- @ekrich extended Scala Native’s implementation of
Stringto support
toUpperCaseand
toLowerCasein #573.
- The implementation of
java.lang.Characterwas extended to support
Character.Subsetand
Character.UnicodeBlockby @densh in #651.
@asoltysik implemented support for system properties in #591.
println(System.getProperty("java.version")) // prints '1.8' println(System.getProperty("file.separator")) // '\' on Windows, // '/' elsewhere
- Scala Native can now read environment variables using
System.getEnv, thanks to @jonas’ efforts in #606.
stdinand
stdoutcan reliably be read from and written to, thanks to @fduraffourg and @densh in #622 and #659.
Bugfixes
- A bugfix has been contributed by @jonas to
String.replace, fixing one broken benchmark at the same time. His work can be found in #616.
System.nanoTimewas fixed by Brad Rathke in #549.
- @xuwei-k fixed
nativeAvailableDependencieswhich didn’t work in the
testconfiguration in #565.
Improvements to the tooling and integration
- @MasseGuillaume and @densh worked on refactoring Scala Native’s sbt plugin to make it more idiomatic in #568 and #630.
- Follow up fixes were contributed by @jonas in #639 and #653. They improve how sbt determines the target architecture to compile to.
Preparing for a better garbage collector
In this release, @LukasKellenberger introduced in #539 a new setting in the sbt plugin that lets users select what implementation of the garbage collector should be used. Currently, it lets you select Boehm GC, or disable the garbage collector altogether.
This work was done in preparation for the improved GC that will be shipped with Scala Native 0.3!
A community effort
As shown, many of the improvements that were brought by Scala Native 0.2 have been contributed by members of the vibrant community that is developing itself around Scala Native. In total, to get to Scala Native 0.2, there have been 61 commits merged, 11,344 lines added and 1,954 lines deleted by 17 people: Denys Shabalin, Jonas Fonseca, Guillaume Massé, Martin Duhem, Lukas Kellenberger, Andrzej Sołtysik, Eric K Richardson, Remi Coudert, Florian Duraffour, Brad Rathke, Richard Whaling, Ruben Berenguel M, Sam Halliday, Shunsuke Otani, Cedric Viaccoz, Kenji Yoshida, Ignat Loskutov.
The combination of these improvements was enough to get a prototype of
scalafmt running on Scala Native by @olafurpg, showing a blazing
fast startup time!
@adriaanm @den_sh @scala_native OMG IT WORKS :D 30x faster! pic.twitter.com/M7V9udU5bT— Ólafur Páll Geirsson (@olafurpg) April 27, 2017
What to expect for Scala Native 0.3?
The plans for the next release of Scala Native include a new garbage collector, a better integration with sbt and more additions to the standard library.
Improved garbage collector
The first releases of Scala Native use Boehm GC. A new and improved garbage collector has been under development by @LukasKellenberger and will be presented at Scala Days during Denys’ talk. Stay tuned for more more details to come soon!
The pull request introducing the new garbage collector can be found in #726.
Running tests from sbt
Currently, testing frameworks such as utest or scalacheck cannot be used with Scala Native. An effort to enable support for sbt-compatible testing frameworks has been undertaken by @Duhemm from the Scala Center and is expected to land in Scala Native’s third release.
Support for
java.nio,
java.util.{jar, zip}
The existing I/O capabilities of Scala Native have been extended in this
release by adding support for the classes defined in the packages
java.nio,
java.util.jar and
java.util.zip.
Smaller binaries
In #686, @densh started work to reduce the size of the binaries compiled by Scala Native, using a technique called selector-based row displacement.
These improvements make the dispatch table up to 10 times smaller, on some codebases in the wild.
0.4 and beyond
Some features are already in the works for Scala Native 0.4.
Windows support
@muxanick has been working on a port of Scala Native to Windows. The advancement of his work can be consulted in #691.
Automatic binding generation
A prototype of automatic binding generation is in development by
@jonas. The goal is to be able to generate automatically bindings
for C libraries. For instance, given the following C header
test.h:
enum color { RED = 1, GREEN, BLUE = 100 }; typedef int SomeInt; char *strchr(const char *s, int c);
We want to generate the following definitions:
@extern object Test { object color { val RED = 1 val GREEN = 2 val BLUE = 100 } type SomeInt = CInt def strchr(s: CString, c: CInt): CString = extern }
Ultimately, this tool will make it much easier to providing bindings for C’s stdlib and external libraries. | https://www.scala-lang.org/blog/2017/05/26/whats-new-scala-native.html | CC-MAIN-2021-43 | refinedweb | 1,142 | 57.37 |
The chips seem to do just fine as long as I plug them in the right order with no heat
I power on all the chips, wait a few min and they are all fine and cool to touch.
I plug in the arduino that has a different power source with a shared ground and 3 of the chips fry.
I have a bunch of 3w rgb leds with 350ma per led and a HengFu with two 20amp 5v outputs. The r3 resistor I used a 1.5ohm 2watt.
One weird thing, some of the tlc chips get really hot while others stay cool even with the same code pumping through them
have internal resistance of about 200k between power and ground pins
#include "Tlc5940.h"int green = 32; int blue = 0; int red = 64; void setup(){ Tlc.init();}void loop(){ Tlc.clear(); Tlc.set(red + 0, 4095); Tlc.set(red + 1, 4095); Tlc.set(red + 2, 4095); Tlc.set(green + 0, 4095); Tlc.set(green + 1, 4095); Tlc.set(green + 2, 4095); Tlc.update(); delay(350);}
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=80779.msg750911 | CC-MAIN-2015-11 | refinedweb | 212 | 84.68 |
Hi,
I wonder why the training loss does not decrease?
The input image batch has the shape of: [batch_size1200*200]. The true labels are in “one hot” form: [1,0,0], [0,1,0] and [0,0,1].
I have only 5000 images, so I decided to start from transfer learning.
I loaded pretrained ResNet18 to classify my images into 3 categories.
I change the input channel of ResNet18 to 1, and final output dimension to 3, in order to suit my classification problem.
So the shape of the model output tensor is [batch_size * 3], and the shape of the true label tensor is [batch_size * 3].
Since PyTorch does not provide the CrossEntropy loss function between those two tensors, I wrote my own cross entropy loss function based on the equation:
loss = t.mean(-t.sum(target.float() * t.log(y_prediction),dim=1))
Also I am confused about the output of ResNet18: I read somewhere that ResNet18 has softmax layer before output, but the elements of final output did not add up to 1? So I added a softmax layer after ResNet18.
My training code
import torch as t import torch.nn.functional as F device = t.device('cuda:1' if t.cuda.is_available() else 'cpu') optimizer = optim.SGD(model.parameters(), lr = 0.01, momentum = 0.9) for images, target in train_dataloader: images = images.float().to(device) target = target.float().to(device) optimizer.zero_grad() y_prediction = my_resnet18_model(images) y_prediction = F.softmax(y_prediction, dim = 1) loss = t.mean(-t.sum(target * t.log(y_prediction), dim = 1) loss.backward() optimizer.step() running_loss += loss.item() * images.shape[0] epoch_loss = running_loss / len(train_dataset) print('train loss: {}'.format(epoch_loss))
The epoch loss stayed around 1.09.
Am I using the loss function right?
Could I add the softmax after ResNet18?
How can I improve?
Any comments or suggestions are appreciated. Thanks in advance! | https://discuss.pytorch.org/t/cross-entropy-loss-not-decreasing-3-category-image-classification/25223 | CC-MAIN-2022-21 | refinedweb | 307 | 62.54 |
Welcome to the Wiki and blog space of Apache Cayenne
- a powerful and developer-friendly Java Object Relational Mapping (ORM) framework. To post comments, you need a Confluence account. If you don't have one yet, signup here
.
Contents
- Website
- Cayenne FAQ
- Board Reports
- Cayenne Examples
- Release 3.0 (release under development, includes JPA information)
- Summer of Code 2006
- Summer of Code 2008
Making Sense of Release Numbers
- Cayenne 3.0 (alpha, currently in development, approaching Beta) the next major release.
- Cayenne 2.0 (stable, released)
- Cayenne 1.2 (stable, released) is the last major release made from ObjectStyle.org, it mirrors matching 2.0 minor version numbers, only uses org.objectstyle package namespace. | http://cwiki.apache.org/CAY/ | crawl-002 | refinedweb | 114 | 53.37 |
- LESS and SASS. There are some others, but I have experience with only these two. In the first part of this article I'll share with you what I don't like about preprocessors and then in the second part I'll show you how I managed to solve most of the problems that I had.
The Problems
Setup
No matter which CSS preprocessor is involved, there is always setup required, like, you can't just start typing
.less or
.sass files and expect to get the
.css file. LESS requires NodeJS and SASS Ruby. At the moment, I'm working mostly on HTML/CSS/JavaScript/NodeJS applications. So, LESS seems like a better option, because I don't need to install additional software. You know, adding one more thing to your ecosystem means more time for maintenance. Also, not only do you need the required tool, but all of your colleagues should now integrate the new instrument as well.
Firstly, I chose LESS because I already had NodeJS installed. It played well with Grunt and I successfully finished two projects with that setup. After that, I started reading about SASS. I was interested in OOCSS, Atomic design and I wanted to build a solid CSS architecture. Very soon I switched to SASS, because it gave me better possibilities. Of course I (and my colleagues too) had to install Ruby.
Output
A lot of developers don't check the produced CSS. I mean, you may have really good looking SASS files, but what's used in the end is the compiled
.css file. If it is not optimized and its file size is high, then you have a problem. There are few things which I don't like in both preprocessors.
Let's say that we have the following code:
// LESS or SASS p { font-size: 20px; } p { padding: 20px; }
Don't you think that this should be compiled to:
p { font-size: 20px; padding: 20px; }
Neither LESS nor SASS works like that. They just leave your styles as you type them. This could lead to code duplication. What if I have complex architecture with several layers and every layer adds something to the paragraph. There will be several definitions, which are not exactly needed. You may even have the following situation:
p { font-size: 20px; } p { font-size: 30px; }
The correct code at the end should be only the following:
p { font-size: 30px; }
I now know that the browser will take care and will find out the right font size. But, isn't it better to save those operations. I'm not sure that this will affect the performance of your page, but it affects the readability for sure.
Combining selectors which share the same styles is a good thing. As far as I know, LESS doesn't do this. Let's say that we have a mixin and we want to apply it to two classes.
.reset() { padding: 0; margin: 0; } .header { .reset(); } .footer { .reset(); }
And the result is:
.header { padding: 0; margin: 0; } .footer { padding: 0; margin: 0; }
So, these two classes have the same styles and they could be combined into one definition.
.header, .footer { padding: 0; margin: 0; }
I was wondering if this is actual performance optimization, and I didn't find an accurate answer, but it looks like a good thing. SASS has something called
place holders. It's used exactly for such situations. For example:
%reset { padding: 0; margin: 0; } .header { @extend %reset; } .footer { @extend %reset; }
The code above produces exactly what I wanted. The problem is that if I use too many place holders I may end up with a lot of style definitions, because the preprocessor thinks that I have something to combine.
%reset { padding: 0; margin: 0; } %bordered { border: solid 1px #000; } %box { display: block; padding: 10px; } .header { @extend %reset; @extend %bordered; @extend %box; }
There are three place holders. The
.header class extends them all and the final compiled CSS looks like this:
.header { padding: 0; margin: 0; } .header { border: solid 1px #000; } .header { display: block; padding: 10px; }
It looks wrong, doesn't it? There should be only one style definition and only one
padding property.
.header { padding: 10px; margin: 0; border: solid 1px #000; display: block; }
Of course, there are tools which may solve this, having the compiled CSS. But as I said, I prefer to use as less libraries as possible.
Syntax Limitation
While I was working on OrganicCSS, I met a lot of limitations. In general, I wanted to write CSS as I write JavaScript. I mean, I had some ideas about complex architecture, but I wasn't able to achieve them, because the language which I was working with was kinda primitive. For example, let's say that I need a mixin which styles my elements. I want to pass a theme and border type. Here is how this should look in LESS:
.theme-dark() { color: #FFF; background: #000; } .theme-light() { color: #000; background: #FFF; } .component(@theme, @border) { border: "@{border} 1px #F00"; .theme-@{theme}(); } .header { .component("dark", "dotted"); }
Of course I'll have a lot of themes and they should also be mixins. So, the variable interpolation works for the border property, but not for the mixin names. That's a simple one, but it is currently not possible, or at least I don't know if it is fixed. If you try to compile the above code you will get
Syntax Error on line 11.
SASS is one step further. The interpolation works with placeholders, which makes things a little bit better. The same idea looks like this:
@mixin theme-dark() { color: #FFF; background: #000; } @mixin theme-light() { color: #000; background: #FFF; } %border-dotted { border: dotted 1px #000; } @mixin component($theme, $border) { @extend %border-#{$border}; @include theme-#{$theme}; } .header { @include component("dark", "dotted"); }
So, the border styling works, but the theme produces:
Sass Error: Invalid CSS after " @include theme-": expected "}", was "#{$theme};"
That's because the interpolation in the names of the mixins and extends is not allowed. There is a long discussion about that and will probably be fixed soon.
Both LESS and SASS are great if you want to improve your writing speed, but they are far from perfect for building modular and flexible CSS. Mainly, they are missing things like encapsulation, polymorphism and abstraction. Or at least, they are not in the form which I needed.
A New Approach
I fought several days with those limitation. I invested a good amount of time reading documentation. In the end, I just gave up and started looking for other options. What I had wasn't flexible enough and I started thinking about writing my own preprocessor. Of course, that's a really complex task and there are a lot of things to think about, such as:
- the input - normally preprocessors take code which looks like CSS. I guess the idea is to complete the language, such as add in missing, yet necessary features. It is also easy to port pure CSS and the developers could start using it immediately, because in practice, it is almost the same language. However, from my point of view, this approach brings few difficulties, because I had to parse and analyze everything.
- the syntax - even if I write the parsing part, I had to invent my own syntax which is kind of a complex job.
- competitors - there are already two really popular preprocessors. They have good support and an active community. You know, most of the coolest things in our sphere are so useful, because of the contributers. If I write my own CSS preprocessor and I don't get enough feedback and support from the people, I may be the only one which is actually using it.
So, I thought about it a bit and found a solution. There is no need to invent a new language with a new syntax. It's already there. I could use pure JavaScript. There is already a big community and a lot of people may start using my library immediately. Instead of reading external files, parsing and compiling them, I decided to use the NodeJS ecosystem. And of course, the most important thing - I completely removed the CSS part. Writing everything in JavaScript made my web application a lot cleaner, because I didn't have to deal with the input format and all those processes which produces the actual CSS.
(The name of the library is AbsurdJS. You may find this name funny and it is indeed. When I share my idea with some friends they all said, writing your CSS in JavaScript - absurd. So, that was the perfect title.)
AbsurdJS
Installation
To use AbsurdJS you need NodeJS installed. If you still don't have this little gem on your system go to nodejs.org and click the
Install button. Once everything finishes you could open a new console and type:
npm install -g absurd
This will setup AbsurdJS globally. This means that wherever you are, you may run the
absurd command.
Writing Your CSS
In the JavaScript world, the closest thing to CSS is JSON format. So, that's what I decided to use. Let's take a simple example:
.content { padding: 0; margin: 0; font-size: 20px; } .content p { line-height: 30px; }
This is pure CSS. Here is how it looks like in LESS and SASS:
.content { padding: 0; margin: 0; font-size: 20px; p { line-height: 30px; } }
In the context of AbsurdJS the snippet should be written like this:
module.exports = function(api) { api.add({ '.content': { padding: 0, margin: 0, 'font-size': '20px', p: { 'line-height': '30px' } } }); }
You may save this to a file called
styles.js and run:
absurd -s .\styles.js
It will compile the JavasSript to the same CSS. The idea is simple. You write a NodeJS package, which exports a function. The function is called with only one parameter - the AbsurdJS API. It has several methods and I'll go through them later, but the most common one is
add. It accepts valid JSON. Every object defines a selector. Every property of that object could be a CSS property and its value or another object.
Importing
Placing different parts of your CSS in different files is really important. This approach improves the readability of your styles. AbsurdJS has an
import method, which acts as the
@import directive in the CSS preprocessors.
var cwd = __dirname; module.exports = function(api) { api.import(cwd + '/config/main.js'); api.import(cwd + '/config/theme-a.js'); api.import([ cwd + '/layout/grid.js', cwd + '/forms/login-form.js', cwd + '/forms/feedback-form.js' ]); }
What you have to do is write a
main.js file which imports the rest of the styles. You should know that there is overwriting. What I mean is that if you define a style for the
body tag inside
/config/main.js and later in
/config/theme-a.js use the same property, the final value will be the one used in the last imported file. For example:
module.exports = function(api) { api.add({ body: { margin: '20px' } }); api.add({ body: { margin: '30px' } }); }
Is compiled to
body { margin: 30px; }
Notice that there is only one selector. While, if you do the same thing in LESS or SASS you will get
body { margin: 20px; } body { margin: 30px; }
Variables and Mixins
One of the most valuable features in preprocessors are their variables. They give you the ability to configure your CSS, such as define a setting somewhere in the beginning of the stylesheet and use it later on. In JavaScript, variables are something normal. However, because you have modules placed in different files you need something that acts as a bridge between them. You may want to define your main brand color in one file, but later use it in another. AbsurdJS offers an API method for that, called
storage. If you execute the function with two parameters, you create a pair:
key-value. If you pass only a key, you actually get the stored value.
// config.js module.exports = function(api) { api.storage("brandColor", "#00F"); } // header.js module.exports = function(api) { api.add({ header: { color: api.storage("brandColor") } }) }
Every selector may accept not only an object, but also an array. So this is also valid:
module.exports = function(api) { api.add({ header: [ { color: '#FF0' }, { 'font-size': '20px' } ] }) }
This makes sending multiple objects to specific selectors possible. It plays very well with the idea of mixins. By definition, the mixin is a small piece of code which could be used multiple times. That's the second feature of LESS and SASS, which makes them attractive for developers. In AbsurdJS the mixins are actually normal JavaScript functions. The ability to put things inside storage gives you the power to share mixins between the files. For example:
// A.js module.exports = function(api) { api.storage("button", function(color, thickness) { return { color: color, display: "inline-block", padding: "10px 20px", border: "solid " + thickness + "px " + color, 'font-size': "10px" } }); } // B.js module.exports = function(api) { api.add({ '.header-button': [ api.storage("button")("#AAA", 10), { color: '#F00', 'font-size': '13px' } ] }); }
The result is:
.header-button { color: #F00; display: inline-block; padding: 10px 20px; border: solid 10px #AAA; font-size: 13px; }
Notice, that there is only one selector defined and the
font-size property has the value from the second object in the array (the mixin defines some basic styles, but later they are changed).
Plugins
Ok, mixins are cool, but I always wanted to define my own CSS properties. I mean using properties that don't normally exist, but encapsulate valid CSS styles. For example:
.header { text: medium; }
Let's say that we have three types of text:
small,
medium and
big. Each of them has a different
font-size and different
line-height. It's obvious that I can achieve the same thing with mixins, but AbsurdJS offers something better - plugins. The creation of the plugin is again via the API:
api.plugin("text", function(api, type) { switch(type) { case "small": return { 'font-size': '12px', 'line-height': '16px' } break; case "medium": return { 'font-size': '20px', 'line-height': '22px' } break; case "big": return { 'font-size': '30px', 'line-height': '32px' } break; } });
This allows you to apply
text: medium to your selectors. The above styling is compiled to:
.header { font-size: 20px; line-height: 22px; }
Media Queries
Of course the library supports media queries. I also copied the idea of the
bubbling feature (you are able to define breakpoints directly inside the elements and AbsurdJS will take care for the rest).
api.add({ '.footer': { 'font-size': '14px', '@media all and (min-width: 320px) and (max-width: 550px)': { 'font-size': '24px' } }, '.content': { '@media all and (min-width: 320px) and (max-width: 550px)': { margin: '24px' } } })
The result is:
.footer { font-size: 14px; } @media all and (min-width: 320px) and (max-width: 550px) { .footer { font-size: 24px; } .content { margin: 24px; } }
Keep in mind that if you have the same media query used multiple times, the compiled file will contain only one definition. This actually saves a lot of bytes. Unfortunately LESS and SASS doesn't do this.
Pseudo Classes
For these, you just need to pass in valid JSON. The following example demonstrates how to use pseudo CSS classes:
module.exports = function(api) { api.add({ a: { 'text-decoration': 'none', ':hover': { 'text-decoration': 'underline' } } }); }
And it is compiled to:
a { text-decoration: none; } a:hover { text-decoration: underline; }
Integration
AbsurdJS works as a command line tool, but it could be used inside a NodeJS application as well. For example:
var Absurd = require("absurd"), absurd = Absurd(), api = absurd.api, output = "./css/styles.css"; api.add({ ... }).import("..."); absurd.compileFile(output, function(err, css) { // do something with the css });
Or if you have a file which acts as an entry point:
var Absurd = require("absurd"); Absurd("./css/styles.js").compileFile("./css/styles.css", function(err, css) { // do something with the css });
The library also supports integration with Grunt. You can read more about that on the following Github page.
Command Line Interface Options
There are three parameters available:
- [-s] - main source file
- [-o] - output file
- [-w] - directory to watch
For example, the following line will start a watcher for a
./css directory, will grab
./css/main.js as an entry point and will output the result to
./styles.css:
absurd -s ./css/main.js -o ./styles.css -w ./css
Conclusion
Don't get me wrong. The available CSS preprocessors are awesome, and I'm still using them. However, they came with their own set of problems. I managed to solve them by writing AbsurdJS. The truth is that I just replaced one tool with another. The usage of this library eliminates the usual writing of CSS and makes things really flexible, because everything is JavaScript. It could be used as a command line tool or it could be integrated directly into the application's code. If you are interested in AbsurdJS, feel free to check out the full documentation at github.com/krasimir/absurd or fork the repo.
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
| https://code.tutsplus.com/tutorials/absurdjs-or-why-i-wrote-my-own-css-preprocessor--net-36003 | CC-MAIN-2016-50 | refinedweb | 2,845 | 66.84 |
TypeError: Error # Cannot access a property or method of a null In a loop I was disposing all the items before getting them back from the pool and. My connection problems crop up when I try to start a battle. :P TypeError: Error # Cannot access a property or method of a null object reference. TypeError: Error # cannot access a property or method of a null object reference. The loop runs once as the test Array [0] and table [1].
Battle loop error. error #1009, null - congratulate, this
Hit Test help
Can I disable hit testing in Flash button?
I recently created a Flash game which is the extreme slowing down on the greatest levels. Use Adobe Scout with a version of the game that has Advanced telemetry activated, I learned that, on these levels, what we call 'hit test button' is engulf a huge piece of my game processor cycles - we're talking about 25 to 33 percent or more.
A few searches on Google directed me to this thread over 2 years, in which Mark Shepard noted that the hit test button is a process legacy meant to support the old class SimpleButton. He said that this led to the slowdown in scenes with many objects from the display list, and there is no way to avoid it otherwise than to reduce the number of objects in the display list.
Other users Chorus to say that the hit test button moved not when they switched to using touch rather than the events of mouse events. However, my game is for PC, and as such, I can't use the touch events rather than mouse events.
So my question is, basically: in 2 years because this problem has been reported, did you do something to allow programmers to turn off Flash button hit-testing? (Like, say, allowing us to set a flag to supportSimpleButtons to false to disable the button hit testing process?)
It answers the question, but it was not sufficiently clear.
Yes, disable mouse interactivity will stop the hit test. to stop the interactivitee use:
sprers.eunabled = false;
If this object is also a container of displayobject, also use
sprers.euhildren = false;
Simple Hit test
Hey, I have a clip with a provision of
1 PEnemy
2. the enemy
3 enemy
then the animations and on some mounts a MC with an instance name of "hit".
My video clip anime and I would like to detect testing with another child of another movie clip, called 'you' with a child MC called "target".
So I want bacicly
sprers.eu to sprers.eu of hitTest
I don't understand not hit test well in as3, it's what I have:
If (you. sprers.eutObject (sprers.eu));
But it does not work
Also, I get this output:
TypeError: Error # hitTestObject parameter must be null.
at sprers.euy::DisplayObject/_hitTest()
at sprers.euy::DisplayObject/hitTestObject()
at eugenehoudin5AS3_fla::MainTimeline/EnterFrame()
Code cannot target an object that does not exist, it must put in a logical conditional to check if the object is null or not. One thing you could do to make sure that the object still exists for the code also is it present in all frames, but make it invisible in frames where you do not want to be seen. In your code, you could test its visible property before you try to do the placement test - if it is invisible, pass the hit test.
Hit test timer
I am a construction game.
There is a timer that counts down from 60
the main character is a diver who must swim to the other side of the cave, but the diver must collect "oxegen icons" in order not to run out of air.
I am able to make the icon disappear when the diver swims above with a Hittest. How to add more time on the "timer" on the same hit test? Thank you
onClipEvent (enterFrame) {}
{if (This, HitTest (_root. Man))}
_sprers.eudPlay (10)
}
}
Try:
onClipEvent (enterFrame) {}
{if (This, HitTest (_root. Man))}
_sprers.eudPlay (10)
_root. Timer +=?; where? is any time you want to add
}
}
Helps the animation/Hit Test in AS3
I am developing a game in a school using Flash CS4 and Actionscript project. I have searched the web for help, but are empty. Here's what I want to do
I have a grid of 3 by 3 on the screen. Each block in the grid contains a clip with four objectives that scroll at 24 fps. Each target with have a different result depending on which frame the mouse is clicked. I do not what the animation to stop after that the frame is clicked, however. There are several different types of targets in the game. Some add points, some subtract points, a target has the avility to freeze activities for a defined period and another is basically an instant on play. Is that the way that I have found no help via the web before this post, I'm not even positive that it is possible to code in AS Does anyone know if this is possible, and if so, how I would go about coding it? Any help would be great!
If you have set your targets already on stage, make sure that you named all, jump the 2 lines and
var: target = new Target();
sprers.eu = "target1";
getChildByName("target1").addEventListener (sprers.eu, clickHandler);
getChildByName("target2").addEventListener (sprers.eu, clickHandler);
function clickHandler(e:MouseEvent):void {}
trace (sprers.eu);
results eventually in "target1".
trace (MovieClip (sprers.eutTarget) .currentFrame);
results in some framenumber animation of the selected MovieClip is during the click
}
Based on this here that you can easily write any other code that processes the results
TypeError: Error # with hit test, please help
-The actions and events-
sprers.euntListener (sprers.eu_MOVE, charMove);
function charMove(evt:MouseEvent)
{
addEventListener (sprers.eu_FRAME, checkcharCollision);
}
function checkcharCollision(event:Event)
{
for (var i: uint = 0; i < sprers.eu; i ++)
{
if (char [i] .hitTestObject (cur))
{
sprers.eu (i, 1);
lalLChannel = sprers.eu ();
lalL_sprers.eu = 1;
sprers.euransform = lalL_transform;
sprers.eudStop ("ful");
sprers.euntListener (sprers.eu_COMPLETE, lalLComplete);
}
}
}
and it gives me this error as soon as I move the mouse:
TypeError: Error # cannot access a property or method of a null object reference.
to INDEX_fla::MainTimeline/checkcharCollision()
NY ideas?
THX pavel
for (var i: uint = 0; i
Hit testing objects in the table problem
Hey guys, thank you very much in advance for any comments. These forums are a great help.
I have a serious problem with a loop in a table. I'm trying to hitTestObject each MC in a table against all other MC in this table. That part works.
The problem is that in my statement of hitTestObject, so obviously examines only 2 items at a time. When touch 2 MC, I put a property called 'Touch' to true. The problem is they are moving MCs and at one point touching only 2 / 3. What is happening is:
The loop runs once as the test Array [0] and table [1]. Say that those who are affected. She sets their properties 'Touch' true (it's what I want). THEN it works again test Array [1] and table [2] and finds that they are NOT overlapping. It this process it defines two of their properties 'Touch' to false, EVEN IF one of them may overlap a different array object.
I want to individual, set the property to "Touch" for each object in the table. Currently, these properties are getting crushed even if 2 / 3 objects are superimposed in fact.
That makes sense? Essentially the "else" statement is too often called because certain combinations of array objects are not touch, but others are.
CODE BELOW
sprers.euntListener (sprers.eu_FRAME, hitTestBalls);
function hitTestBalls(e:Event) {}
for (var m1:int = 0; m1 < sprers.eu; m1 ++) {}
for (var m2:int = m1 + 1; m2 < sprers.eu; m2 ++) {}
{if (MonsterArray [M1] .hitTestObject (MonsterArray [m2]))}
MonsterArray [m2]. Touch = true;
MonsterArray [m1]. Touch = true;
trace (MonsterArray [m1]. The touching, MonsterArray [m2]. Touch);
trace (M1, m2);
break?
} else {}
trace (M1, m2);
trace ("NotTouching");
MonsterArray [m1]. Touch = false; MonsterArray [m2]. Touch = false;
}
}
}
While waiting for a response, here's something to consider. You don't want to affect the Touching false at any time after that you start the analysis, only front
function hitTestBalls(e:Event) {}
first put all wrong
for (var m0:int = 0; m0< sprers.eu;="">
MonsterArray [m0]. Touch = false;
}
now test for overlapping - this way you don't overwrite anything with fake
for (var m1:int = 0; m1< sprers.eu;="">
for (var m2:int = m1 + 1; m2)< sprers.eu;="" m2++)="">
{if (MonsterArray [M1] .hitTestObject (MonsterArray [m2]))}
MonsterArray [m2]. Touch = true;
MonsterArray [m1]. Touch = true;
}
}
}
}
And if there be oinky be a pair that overlap as you say, you can add a breakdown; orders to end a loop when a hit is detected.
APP created with air for Android but does not work on the emulator to test - help!
When I createan applicationusingFlashCS> > > AIRFORANDROID.
After creatinga test pageI'm going topublishparameters andSendleApp onEmulatorRELEASE ofLeAPPisload correctlybut as soon asyou startthe emulator, give thiserror "applicationXXnameappXX(process air .)" XXnameappXX) hasstoppedunexpectedly. Pleasetry again"Please Help!
"Okay I find this before ' and install it on the android emulator! Now work all that I hope so! Thanks for your response!
Hit Test Dosent work
im making a type of game where you send your troops in battle when you click on the button buy
This is my script that will put the troops so stop thay and attack the target.
onClipEvent (enterFrame) {}
If (sprers.eut (enemyHouse)) {}
_x += ;
_sprers.eu_sprers.eu_sprers.eudPlay (9);
} else {}
_x += ;
}
}
so your troop in this case, which is a giant (giant_mc) walks when it reproduces until it hits the enemyHouse then it stops and goes to frame 9 his offensive frames, but that doesent happen he walks right past the enemyHouse and it dosent stop and animate.
Your design is a failure because of the way in which you are coding. Just do things because they work is not helping you solve the problems of things that do not work.
I would recommend that you stop placing code 'on' objects and start using the calendar for all of your code. Place the code on the objects is a bad habit.
Here you can use the code that replaces everything you have shown so far and it is placed on the timeline. I removed the useless lazy code (like Treasury = 0);. For this code, you must assign an instance name of your button (I use 'btn' in what I watch)
Giants of var = 0;
function addGiant() {}
If (cash > = ) {}
var giant = attachMovie ("giant_mc", "giant_mc" + giant, _sprers.eutHighestDepth (), {_x, _y});})
sprers.eurFrame = moveGiant;
Giants += 1;
cash-= ;
}
}
sprers.euase = addGiant;
function moveGiant() {}
If (sprers.eut (enemyHouse)) {}
delete sprers.eurFrame;
sprers.eu_sprers.eudPlay (9);
} else {}
This ._x += ;
}
}
whenever I hit the help in the taskbar it help & support not able to boot
original title: help & support does not
whenever I got help on the bar he spots help & support not able to start do - what I do
Hi Frank,.
Try this:
Go to start/run and
type: helpctr - regserver
To reinstall the help and Support: go to C:\Windows\inf\sprers.eu Right
Click on, then choose install. Have your CD at hand.
Note: The folder is hidden by default. Go to start/run and type in: control
records. View: Display the hidden files and folders and uncheck Hide extensions for
known file types.
hope this helps,
Eddie B.
How to make an ahpe base hit test.
I have a form that is currently added to the step. The user must interact with objects in the level. If they hit a set of objects above. Currently the car is moving only in a straight line. But I want that he follow the shape of the track to make it better. Any ideas as to how I could do this?
This is my current code:
import sprers.eu;
var: = new track;
var: car = new car;
flag: flag of var = new Flag;
var end: = end of new part EndGame;
sprers.euld (car);
car.x = ;
car.y = ;
sprers.euld (track);
Track.x = ;
Track.y = ;
sprers.euld (flag);
Flag.x = ;
Flag.y = ;
sprers.euntListener (sprers.eu_FRAME, moveCar);
function moveCar(e:Event):void
{
car.x += 5;
sprers.euntListener (sprers.eu_FRAME, CheckForCollisions);
}
function CheckForCollisions(e:Event):void
{
If (sprers.eutObject (flag))
{
removeEventListener (sprers.eu_FRAME, moveCar);
trace (":)");
because. Visible = false;
sprers.eue = false;
sprers.eue = false;
removeChild (track);
addChild (end);
end.x = ;
end.y = ;
}
}
Answered my self
hit testHello
I have a problem with the admission tests, if you make an object which is any shape other then a square he createds an invisable square around him and uses the ACE edge for admission tests. I have a ship that you move rounded astriods and I need to be exactly where you see the edge and no where is the edge of the box.
It's the code using im.
Thank you.
Yes, this is called the "BoundingBox" represents the min and max space occupied by the instance. In Flash, using a "shapeFlag" founded, there is another hitTest method, but it will compare only a single point. What you're looking for is to compare the two forms and it is not taken in charge, but there are solutions, is somewhat complex but. See Grant Skinners CollisionDetection class that does exactly this:
here: sprers.eu
irrational behavior in the hit test
OK, so I made three modules that were supposed to "align on" place when some of them crept over a particular coordinate (in this case, I created a grid using squares mc). When you release the mouse, the rest object and stopdrag lights for this object. When the object is clicked once again, it can be moved from it of locked position and moved elsewhere.
The problem is when each of the three objects are locked in place, even if they all have their own interaction with unique film clip coordinates, the other two cannot be moved. It doesn't matter which of the three is locked in place, the other two do not move either. I found this very confused, so I mounted three layers on each module to indicate if it was to drag a status of drag stop or "locked".
When using the following code, the elements begin to blink. By clicking on any of them changes the model of flashing and sometimes its quick, sometimes its slow and sometimes stops. We thought there was a reason (fast, slow, fast slow, stop) but discovered it wasn't really, and it's probably due with synchronization.
My big question is WHY the two other movie clips/modules are locking up when the third module snaps into place?
paleos var = - 1;
Red
Andromeda var = - 1;
Blue
synergy var = - 1;
Violet
onEnterFrame = function() {}
{if(Paleos==1)}
redpod_sprers.eudStop ("frame2");
} else {redpod_sprers.eudStop ("frame1");
}
{if(Synergy==1)}
violetpod_sprers.eudStop ("frame2");
} else {violetpod_sprers.eudStop ("frame1");
}
{if(Andromeda==1)}
bluepod_sprers.eudStop ("frame2");
} else {bluepod_sprers.eudStop ("frame1");
}
If (redpod_sprers.eut (grid01_mc._x, grid01_mc._y, true) & & paleos == 1) {}
redpod_mc._x = grid01_mc._x;
redpod_mc._y = grid01_mc._y;
redpod_sprers.euag ();
redpod_sprers.eudStop ("frame3");
synergy synergy = *-1;
Andromeda = Andromeda *-1;
}
If (bluepod_sprers.eut (grid02_mc._x, grid02_mc._y, true) & & Andromeda == 1) {}
bluepod_mc._x = grid02_mc._x;
bluepod_mc._y = grid02_mc._y;
bluepod_sprers.euag ();
bluepod_sprers.eudStop ("frame3");
Paleos = paleos *-1;
synergy synergy = *-1;
}
If (violetpod_sprers.eut (grid03_mc._x, grid03_mc._y, true) & & synergy == 1) {}
violetpod_mc._x = grid03_mc._x;
violetpod_mc._y = grid03_mc._y;
violetpod_sprers.euag ();
violetpod_sprers.eudStop ("frame3");
Paleos = paleos *-1;
Andromeda = Andromeda *-1;
}
}
redpod_sprers.eus = function() {}
redpod_sprers.eurag ();
Paleos = paleos *-1;
}
redpod_sprers.euase = function() {}
redpod_sprers.euag ();
}
violetpod_sprers.eus = function() {}
violetpod_sprers.eurag ();
synergy synergy = *-1;
}
violetpod_sprers.euase = function() {}
violetpod_sprers.euag ();
}
bluepod_sprers.eus = function() {}
bluepod_sprers.eurag ();
Andromeda = Andromeda *-1;
}
bluepod_sprers.euase = function() {}
bluepod_sprers.euag ();
}
It's messy, but I found a solution using a modified mouse listener created by Noct in
Action Script 3 registry test of positioning as an object is slipped on another object
Hi all, I have a problem working this. My question is about Action Script3
I want to be able to drag a clip on top of the other. While the clips are touch, I want to sign up for a hit test.
I used touch_begin and touch_end of pick up and drop my movieclip.
Can someone tell me the service I need to record a success as my object past on an another movieclip?
peace
You can use hitTestObject in a loop (for example, enterframe) while dragging if you do not need a shape-based placement test. end the loop when dragging stops.
Having some problems! Help, please!
Hi, I was watching a tutorial until I got stuck in the middle of it and was hopeing if someone could help me. I know that the tutorial is weird but I'm just to learn from him.
Here is the link to the tutorial: sprers.eu?v=zrSZxOALNRY - jammed at
So I don't know how he did image the same size whenever he placed the png in the area of the model because every time I put the 2nd photo is a different size and the possistioned in a different domain. If someone could help me please I would very much apreciate it. Also please tell me how you hate ponies and others that I'm just trying to learn. If you don't get what I mean please tell me and I'll try to re phrase it.
Thanks in advance!
You must go down the basics of EI. "Base" type in the search field in the help inside same EI and you will get these tutorials. Go through 3 or 4 without trying to follow just to get down the basic workflow and techniques.
Then type 'character animation' or 'puppet ' corner in the same field of research and take a look at these or these resources. One of the best hits will help you get started.
There are a ton of help out there, but you must have some knowledge base before any tutorial will help you make more that follow a recipe.
Making a button work in Flash CS3, CS4 or CS5 with ActionScript its not too bads classes
Now create an Array with all your buttons names in it like so;var btnArray:Array = new Array(home, aboutUs, contactUs); doesnt make sense keep reading
Leave them blank for now!function onMouseClick (event:MouseEvent):void { } function onMouseOver (evt:MouseEvent):void { } function onMouseOut (evt:MouseEvent):void { } arrays length property by setting it less then the sprers.eu sprers.eu class and if it is for navigation in the flash file then go back to your flash file and at the beginning of each section put a frame label with the same name as the button that will navigate to that section then use the sprers.eu property to go there like so) }
I hope that was clear enough for the smart ones lol any how the complete code is a lot more clean and short the writing ten functions and ten event listeners here it isvar btnArray:Array = new Array(home, aboutUs, contactUs);; }
Flex: sprers.eu
Goals / Motivations
Related Sponsored Content_sprers.e # Cannot access a property or method of a null object reference. At sprers.eution::AutomationManager/isObjectChildOfSystemManagerProxy()[C:\work\flex\dmv_automation\projects\automation_agent\src\mx\automation\sprers.eu] at sprers.eution::AutomationManager/recordAutomatableEvent()[C:\work\flex\dmv_automation\projects\automation_agent\src\mx\automation\sprers.eu] at sprers.eu::UIComponentAutomationImpl/recordAutomatableEvent()[E:\SVN\4.x\frameworks\projects\automation\src\mx\automation\delegates\core\sprers.eu] at sprers.eutClasses::SparkButtonBaseAutomationImpl/clickHandler()[E:\dev\4.x\frameworks\projects\automation_spark\src\spark\automation\delegates\components\supportClasses\sprers.eu] sprers.euicTabBarButton; import sprers.euyObject; import sprers.euvent; import sprers.eution; import sprers.euationObject; import sprers.euoggleButtonAutomationImpl; import sprers.eu; [Mixin] public class TerrificTabBarButtonDelegate extends SparkToggleButtonAutomationImpl { public static function init(root:DisplayObject):void { sprers.euer sprers.eu “sprers.eu,” which is what I expect as the close button is of that type.(sprers.eutionName != "closeButton") sprers.euandler(sprers.eutionName != "closeButton") sprers.euandler(event); } }
Figure 9 : TabBar Custom Delegate
If you are following along at home, do not forget to add the compile argument to include in the new delegate class, as the Flex compiler only includes classes that are referenced elsewhere in the code:-includes sprers.eu sprers.eu “sprers.eu” package. This event allows FlexMonkey to instantiate an event with just the “type” value and then set the “index” as property outside of the constructor. The “index” property is a custom event property that tells the TerrificTabBar component which tab to close.package sprers.eu { import sprers.eu; public class AutomationTerrificTabBarEvent extends Event { public var index:int; public function AutomationTerrificTabBarEvent(type:String, index:int=-1, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, bubbles, cancelable); sprers.eu = sprers.eu in the same directory as my MXML application source file. This causes Flash Builder to copy it out to the same “bin” directory as my SWF file, where FlexMonkey can load it and use it instead of the default version of the file. <Property Name="index"> <PropertyType Type="int"/> </Property> </Event> </Events> </ClassInfo>
Figure; sprers.euntListener(sprers.eu_TAB, closeHandler, false, sprers.euT+1, true); }
Figure(sprers.eu_TAB, sprers.eu)); }
Figure _sprers.euchEvent(new TerrificTabBarEvent(sprers.eu_TAB, (event as AutomationTerrificTabBarEvent).index)); } else { return sprers.euAutomatableEvent(event); } }
Figure
About the Author
Jon Rose is an enterprise software consultant and Flex Practice Director at Gorilla Logic, Inc. (sprers.eu) located in Boulder, Colorado. He is an editor and contributor to sprers.eu, an enterprise software community. He is the co-host of sprers.eu, a videocast for those who like booze and bits. He has worked with clients large and small in both the private sector and government. His love of solving problems drives him to build quality software. You can read his blog at: sprers.eu
This content is in the Microsoft topic
Related Topics:
Cannot access a property or method of a null object reference at zpp_sprers.eu::ZPP_Space/presteparb() #74
API Changes
Experimental APIs
Internal API
Those APIs are not intended to be used by clients, and will be hidden or removed with PMD You can identify them with the annotation. You’ll also get a deprecation warning.
- The protected or public member of the Java rule are deprecated and considered to be internal API. They will be removed with PMD 7.
External Contributions
Stats
- 43 commits
- 21 closed tickets & PRs
- Days since last release: 27
January -
The PMD team is pleased to announce PMD
This is a minor release.
Table Of Contents
New and noteworthy
SARIF Format
PMD now supports the Static Analysis Results Interchange Format (SARIF) as an additional report format. Just use the command line parameter to select it. SARIF is an OASIS standard format for static analysis tools. PMD creates SARIF JSON files in SARIF version An example report can be found in the documentation in Report formats for PMD.
CPD
- The C++ module now supports the new option , which can be used to avoid detection of some uninteresting clones. This options has been introduced with PMD for C# and is now available for C++ as well. See #
New Rules
The new Apex rule brings the well known Java rule to Apex. In Apex the same principle applies: and should always be overridden together to ensure collection classes such as Maps and Sets work as expected. | https://sprers.eu/battle-loop-error-error-1009-null.php | CC-MAIN-2022-40 | refinedweb | 3,894 | 66.33 |
Michael HuletTreehouse Moderator 47,600 Points
Phone Numbers Print Twice
I've gotten to the part of the video where we write the
print_phone_numbers method, and for some reason, all my phone numbers print twice. Here is my version of the aforementioned method:
def print_phone_numbers puts "\nPhone Numbers\n" + ("-" * 20) phone_numbers.each do |number| puts number end end
Here is the output of calling that method (after adding some phone numbers):
Phone Numbers -------------------- Home: (555)-555-5555 Work: (555)-555-5555 Home: (555)-555-5555 Work: (555)-555-5555
Curiously, if I add another
puts statement in the
each loop, so the
print_phone_numbers method looks like this:
def print_phone_numbers puts "\nPhone Numbers\n" + ("-" * 20) phone_numbers.each do |number| puts "Hi" puts number end end
The output looks like this:
Phone Numbers -------------------- Hi Home: (555)-555-5555 Hi Work: (555)-555-5555 Home: (555)-555-5555 Work: (555)-555-5555
Any idea how I could fix this?
EDIT: Here's the contents of both files involved in this program, since it was requested
require "./phone_number.rb" class Contact attr_writer :first_name, :middle_name, :last_name attr_reader :phone_numbers def initialize @phone_numbers = [] end def first_name return @first_name end def middle_name return @middle_name end def last_name return @last_name end def full_name name = first_name if !middle_name.nil? name += " #{middle_name}" end return name += " #{last_name}" end def last_first name = last_name + ", " + first_name if !middle_name.nil? name += " #{middle_name.slice(0, 1)}" end return name end def first_last return first_name + " " + last_name end def to_s(format = "full_name") case format when "full_name" return full_name when "last_first" return last_first when "first" return first_name when "last" return last_name else return first_last end end def add_phone_number(kind, number) phone_number = PhoneNumber.new phone_number.kind = kind phone_number.number = number phone_numbers.push phone_number end def print_phone_numbers puts "\nPhone Numbers\n" + ("-" * 20) iterations = 0 phone_numbers.each do |number| puts number iterations += 1 puts iterations end end end michael = Contact.new michael.first_name = "Michael" michael.last_name = "Hulet" michael.add_phone_number("Home", "(555)-555-5555") michael.add_phone_number("Work", "(555)-555-5555") puts michael.print_phone_numbers
class PhoneNumber attr_accessor :kind, :number def to_s return "#{kind}: #{number}" end end
2 Answers
Owen Tran6,822 Points
def print_phone_numbers puts "\nPhone Numbers\n" + ("-" * 20) phone_numbers.each do |number| puts number # <<< remove this end end
Owen Tran6,822 Points
So remove one of the puts, doesn't matter which one
Michael HuletTreehouse Moderator 47,600 Points
I removed one of the extraneous
puts statements, and it fixed my problem. Thanks so much!
Owen Tran6,822 Points
You're welcome :)
Owen Tran6,822 Points
What is phone_numbers? Can you post the rest of your code? And how are you calling the method?
This works:
phone_numbers = {"Home:" => '(555)-555-5555', "Work:" =>'(555)-555-5555'}
puts "\nPhone Numbers\n" + ("-" * 20)
phone_numbers.each do |key,number|
puts key + number
end
Michael HuletTreehouse Moderator 47,600 Points
phone_numbers is an array instance variable of the
Contact class. Per your request, I edited my post to include all of my code
Owen Tran6,822 Points
Owen Tran6,822 Points
or at the bottom
puts michael.print_phone_numbers
remove the puts to just :
michael.print_phone_numbers
The put here means you are putting the return value, then you are putting AGAIN in the method, that's why it's putting twice. Make sense? | https://teamtreehouse.com/community/phone-numbers-print-twice | CC-MAIN-2020-24 | refinedweb | 533 | 62.58 |
Accessing or modifying shared objects in signal handlers can result in race conditions that can leave data in an inconsistent state. The two exceptions (C Standard, 5.1.2.3, paragraph 5) to this rule are the ability to read from and write to lock-free atomic objects and variables of type
volatile sig_atomic_t. Accessing any other type of object from a signal handler is undefined behavior. (See undefined behavior 131.)
The need for the
volatile keyword is described in DCL22-C. Use volatile for data that cannot be cached.
The type
sig_atomic_t is the integer type of an object that can be accessed as an atomic entity even in the presence of asynchronous interrupts. The type of
sig_atomic_t is implementation-defined, though it provides some guarantees. Integer values ranging from
SIG_ATOMIC_MIN through
SIG_ATOMIC_MAX, inclusive, may be safely stored to a variable of the type. In addition, when
sig_atomic_t is a signed integer type,
SIG_ATOMIC_MIN must be no greater than
−127 and
SIG_ATOMIC_MAX no less than
127. Otherwise,
SIG_ATOMIC_MIN must be
0 and
SIG_ATOMIC_MAX must be no less than
255. The macros
SIG_ATOMIC_MIN and
SIG_ATOMIC_MAX are defined in the header
<stdint.h>.
According to the C99 Rationale [C99 Rationale 2003], other than calling a limited, prescribed set of library functions,
the C89 Committee concluded that about the only thing a strictly conforming program can do in a signal handler is to assign a value to a
volatile staticvariable which can be written uninterruptedly and promptly return.
However, this issue was discussed at the April 2008 meeting of ISO/IEC WG14, and it was agreed that there are no known implementations in which it would be an error to read a value from a
volatile sig_atomic_t variable, and the original intent of the committee was that both reading and writing variables of
volatile sig_atomic_t would be strictly conforming.
The signal handler may also call a handful of functions, including
abort(). (See SIG30-C. Call only asynchronous-safe functions within signal handlers for more information.)
Noncompliant Code Example
In this noncompliant code example,
err_msg is updated to indicate that the
SIGINT signal was delivered. The
err_msg variable is a character pointer and not a variable of type
volatile sig_atomic_t.
#include <signal.h> #include <stdlib.h> #include <string.h> enum { MAX_MSG_SIZE = 24 }; char *err_msg; void handler(int signum) { strcpy(err_msg, "SIGINT encountered."); } int main(void) { signal(SIGINT, handler); err_msg = (char *)malloc(MAX_MSG_SIZE); if (err_msg == NULL) { /* Handle error */ } strcpy(err_msg, "No errors yet."); /* Main code loop */ return 0; }
Compliant Solution (Writing
volatile sig_atomic_t)
For maximum portability, signal handlers should only unconditionally set a variable of type
volatile sig_atomic_t and return, as in this compliant solution:
#include <signal.h> #include <stdlib.h> #include <string.h> enum { MAX_MSG_SIZE = 24 }; volatile sig_atomic_t e_flag = 0; void handler(int signum) { e_flag = 1; } int main(void) { char *err_msg = (char *)malloc(MAX_MSG_SIZE); if (err_msg == NULL) { /* Handle error */ } signal(SIGINT, handler); strcpy(err_msg, "No errors yet."); /* Main code loop */ if (e_flag) { strcpy(err_msg, "SIGINT received."); } return 0; }
Compliant Solution (Lock-Free Atomic Access)
Signal handlers can refer to objects with static or thread storage durations that are lock-free atomic objects, as in this compliant solution:
#include <signal.h> #include <stdlib.h> #include <string.h> #include <stdatomic.h> #ifdef __STDC_NO_ATOMICS__ #error "Atomics are not supported" #elif ATOMIC_INT_LOCK_FREE == 0 #error "int is never lock-free" #endif atomic_int e_flag = ATOMIC_VAR_INIT(0); void handler(int signum) { e_flag = 1; } int main(void) { enum { MAX_MSG_SIZE = 24 }; char err_msg[MAX_MSG_SIZE]; #if ATOMIC_INT_LOCK_FREE == 1 if (!atomic_is_lock_free(&e_flag)) { return EXIT_FAILURE; } #endif if (signal(SIGINT, handler) == SIG_ERR) { return EXIT_FAILURE; } strcpy(err_msg, "No errors yet."); /* Main code loop */ if (e_flag) { strcpy(err_msg, "SIGINT received."); } return EXIT_SUCCESS; }
Exceptions
SIG31-C-EX1: The C Standard, 7.14.1.1 paragraph 5 [ISO/IEC 9899:2011], makes a special exception for
errno when a valid call to the
signal() function results in a
SIG_ERR return, allowing
errno to take an indeterminate value. (See ERR32-C. Do not rely on indeterminate values of errno.)
Risk Assessment
Accessing or modifying shared objects in signal handlers can result in accessing data in an inconsistent state. Michal Zalewski's paper "Delivering Signals for Fun and Profit" [Zalewski 2001] provides some examples of vulnerabilities that can result from violating this and other signal-handling rules.
Automated Detection
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
Key here (explains table format and definitions)
CERT-CWE Mapping Notes
Key here for mapping notes
CWE-662 and SIG31-C
CWE-662 = Union( SIG31-C, list) where list =
- Improper synchronization of shared objects between threads
- Improper synchronization of files between programs (enabling TOCTOU race conditions
CWE-828 and SIG31-C
CWE-828 = SIG31-C + non-async-safe things besides shared objects.
7 Comments
David Keaton
Yes, that's right. A signal handler can store into a
volatile sig_atomic_tof static storage duration but cannot read it. SIG00-A has one such access and it documents its violation of SIG31-C. If an NCCE surfaces that doesn't violate SIG31-C, so much the better.
Signal handlers can access all of their parameters and local variables. Only objects of static storage duration are off limits. For the purposes of this restriction, objects in the heap count as having static storage duration. The purpose is to allow all accesses in the signal handler's stack frame, and disallow everything but a store to a
volatile sig_atomic_teverywhere else.
Of course, this is just for maximally portable code. Most systems allow their own set of additional actions.
David Svoboda
Text and compliant example now both get & set static volatile sig_atomic_t values
Robert Seacord
Mitigation Strategies
Static Analysis
Compliance with this rule can be checked using structural static analysis checkers using the following algorithm:
signal(int, void (*f)(int)).
signal(int, void (*f)(int))get the second argument from the argument list. To make sure that this is not an overloaded function the function type signature is evaluated and/or the location of the declaration of the function is verified to be from the correct file (because this is not a link-time analysis it is not possible to test the library implementation). Any definition for
signal()in the application is suspicious, because it should be in a library.
sig_atomic_t.
Douglas A. Gwyn
It should be mentioned that _Exit (and probably abort) are not advisable, because atexit-registered handlers should be allowed to perform their intended functions before the program is terminated.
Also, there seems to be no real reason for a signal handler to want to read a flag; setting it is sufficient.
David Svoboda
re: _Exit()/abort(). Didn't we have this conversation on SIG30-C?
re: handlers reading flags. True, the examples didn't use to read flags. SIG00-C has example code that reads flags (implementing a finite state machine with them). The examples here do illustrate that reading sig_atomic_t flags is perfectly safe (if not particularly useful
Alex Volkovitsky
should we remove the note about "This may be necessary to ensure that the handler persists" since the cited recommendation tells us not to do this because of the race condition?
David Svoboda
Yes, I updated that paragraph, mainly deferring to SIG30, which discusses safe functions to call in signal handlers. | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152213 | CC-MAIN-2019-22 | refinedweb | 1,205 | 54.02 |
I'm trying to figure out what Catalyst has done in my project from an Illustrator comp I imported through Flash Catalyst.
I went through the process of designing my own Button component in Illustrator, and assigned the artwork as a button in Catalyst. When I look at the generated Button1.mxml file for the button, it begins like this:
<s:Skin xmlns:
This makes sense to me except for this reference to the namespace "ai". I can't seem to find any documentation as to what the ai namespace is or what's contained in it. It obviously must relate to Illustrator in some way, but I can't find any file included with the project that defines this namespace to the compiler or what components or properties are available through this namespace.
I do see a couple of components using the ai namespace though:
<s:Group
<s:BitmapImage
</s:Group>
So apparently there's a knockout property defined. What other features are available through the ai namespace? I looked through every manifest xml file and all of the included .swc files for clues but found absolutely nothing. How does Flash Builder even know about this uri?
Help appreciated.
Thanks! | https://forums.adobe.com/thread/505425 | CC-MAIN-2018-34 | refinedweb | 201 | 62.27 |
In this tutorial, we will develop a program that can recognize objects in a real-time video stream on a built-in laptop webcam using deep learning.
Object recognition involves two main tasks:
- Object Detection (Where are the objects?): Locate objects in a photo or video frame
- Image Classification (What are the objects?): Predict the type of each object in a photo or video frame
Humans can do both tasks effortlessly, but computers cannot.
Computers require a lot of processing power to take full advantage of the state-of-the-art algorithms that enable object recognition in real time. However, in recent years, the technology has matured, and real-time object recognition is now possible with only a laptop computer and a webcam.
Real-time object recognition systems are currently being used in a number of real-world applications, including the following:
- Self-driving cars: detection of pedestrians, cars, traffic lights, bicycles, motorcycles, trees, sidewalks, etc.
- Surveillance: catching thieves, counting people, identifying suspicious behavior, child detection.
- Traffic monitoring: identifying traffic jams, catching drivers that are breaking the speed limit.
- Security: face detection, identity verification on a smartphone.
- Robotics: robotic surgery, agriculture, household chores, warehouses, autonomous delivery.
- Sports: ball tracking in baseball, golf, and football.
- Agriculture: disease detection in fruits.
- Food: food identification.
There are a lot of steps in this tutorial. Have fun, be patient, and be persistent. Don’t give up! If something doesn’t work the first time around, try again. You will learn a lot more by fighting through to the end of this project. Stay relentless!
By the end of this tutorial, you will have the rock-solid confidence to detect and recognize objects in real time on your laptop’s GPU (Graphics Processing Unit) using deep learning.
Let’s get started!
Table of Contents
- You Will Need
- Install TensorFlow CPU
- Install TensorFlow GPU
- –Install CUDA Toolkit v9.0
- –Install the NVIDIA CUDA Deep Neural Network library (cuDNN)
- –Install TensorFlow GPU
- –Install TensorFlow Models
- –Install Protobuf
- –Install COCO API
- –Test the Installation
- Install LabelImg
- Recognize Objects Using Your WebCam
- –Approach
- –Implementation (Python Code)
You Will Need
Install TensorFlow CPU
We need to get all the required software set up on our computer. I will be following this really helpful tutorial.
Open an Anaconda command prompt terminal.
Type the command below to create a virtual environment named tensorflow_cpu that has Python 3.6 installed.
conda create -n tensorflow_cpu pip python=3.6
Press y and then ENTER.
A virtual environment is like an independent Python workspace which has its own set of libraries and Python version installed. For example, you might have a project that needs to run using an older version of Python, like Python 2.7. You might have another project that requires Python 3.7. You can create separate virtual environments for these projects.
Now, let’s activate the virtual environment by using this command:
conda activate tensorflow_cpu
Type the following command to install TensorFlow CPU.
pip install --ignore-installed --upgrade tensorflow==1.9
Wait for Tensorflow CPU to finish installing. Once it is finished installing, launch Python by typing the following command:
python
Type:
import tensorflow as tf
Here is what my screen looks like now:
Now type the following:
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
You should see a message that says: “Your CPU supports instructions that this TensorFlow binary….”. Just ignore that. Your TensorFlow will still run fine.
Now run this command to complete the test of the installation:
print(sess.run(hello))
Press CTRL+Z. Then press ENTER to exit.
Type:
exit
That’s it for TensorFlow CPU. Now let’s install TensorFlow GPU.
Return to Table of Contents
Install TensorFlow GPU
Your system must have the following requirements:
- Nvidia GPU (GTX 650 or newer…I’ll show you later how to find out what Nvidia GPU version is in your computer)
- CUDA Toolkit v9.0 (we will install this later in this tutorial)
- CuDNN v7.0.5 (we will install this later in this tutorial)
- Anaconda with Python 3.7+
Here is a good tutorial that walks through the installation, but I’ll outline all the steps below.
Install CUDA Toolkit v9.0
The first thing we need to do is to install the CUDA Toolkit v9.0. Go to this link.
Select your operating system. In my case, I will select Windows, x86_64, Version 10, and exe (local).
Download the Base Installer as well as all the patches. I downloaded all these files to my Desktop. It will take a while to download, so just wait while your computer downloads everything.
Open the folder where the downloads were saved to.
Double-click on the Base Installer program, the largest of the files that you downloaded from the website.
Click Yes to allow the program to make changes to your device.
Click OK to extract the files to your computer.
I saw this error window. Just click Continue.
Click Agree and Continue.
If you saw that error window earlier… “…you may not be able to run CUDA applications with this driver…,” select the Custom (Advanced) install option and click Next. Otherwise, do the Express installation and follow all the prompts.
Uncheck the Driver components, PhysX, and Visual Studio Integration options. Then click Next.
Click Next.
Wait for everything to install.
Click Close.
Delete C:\Program Files\NVIDIA Corporation\Installer2.
Double-click on Patch 1.
Click Yes to allow changes to your computer.
Click OK.
Click Agree and Continue.
Go to Custom (Advanced) and click Next.
Click Next.
Click Close.
The process is the same for Patch 2. Double-click on Patch 2 now.
Click Yes to allow changes to your computer.
Click OK.
Click Agree and Continue.
Go to Custom (Advanced) and click Next.
Click Next.
Click Close.
The process is the same for Patch 3. Double-click on Patch 3 now.
Click Yes to allow changes to your computer.
Click OK.
Click Agree and Continue.
Go to Custom (Advanced) and click Next.
Click Next.
Click Close.
The process is the same for Patch 4. Double-click on Patch 4 now.
Click Yes to allow changes to your computer.
Click OK.
Click Agree and Continue.
Go to Custom (Advanced) and click Next.
Click Next.
After you’ve installed Patch 4, your screen should look like this:
Click Close.
To verify your CUDA installation, go to the command terminal on your computer, and type:
nvcc --version
Return to Table of Contents
Install the NVIDIA CUDA Deep Neural Network library (cuDNN)
Now that we installed the CUDA 9.0 base installer and its four patches, we need to install the NVIDIA CUDA Deep Neural Network library (cuDNN). Official instructions for installing are on this page, but I’ll walk you through the process below.
Go to
Create a user profile if needed and log in.
Go to this page:
Agree to the terms of the cuDNN Software License Agreement.
We have CUDA 9.0, so we need to click cuDNN v7.6.4 (September 27, 2019), for CUDA 9.0.
I have Windows 10, so I will download cuDNN Library for Windows 10.
In my case, the zip file downloaded to my Desktop. I will unzip that zip file now, which will create a new folder of the same name…just without the .zip part. These are your cuDNN files. We’ll come back to these in a second.
Before we get going, let’s double check what GPU we have. If you are on a Windows machine, search for the “Device Manager.”
Once you have the Device Manager open, you should see an option near the top for “Display Adapters.” Click the drop-down arrow next to that, and you should see the name of your GPU. Mine is NVIDIA GeForce GTX 1060.
If you are on Windows, you can also check what NVIDIA graphics driver you have by right-clicking on your Desktop and clicking the NVIDIA Control Panel. My version is 430.86. This version fits the requirements for cuDNN.
Ok, now that we have verified that our system meets the requirements, lets navigate to C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0, your CUDA Toolkit directory.
Now go to your cuDNN files, that new folder that was created when you did the unzipping. Inside that folder, you should see a folder named cuda. Click on it.
Click bin.
Copy cudnn64_7.dll to C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin. Your computer might ask you to allow Administrative Privileges. Just click Continue when you see that prompt.
Now go back to your cuDNN files. Inside the cuda folder, click on include. You should see a file named cudnn.h.
Copy that file to C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\include. Your computer might ask you to allow Administrative Privileges. Just click Continue when you see that prompt.
Now go back to your cuDNN files. Inside the cuda folder, click on lib -> x64. You should see a file named cudnn.lib.
Copy that file to C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\lib\x64. Your computer might ask you to allow Administrative Privileges. Just click Continue when you see that prompt.
If you are using Windows, do a search on your computer for Environment Variables. An option should pop up to allow you to edit the Environment Variables on your computer.
Click on Environment Variables.
Make sure you CUDA_PATH variable is set to C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0.
I recommend restarting your computer now.
Return to Table of Contents
Install TensorFlow GPU
Now we need to install TensorFlow GPU. Open a new Anaconda terminal window.
Create a new Conda virtual environment named tensorflow_gpu by typing this command:
conda create -n tensorflow_gpu pip python=3.6
Type y and press Enter.
Activate the virtual environment.
conda activate tensorflow_gpu
Install TensorFlow GPU for Python.
pip install --ignore-installed --upgrade tensorflow-gpu==1.9
Wait for TensorFlow GPU to install.
Now let’s test the installation. Launch the Python interpreter.
python
Type this command.
import tensorflow as tf
If you don’t see an error, TensorFlow GPU is successfully installed.
Now type this:
hello = tf.constant('Hello, TensorFlow!')
And run this command. It might take a few minutes to run, so just wait until it finishes:
sess = tf.Session()
Now type this command to complete the test of the installation:
print(sess.run(hello))
You can further confirm whether TensorFlow can access the GPU, by typing the following into the Python interpreter (just copy and paste into the terminal window while the Python interpreter is running).
tf.test.is_gpu_available( cuda_only=True, min_cuda_compute_capability=None )
To exit the Python interpreter, type:
exit()
And press Enter.
Return to Table of Contents
Install TensorFlow Models
Now that we have everything setup, let’s install some useful libraries. I will show you the steps for doing this in my TensorFlow GPU virtual environment, but the steps are the same for the TensorFlow CPU virtual environment.
Open a new Anaconda terminal window. Let’s take a look at the list of virtual environments that we can activate.
conda env list
I’m going to activate the TensorFlow GPU virtual environment.
conda activate tensorflow_gpu
Install the libraries. Type this command:
conda install pillow lxml jupyter matplotlib opencv cython
Press y to proceed.
Once that is finished, you need to create a folder somewhere that has the TensorFlow Models (e.g. C:\Users\addis\Documents\TensorFlow). If you have a D drive, you can also save it there as well.
In your Anaconda terminal window, move to the TensorFlow directory you just created. You will use the cd command to change to that directory. For example:
cd C:\Users\addis\Documents\TensorFlow
Go to the TensorFlow models page on GitHub:.
Click the button to download the zip file of the repository. It is a large file, so it will take a while to download.
Move the zip folder to the TensorFlow directory you created earlier and extract the contents.
Rename the extracted folder to models instead of models-master. Your TensorFlow directory hierarchy should look like this:
TensorFlow
- models
- official
- research
- samples
- tutorials
Return to Table of Contents
Install Protobuf
Now we need to install Protobuf, which is used by the TensorFlow Object Detection API to configure the training and model parameters.
Go to this page:
Download the latest *-win32.zip release (assuming you are on a Windows machine).
Create a folder in C:\Program Files named it Google Protobuf.
Extract the contents of the downloaded *-win32.zip, inside C:\Program Files\Google Protobuf
Search for Environment Variables on your system. A window should pop up that says System Properties.
Click Environment Variables.
Go down to the Path variable and click Edit.
Click New.
Add C:\Program Files\Google Protobuf\bin
You can also add it the Path System variable.
Click OK a few times to close out all the windows.
Open a new Anaconda terminal window.
I’m going to activate the TensorFlow GPU virtual environment.
conda activate tensorflow_gpu
cd into your \TensorFlow\models\research\ directory and run the following command:
for /f %i in ('dir /b object_detection\protos\*.proto') do protoc object_detection\protos\%i --python_out=.
Now go back to the Environment Variables on your system. Create a New Environment Variable named PYTHONPATH (if you don’t have one already). Replace C:\Python27amd64 if you don’t have Python installed there. Also, replace <your_path> with the path to your TensorFlow folder.
C:\Python27amd64;C:\<your_path>\TensorFlow\models\research\object_detection
For example:
C:\Python27amd64;C:\Users\addis\Documents\TensorFlow
Now add these two paths to your PYTHONPATH environment variable:
C:\<your_path>\TensorFlow\models\research\
C:\<your_path>\TensorFlow\models\research\slim
Return to Table of Contents
Install COCO API
Now, we are going to install the COCO API. You don’t need to worry about what this is at this stage. I’ll explain it later.
Download the Visual Studios Build Tools here: Visual C++ 2015 build tools from here:
Choose the default installation.
After it has installed, restart your computer.
Open a new Anaconda terminal window.
I’m going to activate the TensorFlow GPU virtual environment.
conda activate tensorflow_gpu
cd into your \TensorFlow\models\research\ directory and run the following command to install pycocotools (everything below goes on one line):
pip install git+
If it doesn’t work, install git:
Follow all the default settings for installing Git. You will have to click Next several times.
Once you have finished installing Git, run this command (everything goes on one line):
pip install git+
Return to Table of Contents
Test the Installation
Open a new Anaconda terminal window.
I’m going to activate the TensorFlow GPU virtual environment.
conda activate tensorflow_gpu
cd into your \TensorFlow\models\research\object_detection\builders directory and run the following command to test your installation.
python model_builder_test.py
You should see an OK message.
Return to Table of Contents
Install LabelImg
Now we will install LabelImg, a graphical image annotation tool for labeling object bounding boxes in images.
Open a new Anaconda/Command Prompt window.
Create a new virtual environment named labelImg by typing the following command:
conda create -n labelImg
Activate the virtual environment.
conda activate labelImg
Install pyqt.
conda install pyqt=5
Click y to proceed.
Go to your TensorFlow folder, and create a new folder named addons.
Change to that directory using the cd command.
Type the following command to clone the repository:
git clone
Wait while labelImg downloads.
You should now have a folder named addons\labelImg under your TensorFlow folder.
Type exit to exit the terminal.
Open a new terminal window.
Activate the TensorFlow GPU virtual environment.
conda activate tensorflow_gpu
cd into your TensorFlow\addons\labelImg directory.
Type the following commands, one right after the other.
conda install pyqt=5
conda install lxml
pyrcc5 -o libs/resources.py resources.qrc
exit
Test the LabelImg Installation
Open a new terminal window.
Activate the TensorFlow GPU virtual environment.
conda activate tensorflow_gpu
cd into your TensorFlow\addons\labelImg directory.
Type the following commands:
python labelImg.py
If you see this window, you have successfully installed LabelImg. Here is a tutorial on how to label your own images. Congratulations!
Return to Table of Contents
Recognize Objects Using Your WebCam
Approach
Note: This section gets really technical. If you know the basics of computer vision and deep learning, it will make sense. Otherwise, it will not. You can skip this section and head straight to the Implementation section if you are not interested in what is going on under the hood of the object recognition application we are developing.
In this project, we use OpenCV and TensorFlow to create a system capable of automatically recognizing objects in a webcam. Each detected object is outlined with a bounding box labeled with the predicted object type as well as a detection score.
The detection score is the probability that a bounding box contains the object of a particular type (e.g. the confidence a model has that an object identified as a “backpack” is actually a backpack).
The particular SSD with Inception v2 model used in this project is the ssd_inception_v2_coco model. The ssd_inception_v2_coco model uses the Single Shot MultiBox Detector (SSD) for its architecture and the Inception v2 framework for feature extraction.
Single Shot MultiBox Detector (SSD)
Most state-of-the-art object detection methods involve the following stages:
- Hypothesize bounding boxes
- Resample pixels or features for each box
- Apply a classifier
The Single Shot MultiBox Detector (SSD) eliminates the multi-stage process above and performs all object detection computations using just a single deep neural network.
Inception v2
Most state-of-the-art object detection methods based on convolutional neural networks at the time of the invention of Inception v2 added increasingly more convolution layers or neurons per layer in order to achieve greater accuracy. The problem with this approach is that it is computationally expensive and prone to overfitting. The Inception v2 architecture (as well as the Inception v3 architecture) was proposed in order to address these shortcomings.
Rather than stacking multiple kernel filter sizes sequentially within a convolutional neural network, the approach of the inception-based model is to perform a convolution on an input with multiple kernels all operating at the same layer of the network. By factorizing convolutions and using aggressive regularization, the authors were able to improve computational efficiency. Inception v2 factorizes the traditional 7 x 7 convolution into 3 x 3 convolutions.
Szegedy, Vanhoucke, Ioffe, Shlens, & Wojna, (2015) conducted an empirically-based demonstration in their landmark Inception v2 paper, which showed that factorizing convolutions and using aggressive dimensionality reduction can substantially lower computational cost while maintaining accuracy.
Data Set
The ssd_inception_v2_coco model used in this project is pretrained on the Common Objects in Context (COCO) data set (COCO data set), a large-scale data set that contains 1.5 million object instances and more than 200,000 labeled images. The COCO data required 70,000 crowd worker hours to gather, annotate, and organize images of objects in natural environments.
Software Dependencies
The following libraries form the object recognition backbone of the application implemented in this project:
- OpenCV, a library of programming functions for computer vision.
- Pillow, a library for manipulating images.
- Numpy, a library for scientific computing.
- Matplotlib, a library for creating graphs and visualizations.
- TensorFlow Object Detection API, an open source framework developed by Google that enables the development, training, and deployment of pre-trained object detection models.
Return to Table of Contents
Implementation
Now to the fun part, we will now recognize objects using our computer webcam.
Copy the following program, and save it to your TensorFlow\models\research\object_detection directory as object_detection_test.py .
# Import all the key libraries utils import label_map_util from utils import visualization_utils as vis_util # Define the video stream cap = cv2.VideoCapture(0) # Which model are we downloading? # The models are listed here: MODEL_NAME = 'ssd_inception_v2_coco_2018_01_28' MODEL_FILE = MODEL_NAME + '.tar.gz' DOWNLOAD_BASE = '' # Path to the frozen detection graph. # This is the actual model that is used for the object detection. PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb' # List of the strings that is used to add the correct label for each box. PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt') # Number of classes to detect NUM_CLASSES = 90 # Download Model()) # Load a (frozen) Tensorflow model into memory.='') # Loading label map # Label maps map indices to category names, so that when our convolution network # predicts `5`, we know that this corresponds to `airplane`.) # Detection with detection_graph.as_default(): with tf.Session(graph=detection_graph) as sess: while True: # Read frame from camera ret, image_np = cap.read() # Expand dimensions since the model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) # Extract image tensor image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Extract detection boxes boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Extract detection scores scores = detection_graph.get_tensor_by_name('detection_scores:0') # Extract detection classes classes = detection_graph.get_tensor_by_name('detection_classes:0') # Extract number of detectionsd num_detections = detection_graph.get_tensor_by_name( 'num_detections:0') # Actual detection. (boxes, scores, classes, num_detections) = sess.run( [boxes, scores,) # Display output cv2.imshow('object detection', cv2.resize(image_np, (800, 600))) if cv2.waitKey(25) & 0xFF == ord('q'): cv2.destroyAllWindows() break print("We are finished! That was fun!")
Open a new terminal window.
Activate the TensorFlow GPU virtual environment.
conda activate tensorflow_gpu
cd into your TensorFlow\models\research\object_detection directory.
At the time of this writing, we need to use Numpy version 1.16.4. Type the following command to see what version of Numpy you have on your system.
pip show numpy
If it is not 1.16.4, execute the following commands:
pip uninstall numpy
pip install numpy==1.16.4
Now run, your program:
python object_detection_test.py
In about 30 to 90 seconds, you should see your webcam power up and object recognition take action. That’s it! Congratulations for making it to the end of this tutorial!
Keep building!
Return to Table of Contents | https://automaticaddison.com/real-time-object-recognition-using-a-webcam-and-deep-learning/ | CC-MAIN-2021-21 | refinedweb | 3,649 | 51.04 |
Let's begin with a little bit of theory. The idea behind the filter is to allocate a bit vector of length m, initially all set to 0, and then choose k independent hash functions, h1, h2, ..., hk, each with range [1 m]. When an element a is added to the set then the bits at positions h(a)1, h(a)2, ..., h(a)k in the bit vector are set to 1. Given a query element q we can test whether it is in the set using the bits at positions h(q)1, h(q)2, ..., h(q)k in the vector. If any of these bits is 0 we report that q is not in the set otherwise we report that q is. The thing we have to care about is that in the first case there remains some probability that q is not in the set which could lead us to a false positive response.
The following class is a naive implementation of a Bloom Filter (pay attention: this implementation is not supposed to be suitable for production. It is made just to show how a Bloom Filter works and to study its behavior):
class Bloom: """ Bloom Filter """ def __init__(self,m,k,hash_fun): """ m, size of the vector k, number of hash fnctions to compute hash_fun, hash function to use """ self.m = m # initialize the vector # (attention a real implementation # should use an actual bit-array) self.vector = [0]*m self.k = k self.hash_fun = hash_fun self.data = {} # data structure to store the data self.false_positive = 0 def insert(self,key,value): """ insert the pair (key,value) in the database """ self.data[key] = value for i in range(self.k): self.vector[self.hash_fun(key+str(i)) % self.m] = 1 def contains(self,key): """ check if key is cointained in the database using the filter mechanism """ for i in range(self.k): if self.vector[self.hash_fun(key+str(i)) % self.m] == 0: return False # the key doesn't exist return True # the key can be in the data set def get(self,key): """ return the value associated with key """ if self.contains(key): try: return self.data[key] # actual lookup except KeyError: self.false_positive += 1The usage of this filter is pretty easy, we have to initialize the data structure with a hash function, a value for k and the size of the bit vector then we can start adding items as in this example:
import hashlib def hash_f(x): h = hashlib.sha256(x) # we'll use sha256 just for this example return int(h.hexdigest(),base=16) b = Bloom(100,10,hash_f) b.insert('this is a key','this is a value') print b.get('this is a key')Now, the problem is to choose the parameters of the filter in order to minimize the number of false positive results. We have that after inserting n elements into a table of size m, the probability that a particular bit is still 0 is exactly
Hence, afer n insertions, the probability that a certain bit is 1 is
So, for fixed parameters m and n, the optimal value k that minimizes this probability is
With this in mind we can test our filter. The first thing we need is a function which tests the Bloom Filter for fixed values of m, n and k countinig the percentage of false positive:
import random def rand_data(n, chars): """ generate random strings using the characters in chars """ return ''.join(random.choice(chars) for i in range(n)) def bloomTest(m,n,k): """ return the percentage of false positive """ bloom = Bloom(m,k,hash_f) # generating a random data rand_keys = [rand_data(10,'abcde') for i in range(n)] # pushing the items into the data structure for rk in rand_keys: bloom.insert(rk,'data') # adding other elements to the dataset rand_keys = rand_keys + [rand_data(10,'fghil') for i in range(n)] # performing a query for each element of the dataset for rk in rand_keys: bloom.get(rk) return float(bloom.false_positive)/n*100.0If we fix m = 10000 and n = 1000, according to the equations above, we have that the value of k which minimizes the false positive number is around 6.9314. We can confirm that experimentally with the following test:
# testing the filter m = 10000 n = 1000 k = range(1,64) perc = [bloomTest(m,n,kk) for kk in k] # k is varying # plotting the result of the test from pylab import plot,show,xlabel,ylabel plot(k,perc,'--ob',alpha=.7) ylabel('false positive %') xlabel('k') show()The result of the test should be as follows
Looking at the graph we can confirm that for k around 7 we have the lowest false positive percentage.
In your theory description should it not read
"Given a query element q .... h(q)1, h(q)2, ..., h(q) in the vector"
rather than h(a)1, h(a)2, ..., h(a)
Thank you Simon. | http://glowingpython.blogspot.com/2013/01/bloom-filter.html | CC-MAIN-2016-18 | refinedweb | 824 | 61.87 |
DLLs and Visual C++ run-time library behavior
When you build a Dynamic-link Library (DLL) by using Visual Studio, by default, the linker includes the Visual C++ run-time library (VCRuntime). The VCRuntime contains code required to initialize and terminate a C/C++ executable. When linked into a DLL, the VCRuntime code provides an internal DLL entry-point function called
_DllMainCRTStartup that handles Windows OS messages to the DLL to attach to or detach from a process or thread. The
_DllMainCRTStartup function performs essential tasks such as stack buffer security set up, C run-time library (CRT) initialization and termination, and calls to constructors and destructors for static and global objects.
_DllMainCRTStartup also calls hook functions for other libraries such as WinRT, MFC, and ATL to perform their own initialization and termination. Without this initialization, the CRT and other libraries, as well as your static variables, would be left in an uninitialized state. The same VCRuntime internal initialization and termination routines are called whether your DLL uses a statically linked CRT or a dynamically linked CRT DLL.
Default DLL entry point _DllMainCRTStartup
In Windows, all DLLs can. When a DLL is loaded into a process address space, either when an application that uses it is loaded, or when the application requests the DLL at runtime, the operating system creates a separate copy of the DLL data. This is called process attach.. On process detach, the function goes through these steps in reverse. It calls
DllMain, decrements the internal counter, calls destructors, calls CRT termination functions and registered
atexit functions, and notifies any other libraries of termination. When the attachment counter goes to zero, the function returns
FALSE to indicate to Windows that the DLL can be unloaded. The
_DllMainCRTStartup function is also called during thread attach and thread detach. In these cases, the VCRuntime code does no additional initialization or termination on its own, and just calls
DllMain to pass the message along. If
DllMain returns
FALSE from process attach, signaling failure,
_DllMainCRTStartup calls
DllMain again and passes
DLL_PROCESS_DETACH as the reason argument, then goes through the rest of the termination process.
When building DLLs in Visual Studio, the default entry point
_DllMainCRTStartup supplied by VCRuntime is linked in automatically. You do not need to specify an entry-point function for your DLL by using the /ENTRY (Entry point symbol) linker option.
Note
While it is possible to specify another entry-point function for a DLL by using the /ENTRY: linker option, we do not recommend it, because your entry-point function would have to duplicate everything that
_DllMainCRTStartup does, in the same order. The VCRuntime provides functions that allow you to duplicate its behavior. For example, you can call __security_init_cookie immediately on process attach to support the /GS (Buffer security check) buffer checking option. You can call the
_CRT_INIT function, passing the same parameters as the entry point function, to perform the rest of the DLL initialization or termination functions.
Initialize a DLL
Your DLL may have initialization code that must execute when your DLL loads. In order for you to perform your own DLL initialization and termination functions,
_DllMainCRTStartup calls a function called
DllMain that you can provide. Your
DllMain must have the signature required for a DLL entry point. The default entry point function
_DllMainCRTStartup calls
DllMain using the same parameters passed by Windows. By default, if you do not provide a
DllMain function, Visual Studio provides one for you and links it in so that
_DllMainCRTStartup always has something to call. This means that if you do not need to initialize your DLL, there is nothing special you have to do when building your DLL.
This is the signature used for
DllMain:
#include <windows.h> extern "C" BOOL WINAPI DllMain ( HINSTANCE const instance, // handle to DLL module DWORD const reason, // reason for calling function LPVOID const reserved); // reserved
Some libraries wrap the
DllMain function for you. For example, in a regular MFC DLL, implement the
CWinApp object's
InitInstance and
ExitInstance member functions to perform initialization and termination required by your DLL. For more details, see the Initialize regular MFC DLLs section.
Warning
There are significant limits on what you can safely do in a DLL entry point. For more information about specific Windows APIs that are unsafe to call in
DllMain, see General Best Practices. If you need anything but the simplest initialization then do that in an initialization function for the DLL. You can require applications to call the initialization function after
DllMain has run and before they call any other functions in the DLL.
Initialize ordinary (non-MFC) DLLs
To perform your own initialization in ordinary (non-MFC) DLLs that use the VCRuntime-supplied
_DllMainCRTStartup entry point, your DLL source code must contain a function called
DllMain. The following code presents a basic skeleton showing what the definition of
DllMain might look like:
#include <windows.h> extern "C" BOOL WINAPI DllMain ( HINSTANCE const instance, // handle to DLL module DWORD const reason, // reason for calling function LPVOID const reserved) // reserved { // Perform actions based on the reason for calling. switch (reason) { case DLL_PROCESS_ATTACH: //. }
Note
Older Windows SDK documentation says that the actual name of the DLL entry-point function must be specified on the linker command-line with the /ENTRY option. With Visual Studio, you do not need to use the /ENTRY option if the name of your entry-point function is
DllMain. In fact, if you use the /ENTRY option and name your entry-point function something other than
DllMain, the CRT does not get initialized properly unless your entry-point function makes the same initialization calls that
_DllMainCRTStartup makes.
Initialize regular MFC DLLs
Because regular MFC
DLL_PROCESS_ATTACH and
DLL_PROCESS_DETACH, you should not write your own
DllMain function. The MFC-provided
DllMain function calls
InitInstance when your DLL is loaded and it calls
ExitInstance before the DLL is unloaded.
A regular MFC DLL can keep track of multiple threads by calling TlsAlloc and TlsGetValue in its
InitInstance function. These functions allow the DLL to track thread-specific data.
In your regular MFC DLL that dynamically links to MFC, if you are using any MFC OLE, MFC Database (or DAO), or MFC Sockets support, respectively, the debug MFC extension DLLs MFCOversionD.dll, MFCDversionD.dll, and MFCNversionD.dll (where version is the version number) are linked in automatically. You must call one of the following predefined initialization functions for each of these DLLs that you are using in your regular MFC DLL's
CWinApp::InitInstance.
Initialize MFC extension DLLs
Because MFC extension DLLs do not have a
CWinApp-derived object (as do regular MFC DLLs), you should add your initialization and termination code to the
DllMain function that the MFC DLL Wizard generates.
The wizard provides the following code for MFC extension DLLs. In the code,
PROJNAME is a placeholder for the name of your project.
#include "pch.h" // For Visual Studio 2017 and earlier, use "stdafx.h" #include <afxdllx.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static AFX_EXTENSION_MODULE PROJNAMEDLL; extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { if (dwReason == DLL_PROCESS_ATTACH) { TRACE0("PROJNAME.DLL Initializing!\n"); // MFC MFC extension DLL to export
CRuntimeClass objects or resources to the client application.
If you are going to use your MFC extension DLL from one or more regular MFC DLLs, you must export an initialization function that creates a
CDynLinkLibrary object. That function must be called from each of the regular MFC DLLs that use the MFC extension DLL. An appropriate place to call this initialization function is in the
InitInstance member function of the regular MFC DLL's
CWinApp-derived object before using any of the MFC MFC MFC extension DLL when each process detaches from the MFC extension DLL (which happens when the process exits or when the DLL is unloaded as a result of a
AfxFreeLibrary call). If your MFC extension DLL will be linked implicitly to the application, the call to
AfxTermExtensionModule is not necessary.
Applications that explicitly link to MFC MFC TlsAlloc when a DLL is attaching allows the DLL to maintain thread local storage (TLS) indexes for every thread attached to the DLL.
Note that the header file Afxdllx.h contains special definitions for structures used in MFC extension DLLs, such as the definition for
AFX_EXTENSION_MODULE and
CDynLinkLibrary. You should include this header file in your MFC extension DLL.
Note
It is important that you neither define nor undefine any of the
_AFX_NO_XXX macros in pch.h (stdafx.h in Visual Studio 2017 and earlier). These macros exist only for the purpose of checking whether a particular target platform supports that feature or not. You can write your program to check these macros (for example,
#ifndef _AFX_NO_OLE_SUPPORT), but your program should never define or undefine these macros.
A sample initialization function that handles multithreading is included in Using Thread Local Storage in a Dynamic-Link Library in the Windows SDK. Note that the sample contains an entry-point function called
LibMain, but you should name this function
DllMain so that it works with the MFC and C run-time libraries.
See also
Create C/C++ DLLs in Visual Studio
DllMain entry point
Dynamic-link Library Best Practices
Feedback
Submit and view feedback for | https://learn.microsoft.com/en-us/cpp/build/run-time-library-behavior?redirectedfrom=MSDN&view=msvc-170 | CC-MAIN-2022-40 | refinedweb | 1,540 | 50.67 |
Add "configure" as a tier for build metrics
RESOLVED FIXED in Firefox 48
Status
People
(Reporter: chmanchester, Assigned: chmanchester)
Tracking
(Depends on: 1 bug)
Firefox Tracking Flags
(firefox48 fixed)
Details
Attachments
(1 attachment)
Not sure exactly how complicated this will be, but it would be very nice to be able to chart progress as we move more things out of configure.
The tricky part is that configure is run from client.mk, and all the tier tracking stuff is in Makefiles. I guess one way to deal with it is to add some manual BUILDSTATUS echos in client.mk, and make the mach logic reading that handle the fact that we'd want to add tiers later on, because you won't have the full list of tiers before running configure.
Hm, it looks like the mach code reading tiers already doesn't mind if you call TIERS multiple times. At least, the output locally looks fine, checking on try now...
So the obvious place to put this is around, which ends up including backend generation, which we do care about, but might not be exactly what's expected from a number called "configure".
I would expect "configure" to include backend generation.
Created attachment 8741570 [details] MozReview Request: Bug 1264703 - Add configure as a tier to build metrics. r=gps This adds a "tier" to build status that measures the time to run configure and config.status. Review commit: See other reviews:
Attachment #8741570 - Flags: review?(gps)
Comment on attachment 8741570 [details] MozReview Request: Bug 1264703 - Add configure as a tier to build metrics. r=gps There is some wonkiness with this patch. But I don't think it is anything too worrying. ::: client.mk:370 (Diff revision 1) > ifdef FOUND_MOZCONFIG > -cp $(FOUND_MOZCONFIG) $(OBJDIR)/.mozconfig > endif > > configure:: $(configure-preqs) > + $(call BUILDSTATUS,TIERS configure) I'm kinda surprised that outputting the TIERS line multiple times has the desired effect! I would think last write would win. One weird thing this patch does is make the tier "progress" footer appear during configure. Before, there was an empty line at the bottom of the terminal during configure. What makes it weird is that during configure you only see a "configure" entry in the progress bar. Once configure finishes, the other tiers appear. The next build, the "configure" tier never appears because the configure target from client.mk is never evaluated. That's kinda wonky. But I don't think it matters that much. Although, in automation we'll have some builds that don't run the configure tier. Not sure if that will confuse things. Hopefully not.
Attachment #8741570 - Flags: review?(gps) → review+
Status: NEW → RESOLVED
Last Resolved: 3 years ago
status-firefox48: --- → fixed
Resolution: --- → FIXED
Target Milestone: --- → mozilla48
Product: Core → Firefox Build System | https://bugzilla.mozilla.org/show_bug.cgi?id=1264703 | CC-MAIN-2019-09 | refinedweb | 461 | 65.12 |
2 years, 4 months ago.
RN2483
This question is relevant to any project trying to bridge a platform's built in USB to UART controller with a second on board UART.
Quote:
In my case, I'm trying to type AT style commands on a computer connected by USB to a NXP FRDM microcontroller that exposes UART0 (hardwired to USB) as well as UART1 on pins PTC3(RX) and PTC4(TX) connected to a LoRa IC:
FRDM-KL25Z Platform document
RN2483 IC device datasheet
Missing text output from second connected UART
#include "mbed.h" Serial Conn(USBTX, USBRX); Serial Lora(PTC4, PTC3); int main() { Conn.baud(57600); // 57600 baud is specified in the Lora.baud(57600); // Microchip RN2483 datasheet Conn.printf("RN2483 Communication!\r\n"); // This works Lora.printf("sys get ver\r\n"); // This fails? No text returned. // Try passing characters while(1) { if(Conn.readable()) { Lora.putc(Conn.getc()); } if(Lora.readable()) { Conn.putc(Lora.getc()); } } }
Question
This seems logically correct, and providing the 'PTC[34]' parameters to a RN2483 mbed library correctly communicates with the IC's UART and prints characters in my serial console. So why isn't anything appearing in my serial console when I manually configure (and avoid the RN2483 lib) two serial connections?
Answer
This problem was solved by properly capturing line ending characters and remapping to CR+LF which is what the IC device expects to terminate all command sequences. I may post more information (like a program) later.
1 Answer
1 year, 8 months ago.
Serial.printf works a bit weird. This is how I did it.
#include "mbed.h" Serial lora(D8,D2); Serial pc(USBTX,USBRX); int main() { lora.baud(57600); pc.baud(57600); pc.printf("HelloWorld!\n"); char str[64] = "sys get ver\r\n\0"; int i=0; while(str[i]!='\0') { lora.putc(str[i]); i++; } while(1) { if(lora.readable()) { pc.putc(lora.getc()); } } }
You need to log in to post a question | https://os.mbed.com/questions/78298/RN2483/ | CC-MAIN-2019-47 | refinedweb | 328 | 58.79 |
Please report
issues and
patches to siftgpu@github.com
Search Criteria
Package Details: siftgpu 0.5.400-9
Dependencies (6)
- devil>=1.7 (devil-ilut-vanilla)
- glew>=1.8 (glew-libepoxy, glew-git, glew-egl-glx)
- freeglut>=2.7 (freeglut-x11-svn, freeglut-wayland-svn)
- cuda (cuda65, cuda-11.0) (make)
- git (git-git) (make)
- opencl-nvidia (opencl-nvidia-410xx, opencl-nvidia-340xx, opencl-nvidia-440xx, opencl-nvidia-full-vulkan-all, opencl-nvidia-vulkan, opencl-nvidia-beta, opencl-nvidia-390xx) (optional)
Required by (1)
Sources (2)
bartus commented on 2019-04-10 11:43
Please report
bartus commented on 2018-06-05 13:21
@ILMostro7: fixed.
ILMostro7 commented on 2018-06-01 19:32
The
optdepends doesn't take a version for packages listed. Otherwise, you get the following:
==> ERROR: optdepends contains invalid characters: '>='
bartus commented on 2018-04-03 21:08
@ILMostro7: I think, I find the issue, the problem arose when an extra copy of
libcudart.so on your system triggers cuda kernel build. Now it checks only for
/opt/cuda/lib64/libcudart.so.
bartus commented on 2018-03-29 19:36
@ILMostro7:
siftgpu works also with
GLSL and
opencl besides
cuda. All three are run time detected by makefile script.
9 # enable CUDA-based SiftGPU? 10 simple_find_cuda = $(shell locate libcudart.so) 11 ifneq ($(simple_find_cuda), ) 12 siftgpu_enable_cuda = 1 13 else 14 siftgpu_enable_cuda = 0 15 endif 16
It's strange that it fails on a system without cuda ... I can build
siftgpu in chroot without
cuda with no problem.
ILMostro7 commented on 2018-03-29 19:11
Should
cuda be a dependency, rather than optdepends?
I get a failure if cuda is not installed, as the installation fails to find "cuda.h".
bartus commented on 2018-03-28 23:08
@Harvie: Yes, looks like it works, updating.
Harvie commented on 2018-03-28 22:03
I've removed the gcc5 hack and it seems to work
Harvie commented on 2018-03-28 21:57
Can we build this with gcc7?
dbrgn commented on 2017-04-19 07:45
I'm disowning this package since I don't use it myself anymore.
Pinned Comments
bartus commented on 2019-04-10 11:43
Please report
issuesand
patchesto siftgpu@github.com | https://aur.tuna.tsinghua.edu.cn/packages/siftgpu/ | CC-MAIN-2021-04 | refinedweb | 369 | 50.63 |
I'm attempting to use unicode with eGUI(D4D). Everything works fine when just using ASCII but I can't get things to compile once I #define D4D_UNICODE. I've never used unicode before so there is probably just something I'm missing. I'm running on a Kinetis K70 with MQX 4.1 with the eGUI 3.01 from github Gargy007/eGUI · GitHub all building in CodeWarrior 10.6. Here is a sample of my code.
#include "wchar.h" const wchar_t * ws = L"Wide string"; D4D_WCHAR english[] = {L"English"};
Line 3 has the error: unknown type name 'wchar_t'
Line 3 has the error: wide character array initialized from incompatible wide string
From what I understand I need the 'L' before my string to make it a long string but that doesn't seem to help.
Does anyone know what I've done wrong.
Thanks,
Sean
Hello Sean,
I was working with IAR, whose compiler interprets the short and int type variables different. I compiled a demo in CW and I got the same error, the solution was change the D4D_WCHAR type variable.
In the file "d4d_types.h" you have to change the D4D_WCHAR typedef from unsigned short to unsigned int.
From:
To:
I hope this solve your problem.
Regards,
Earl Orlando.
/* If this post solve your problem please click the Correct Answer button. */ | https://community.nxp.com/thread/356729 | CC-MAIN-2018-43 | refinedweb | 224 | 83.66 |
I think people mix up this: char *buf = new char;
with this: char *buf = new char[256];
They mix up number of elements with number of bytes.
this means allocating 256 element.this means allocating 256 element.Code:char *buf = new char[256];
file.append(buf); and here you are using only one element of 256 and you can assign as many byte as you like to it.
Whereas here i can assign as many characters as i want with only one element,
this code's working:
Do i see it right or am i missing the point?Do i see it right or am i missing the point?Code:#include <iostream> using namespace std; int main() { char *buf2 = new char; strcpy(buf2, "hellooooooooooooooooooooooo!"); cout << buf2 <<"\n"; delete buf2; return 0; }
I see all the time this. | http://cboard.cprogramming.com/cplusplus-programming/118397-new-char-vs-new-char%5Bsize%5D.html | CC-MAIN-2014-42 | refinedweb | 137 | 82.75 |
Reminder: Migrate Your JInitiator Clients to Sun JRE Now!
By Steven Chan - EBS-Oracle on Dec 30, 2008
The on December 31, 2008 at 02:49 AM PST # on December 31, 2008 at 08:04 AM PST #
It might be worth noting that JRE6u11 (and possibly u10 as well) don't push out properly via an .msi, it should be fixed in u12 though.
Posted by Ian Neal on January 01, 2009 at 08:26 AM PST #
Hi, Ian,
Thanks for that tip. I wasn't aware of that issue. I hope Sun resolves this soon.
Regards,
Steven
Posted by Steven Chan on January 02, 2009 at 04:17 AM PST # on January 07, 2009 at 11:09 PM PST # on January 08, 2009 at 03:42 AM PST # on January 09, 2009 at 02:22 AM PST # on January 09, 2009 at 02:41 AM PST # on January 13, 2009 at 11:10 PM PST # on January 14, 2009 at 05:45 AM PST # on January 15, 2009 at 06:10 AM PST # on January 15, 2009 at 06:55 AM PST # on January 19, 2009 at 05:56 PM PST #
Hi, Connell,
Thanks for the SR number. We'll be working with your Support engineer on this one.
Regards,
Steven
Posted by Steven Chan on January 20, 2009 at 06:49 AM PST # on January 20, 2009 at 05:40 PM PST # on January 25, 2009 at 02:00 AM PST # on January 27, 2009 at 08:17 AM PST # on February 15, 2009 at 01:09 PM PST # on February 17, 2009 at 03:40 AM PST # on February 26, 2009 at 12:11 PM PST # on February 27, 2009 at 07:57 AM PST # on March 03, 2009 at 03:57 PM PST # on March 04, 2009 at 06:56 AM PST # on March 04, 2009 at 10:06 PM PST # on March 05, 2009 at 03:07 AM PST # on March 10, 2009 at 11:20 PM PDT # on March 12, 2009 at 02:45 AM PDT # on April 10, 2009 at 02:52 AM PDT # on April 13, 2009 at 07:04 AM PDT #
We just migrated from Jinitiator 1.3.1 to JRE 1.5.0_19-b02 and having issues with mouse navigation with our custom forms 10g applications. Has anyone encountered this issue? Please let me know what I need to do to fix this.
Thanks,
Srini
Posted by Srini on July 13, 2009 at 05:08 AM PDT #
Hello Srini,
I am not clear if you are using eBusiness Suite or standalone Forms Server, but in either case it would probably be best to raise a Service Request with Oracle Support (with either the eBiz team or Forms team respectively) in order we can investigate the exact circumstances of your issue.
For eBusiness Suite 11i customers having this kind of issue, there is Note 760250.1 "Diagnosing Forms Mouse Focus Problems Using JRE in Release 11i" which may be useful to help diagnosing the root cause
Hope this helps
Mike Shaw
Posted by Mike Shaw on July 13, 2009 at 04:03 PM PDT #
Hi Steven,
I have been following your blog with interest, and wonder if you can clarify a situation please - or direct me to a contact in Oracle to obtain clarification.
We have recenlty upgraded our desktops to Sun JRE 1.5.0_16 for use with eBusiness 11.5.10 - as per your postings to move off JInitiator.
I need some clarification around the supported levels of JRE clients. Reading around there are references to the minimum supported JRE's. However with Sun's End of Life date for 1.5 does this not impact the support?
Also, is there a date planned where Oracle would no longer support eBusiness on JRE 1.5 clients, prompting a move to 1.6
Thanks for you help
Regards
Adam
Posted by Adam Fidler on July 13, 2009 at 09:22 PM PDT #
Hello, Adam,
Thanks for the feedback on our blog. Glad to hear that you've found it useful.
You might find the following article useful:
Understanding J2SE 1.5 End-of-Life Implications for Oracle E-Business Suite -
Feel free to let me know if you have any additional questions.
Regards,
Steven
Posted by Steven Chan on July 14, 2009 at 03:51 AM PDT #
We are in the process of converting from Jinit 1.3.1.29 to Sun's JVM 1.5.0_18-b02. The version of the JVM we run is controlled by another COTS package.
We are running into some issues with Sun’s JVM
1.Sometimes when launching a custom Oracle Forms (10.1.2.3) application the system will core dump and generate a log file. The header of the log file is below.
#
# An unexpected error has been detected by HotSpot Virtual Machine:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x6d1f8111, pid=2548, tid=1788
#
# Java VM: Java HotSpot(TM) Client VM (1.5.0_18-b02 mixed mode, sharing)
# Problematic frame:
# C 0x6d1f8111
#
2.After you receive the core dump the next time you try to launch the application you may receive the following error in the forms console window, in the message area.
error:java.lang.ExceptionInitializerError
If you do not close the start page (HTML start page to launch the application) you
Will receive the following message.
error:java.lang.NoClassDefFoundError
If you close the start page and reopen it forms will launch properly.
3.The last issue we have found is forms sometimes seems to freeze and not repaint the screen when selecting menu options.
Let me know if you can help with any of these issues.
Thanks,
John
Posted by John on July 14, 2009 at 11:31 PM PDT #
Hello, John,
I'm afraid that I don't have any insight into the root cause of this. Since this problem is occurring with a generic Forms-based application and not the Oracle E-Business Suite, your best bet might be to log a formal Service Request with the Oracle Forms team directly.
Good luck with this one.
Regards,
Steven
Posted by Steven Chan on July 15, 2009 at 02:23 AM PDT #
Hi Steve,
Thanks for the wonderful blog and your kind quick response. Currently we are in Jinit 1.3.1.29.
I am planning to upgrade J2SE 1.5 but I noticed that (j2se1.5) the end of life is October 2009. What is your suggestion to me? Shall I go with 1.6? We are in 11.5.10.2(EBS).
Thanks
Prince
Posted by Prince Suthakar on October 08, 2009 at 12:10 AM PDT #
Hi, Prince,
If I were an IT manager facing the choice between J2SE 1.5 and 1.6, I'd go with 1.6 without hesitation. There's no real reason to upgrade to a Java release that will be desupported by Sun in a matter of weeks.
Regards,
Steven
Posted by Steven Chan on October 08, 2009 at 02:39 AM PDT #
Hi Steven,
Your blog has proved invaluable whilst migrating from Jinitiator 1.3.1.28 ---> JRE 1.6.0_13. Just want to thank you for your effort.
Currently we have two sets of clients trying to access Ebusiness Suite via JRE. One set who uses JRE controlled via individual desktop level, and another set who access it via some Citrix infrastructure.
The first set at individual desktop level, has been 99% successful bar some slow loading at times (sometimes up to about 4mins). It always seems to be the first time which is slow?
The second set is having serious issues in that it can sometimes take up to 30mins to load the EBS Forms session. Its also sometimes refusing to load at all. This has been very serious and we've had to revert the clients back to Jinit at user profile option level in EBS, which you'll appreciate is not ideal.
In my mind, the odd 4mins loading period (window just appears to be inactive and suddenly pops the core forms session up), is highly unacceptable.
Just really looking for some feedback/advice if you have any.
Massively appreciated.
Many thanks,
Gary
Posted by Gary Lythgoe on October 13, 2009 at 12:18 AM PDT #
Hi, Gary,
Thanks for the feedback on our blog. Glad to hear that you've found it useful.
The slowness of the first load is likely due to the fact that the JRE is downloading from your application tier server to your end-user's desktop. This is a one-time process, since subsequent Forms invocations should notice that the JRE is already installed, and thereby will skip the download.
The second issue you note is not what I'd expect to see. I'd like to ensure that you get some help from us in investigating this. 19, 2009 at 03:45 AM PDT #
Hi Steven,
We have upgraded to JRE 1.5.0_10 on our R12 instances with Forms 10.1.2.3. Our users are occasionally getting the following:
Exception in thread "AWT-EventQueue-3" java.lang.NoClassDefFoundError: oracle/bali/share/util/BooleanUtils
at oracle.ewt.scrolling.MouseWheelUtils.dispatchMouseWheelEvent(Unknown Source)
at oracle.ewt.event.tracking.GlassMouseGrabProvider$Proxy: oracle.bali.share.util.BooleanUtils
at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 20 more)
... 24 more
and they are affectively locked out of the application. I haven't been able to find anything similar in MetaLink to help resolve the issue. Any ideas?
Regards,
Pete
Posted by Pete Waller on October 23, 2009 at 05:56 AM PDT #
Hi, Pete,
I'm afraid that I don't have any insight into what might be going on here. I'd like to have one of our JRE experts look into this for you. If this is still an issue, 27, 2009 at 02:40 AM PDT #
Hi Steven\Peter,
For what it is worth we have the exact same issue as Peter.
Exception in thread "AWT-EventQueue-3" java.lang.NoClassDefFoundError: oracle/bali/share/util/BooleanUtils
at oracle.ewt.scrolling.MouseWheelUtils.dispatchMouseWheelEvent(Unknown Source)
...
We are running on 11.5.10 ATG6. Dev suite 6i patchset 19 on AIX 5.3\6.1. Using JRE 6u16. I have raised an SR but thought i would mention it here also given Peter's post.
Regards,
Lindsey
Posted by Lindsey McGregor on November 02, 2009 at 12:33 PM PST #
The users get the same error.
Exception in thread "AWT-EventQueue-2" java.lang.NoClassDefFoundError: oracle/bali/share/util/BooleanUtils
at oracle.ewt.scrolling.MouseWheelUtils.dispatchMouseWheelEvent(Unknown Source)
Did any one on the thread get this resolved.
Posted by Rajeev on November 03, 2009 at 12:00 AM PST #
Hi, Lindsey,
I'm sorry to hear that you're hitting the same issue. Thanks for the heads-up on your SR. I would definitely like to monitor this closely. Would you mind emailing your SR number to me?
Regards,
Steven
Posted by Steven Chan on November 03, 2009 at 02:13 AM PST #
Hello. We have migrated from Jinitiator 1.3.1.28 to JRE 1.6.0_16-b01 and are experiencing freezing and crashing issues with Oracle EBS (11.5.10.2). The issue happens sporatically and we are unable to recreate it at will. I've read that having Jinitiator and JRE on the system creates a conflict. Our machines currently have both installed as some of our other applications use Jinitiator. We are not sure what the impact would be on these other applications if we remove Jinitiator (I would think the applications should automatically point to JRE???). Do you have any insight on this? If both JVM's must remain on the machines, any idea on how to resolve the issue? We have been communicating to our users to open separate IE sessions when opening other applications however, we are still having the issue. Some of the users only have Oracle and Outlook open and still freeze and crash. I've found this blog to be very informational but not sure how to go about resolving our issue. One more thing to note, when a user crashes, a log file is created on their desktop. Please see below. The one thing I did notice consistent in all of the log files we've viewed is the problematic frame references mshtml.dll. The only thing I've been able to find on this is to install a new version of IE (we are currently on IE7).
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x3dba2a2a, pid=4356, tid=2296
#
# JRE version: 6.0_16-b01
# Java VM: Java HotSpot(TM) Client VM (14.2-b01 mixed mode, sharing windows-x86 )
# Problematic frame:
# C [mshtml.dll+0x182a2a]
#
# If you would like to submit a bug report, please visit:
#
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
--------------- T H R E A D ---------------
Current thread (0x05f1d400): JavaThread "Thread-0" [_thread_in_native, id=2296, stack(0x08310000,0x08410000)]
siginfo: ExceptionCode=0xc0000005, reading address 0x00000138
Registers:
EAX=0x00000000, EBX=0x00000000, ECX=0x0000002b, EDX=0x05f1dcbc
ESP=0x0840fa24, EBP=0x0840fa3c, ESI=0x030888a0, EDI=0x7c8097e0
EIP=0x3dba2a2a, EFLAGS=0x00010246
Top of Stack: (sp=0x0840fa24)
0x0840fa24: 00000000 030888a0 26ac9e88 3dadcbe5
0x0840fa34: 030888a0 00000000 0840fa50 3dad5964
0x0840fa44: 030888a0 05f1d400 00205918 0840fa60
0x0840fa54: 3dbd7a08 030888a0 26ac9e88 0840faac
0x0840fa64: 6d4130be 00205918 06219e27 05f1d510
0x0840fa74: 0840fab4 00205918 00000000 05f1dcd4
0x0840fa84: 05f1dcd4 fffffffe 0840fa8c 26ac9e88
0x0840fa94: 0840fac0 26ad1438 00000000 26ac9e88
Instructions: (pc=0x3dba2a2a)
0x3dba2a1a: d4 9c d2 3d 8b 3d 10 13 a2 3d 8b f1 ff d7 33 db
0x3dba2a2a: 39 98 38 01 00 00 74 1f ff 35 d4 9c d2 3d ff d7
Stack: [0x08310000,0x08410000], sp=0x0840fa24, free space=1022k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C [mshtml.dll+0x182a2a]
C [mshtml.dll+0xb5964]
C [mshtml.dll+0x1b7a08]
C [jp2iexp.dll+0x30be]
V [jvm.dll+0xecf9c]
V [jvm.dll+0x1741e1]
V [jvm.dll+0xed167]
V [jvm.dll+0xed1dd]
V [jvm.dll+0x116290]
V [jvm.dll+0x1d0424]
V [jvm.dll+0x173e5c]
C [MSVCR71.dll+0x9565]
C [kernel32.dll+0xb729]
Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j sun.plugin2.main.server.IExplorerPlugin.iUnknownRelease(J)V+0
--------------- P R O C E S S ---------------
Java Threads: ( => current thread )
0x04644400 JavaThread "Thread-2" [_thread_in_native, id=2772, stack(0x08d40000,0x08e40000)]
=>0x05f1d400 JavaThread "Thread-0" [_thread_in_native, id=2296, stack(0x08310000,0x08410000)]
0x04629800 JavaThread "traceMsgQueueThread" daemon [_thread_blocked, id=4744, stack(0x05df0000,0x05ef0000)]
0x045eac00 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=5344, stack(0x05bf0000,0x05cf0000)]
0x045e4800 JavaThread "CompilerThread0" daemon [_thread_blocked, id=2464, stack(0x05af0000,0x05bf0000)]
0x045e3000 JavaThread "Attach Listener" daemon [_thread_blocked, id=4684, stack(0x059f0000,0x05af0000)]
0x045e1c00 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=2572, stack(0x058f0000,0x059f0000)]
0x045a3000 JavaThread "Finalizer" daemon [_thread_blocked, id=5564, stack(0x057f0000,0x058f0000)]
0x0459e800 JavaThread "Reference Handler" daemon [_thread_blocked, id=3120, stack(0x04780000,0x04880000)]
0x021f8800 JavaThread "main" [_thread_in_native, id=4720, stack(0x01a60000,0x01b60000)]
Other Threads:
0x0459d000 VMThread [stack: 0x04680000,0x04780000] [id=3560]
0x045f4c00 WatcherThread [stack: 0x05cf0000,0x05df0000] [id=976]
VM state:not at safepoint (normal execution)
VM Mutex/Monitor currently owned by a thread: None
Heap
def new generation total 960K, used 154K [0x24ac0000, 0x24bc0000, 0x24d30000)
eden space 896K, 14% used [0x24ac0000, 0x24ae0170, 0x24ba0000)
from space 64K, 40% used [0x24bb0000, 0x24bb68e0, 0x24bc0000)
to space 64K, 0% used [0x24ba0000, 0x24ba0000, 0x24bb0000)
tenured generation total 4096K, used 644K [0x24d30000, 0x25130000, 0x26ac0000)
the space 4096K, 15% used [0x24d30000, 0x24dd12e0, 0x24dd1400, 0x25130000)
compacting perm gen total 12288K, used 1540K [0x26ac0000, 0x276c0000, 0x2aac0000)
the space 12288K, 12% used [0x26ac0000, 0x26c41328, 0x26c41400, 0x276c0000)
ro space 8192K, 63% used [0x2aac0000, 0x2afd9920, 0x2afd9a00, 0x2b2c0000)
rw space 12288K, 53% used [0x2b2c0000, 0x2b934dd0, 0x2b934e00, 0x2bec0000)
Dynamic libraries:
0x00400000 - 0x0049c000 C:\Program Files\Internet Explorer\iexplore.exe
0x7c900000 - 0x7c9b2000 C:\WINDOWS\system32\ntdll.dll
0x7c800000 - 0x7c8f6000 C:\WINDOWS\system32\kernel32.dll
0x6f000000 - 0x6f056000 C:\WINDOWS\SYSTEM32\SYSFER.DLL
0x77dd0000 - 0x77e6b000 C:\WINDOWS\system32\ADVAPI32.dll
0x77e70000 - 0x77f02000 C:\WINDOWS\system32\RPCRT4.dll
0x77fe0000 - 0x77ff1000 C:\WINDOWS\system32\Secur32.dll
0x77f10000 - 0x77f59000 C:\WINDOWS\system32\GDI32.dll
0x7e410000 - 0x7e4a1000 C:\WINDOWS\system32\USER32.dll
0x77c10000 - 0x77c68000 C:\WINDOWS\system32\msvcrt.dll
0x77f60000 - 0x77fd6000 C:\WINDOWS\system32\SHLWAPI.dll
0x7c9c0000 - 0x7d1d7000 C:\WINDOWS\system32\SHELL32.dll
0x774e0000 - 0x7761d000 C:\WINDOWS\system32\ole32.dll
0x78130000 - 0x78257000 C:\WINDOWS\system32\urlmon.dll
0x77120000 - 0x771ab000 C:\WINDOWS\system32\OLEAUT32.dll
0x3dfd0000 - 0x3e015000 C:\WINDOWS\system32\iertutil.dll
0x77c00000 - 0x77c08000 C:\WINDOWS\system32\VERSION.dll
0x76390000 - 0x763ad000 C:\WINDOWS\system32\IMM32.DLL
0x773d0000 - 0x774d3000 C:\WINDOWS\WinSxS\x86_Microsoft.Windows.Common-Controls_6595b64144ccf1df_6.0.2600.5512_x-ww_35d4ce83\comctl32.dll
0x5d090000 - 0x5d12a000 C:\WINDOWS\system32\comctl32.dll
0x3e1c0000 - 0x3e78d000 C:\WINDOWS\system32\IEFRAME.dll
0x76bf0000 - 0x76bfb000 C:\WINDOWS\system32\PSAPI.DLL
0x5ad70000 - 0x5ada8000 C:\WINDOWS\system32\UxTheme.dll
0x74720000 - 0x7476c000 C:\WINDOWS\system32\MSCTF.dll
0x00d40000 - 0x01005000 C:\WINDOWS\system32\xpsp2res.dll
0x755c0000 - 0x755ee000 C:\WINDOWS\system32\msctfime.ime
0x5dff0000 - 0x5e01f000 C:\WINDOWS\system32\IEUI.dll
0x76380000 - 0x76385000 C:\WINDOWS\system32\MSIMG32.dll
0x4ec50000 - 0x4edf6000 C:\WINDOWS\WinSxS\x86_Microsoft.Windows.GdiPlus_6595b64144ccf1df_1.0.2600.5581_x-ww_dfbc4fc4\gdiplus.dll
0x47060000 - 0x47081000 C:\WINDOWS\system32\xmllite.dll
0x77b40000 - 0x77b62000 C:\WINDOWS\system32\apphelp.dll
0x76fd0000 - 0x7704f000 C:\WINDOWS\system32\CLBCATQ.DLL
0x77050000 - 0x77115000 C:\WINDOWS\system32\COMRes.dll
0x746f0000 - 0x7471a000 C:\WINDOWS\System32\msimtf.dll
0x77a20000 - 0x77a74000 C:\WINDOWS\System32\cscui.dll
0x76600000 - 0x7661d000 C:\WINDOWS\System32\CSCDLL.dll
0x77920000 - 0x77a13000 C:\WINDOWS\system32\SETUPAPI.dll
0x325c0000 - 0x325d2000 C:\Program Files\Microsoft Office\OFFICE11\msohev.dll
0x61930000 - 0x6197a000 C:\Program Files\Internet Explorer\ieproxy.dll
0x061f0000 - 0x06205000 C:\WINDOWS\system32\SSSensor.dll
0x7d1e0000 - 0x7d49c000 C:\WINDOWS\system32\msi.dll
0x7e720000 - 0x7e7d0000 C:\WINDOWS\system32\SXS.DLL
0x3d930000 - 0x3da00000 C:\WINDOWS\system32\WININET.dll
0x01840000 - 0x01849000 C:\WINDOWS\system32\Normaliz.dll
0x75cf0000 - 0x75d81000 C:\WINDOWS\system32\MLANG.dll
0x71ab0000 - 0x71ac7000 C:\WINDOWS\system32\ws2_32.dll
0x71aa0000 - 0x71aa8000 C:\WINDOWS\system32\WS2HELP.dll
0x10000000 - 0x10011000 C:\Program Files\Common Files\Adobe\Acrobat\ActiveX\AcroIEHelperShim.dll
0x02250000 - 0x022eb000 C:\WINDOWS\WinSxS\x86_Microsoft.VC80.CRT_1fc8b3b9a1e18e3b_8.0.50727.4053_x-ww_e6967989\MSVCR80.dll
0x7c420000 - 0x7
0x021d0000 - 0x021e0000 C:\Program Files\Common Files\Adobe\Acrobat\ActiveX\AcroIEHelper.dll
0x6d440000 - 0x6d44c000 C:\Program Files\Java\jre6\bin\jp2ssv.dll
0x7c340000 - 0x7c396000 C:\Program Files\Java\jre6\bin\MSVCR71.dll
0x6dae0000 - 0x6daf2000 C:\Program Files\Java\jre6\lib\deploy\jqs\ie\jqs_plugin.dll
0x71a50000 - 0x71a8f000 C:\WINDOWS\system32\mswsock.dll
0x662b0000 - 0x66308000 C:\WINDOWS\system32\hnetcfg.dll
0x71a90000 - 0x71a98000 C:\WINDOWS\System32\wshtcpip.dll76b40000 - 0x76b6d000 C:\WINDOWS\system32\WINMM.dll
0x769c0000 - 0x76a74000 C:\WINDOWS\system32\USERENV.dll
0x71d40000 - 0x71d5b000 C:\WINDOWS\system32\actxprxy.dll
0x77c70000 - 0x77c94000 C:\WINDOWS\system32\msv1_0.dll
0x76d60000 - 0x76d79000 C:\WINDOWS\system32\iphlpapi.dll
0x722b0000 - 0x722b5000 C:\WINDOWS\system32\sensapi.dll
0x76fc0000 - 0x76fc6000 C:\WINDOWS\system32\rasadhlp.dll
0x76f20000 - 0x76f47000 C:\WINDOWS\system32\DNSAPI.dll
0x42b80000 - 0x42b8a000 C:\WINDOWS\system32\jsproxy.dll
0x75c50000 - 0x75ccd000 C:\WINDOWS\system32\jscript.dll
0x76fb0000 - 0x76fb8000 C:\WINDOWS\System32\winrnr.dll
0x76f60000 - 0x76f8c000 C:\WINDOWS\system32\WLDAP32.dll
0x71f80000 - 0x71f84000 C:\WINDOWS\system32\security.dll
0x3da20000 - 0x3dd95000 C:\WINDOWS\system32\mshtml.dll
0x746c0000 - 0x746e9000 C:\WINDOWS\system32\msls31.dll
0x76c30000 - 0x76c5e000 C:\WINDOWS\system32\WINTRUST.dll
0x77a80000 - 0x77b15000 C:\WINDOWS\system32\CRYPT32.dll
0x77b20000 - 0x77b32000 C:\WINDOWS\system32\MSASN1.dll
0x76c90000 - 0x76cb8000 C:\WINDOWS\system32\IMAGEHLP.dll
0x72d20000 - 0x72d29000 C:\WINDOWS\system32\wdmaud.drv72cf0000 - 0x72cf7000 C:\WINDOWS\system32\msadp32.acm
0x74980000 - 0x74a94000 C:\WINDOWS\system32\msxml3.dll
0x1b000000 - 0x1b00c000 C:\WINDOWS\system32\ImgUtil.dll
0x41e30000 - 0x41e3e000 C:\WINDOWS\system32\pngfilt.dll
0x420c0000 - 0x420f9000 C:\WINDOWS\system32\Dxtrans.dll
0x76b20000 - 0x76b31000 C:\WINDOWS\system32\ATL.DLL
0x6d430000 - 0x6d43a000 C:\WINDOWS\System32\ddrawex.dll
0x73760000 - 0x737ab000 C:\WINDOWS\System32\DDRAW.dll
0x73bc0000 - 0x73bc6000 C:\WINDOWS\System32\DCIMAN32.dll
0x42010000 - 0x42067000 C:\WINDOWS\system32\Dxtmsft.dll
0x68000000 - 0x68036000 C:\WINDOWS\system32\rsaenh.dll
0x42b90000 - 0x42c07000 C:\WINDOWS\system32\mshtmled.dll
0x767f0000 - 0x76817000 C:\WINDOWS\system32\schannel.dll
0x68100000 - 0x68126000 C:\WINDOWS\system32\dssenh.dll
0x58760000 - 0x58792000 C:\WINDOWS\system32\iepeers.dll
0x73000000 - 0x73026000 C:\WINDOWS\system32\WINSPOOL.DRV
0x6d410000 - 0x6d42c000 C:\Program Files\Java\jre6\bin\jp2iexp.dll
0x71ad0000 - 0x71ad9000 C:\WINDOWS\system32\wsock32.dll
0x6d800000 - 0x6da8b000 C:\PROGRA~1\Java\jre6\bin\client\jvm.dll
0x6d7b0000 - 0x6d7bc000 C:\PROGRA~1\Java\jre6\bin\verify.dll
0x6d330000 - 0x6d34f000 C:\PROGRA~1\Java\jre6\bin\java.dll
0x6d290000 - 0x6d298000 C:\PROGRA~1\Java\jre6\bin\hpi.dll
0x6d7f0000 - 0x6d7ff000 C:\PROGRA~1\Java\jre6\bin\zip.dll
0x02770000 - 0x02776000 C:\Program Files\Java\jre6\bin\jp2native.dll
0x6d1d0000 - 0x6d1e3000 C:\Program Files\Java\jre6\bin\deploy.dll
0x6d610000 - 0x6d623000 C:\Program Files\Java\jre6\bin\net.dll
0x6d630000 - 0x6d639000 C:\Program Files\Java\jre6\bin\nio.dll
0x6d6b0000 - 0x6d6f3000 C:\Program Files\Java\jre6\bin\regutils.dll
0x6d000000 - 0x6d14a000 C:\Program Files\Java\jre6\bin\awt.dll
VM Arguments:
jvm_args: -Xbootclasspath/a:C:\PROGRA~1\Java\jre6\lib\deploy.jar;C:\PROGRA~1\Java\jre6\lib\javaws.jar;C:\PROGRA~1\Java\jre6\lib\plugin.jar -Xmx32m -Djava.awt.headless=true -Dkernel.background.download=false -Dkernel.download.dialog=false -XX:MaxDirectMemorySize=64m
java_command:
Launcher Type: generic
Environment Variables:
PATH=C:\Program Files\Internet Explorer;;C:\orant\bin;c:\oracle\ora90\bin;C:\Program Files\Oracle\jre\1.1.8\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;c:\informix\bin;C:\Program Files\Credant\Shield v5.4.2\;"C:\Program Files\Common Files\EMC";C:\Program Files\Windows Imaging\
USERNAME=wmcdowel
OS=Windows_NT
PROCESSOR_IDENTIFIER=x86 Family 15 Model 4 Stepping 1, GenuineIntel
--------------- S Y S T E M ---------------
OS: Windows XP Build 2600 Service Pack 3
CPU:total 1 (1 cores per cpu, 2 threads per core) family 15 model 4 stepping 1, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ht
Memory: 4k page, physical 1039808k(23272k free), swap 2503148k(877736k free)
vm_info: Java HotSpot(TM) Client VM (14.2-b01) for windows-x86 JRE (1.6.0_16-b01), built on Jul 31 2009 11:26:58 by "java_re" with MS VC++ 7.1
time: Wed Nov 04 08:54:53 2009
elapsed time: 1865 seconds
Posted by Michelle DiGaetano on November 13, 2009 at 12:21 AM PST #
Hello, Michelle,
I'm glad to hear that you've migrated your EBS users over to the JRE client. I'm sorry that you're encountering problems, though. I'd like to help you get to the bottom of these issues quickly.
First, have you checked out the troubleshooting guide linked in this article?
Updated Tips for Debugging Sun JRE + Forms Focus Issues for EBS 11i and 12 -
If you've gone through those troubleshooting steps and are still having problems, November 13, 2009 at 06:22 AM PST #
Hi Rajeev,
We are currently testing with the lastest JRE 6.17 version in an attempt to resolve the BooleanUtils.class not found issue. So far so good.
Regards,
Lindsey
Posted by Lindsey on November 18, 2009 at 04:37 PM PST #
I guess I am in the right place. I share the same pain with everyone else is experiencing. We have migrated from Jinitiator 1.3.1.18 to JRE 1.6.0_17 and experiencing forms losing focus with Oracle EBS (11.5.10.2). The issue happens sporatically and we are unable to recreate it at will. We have reapplied the following patch 8717874. We have also regen the forms with the parameter force 'Y'. I am no further along in finding a solution and I am afraid my users are getting little vulgar with their language towards me. I have opened a Service Request with Oracle Support but it is just going back and forth. Does anyone have any ideas I can sure use some help in resolving this issue.
Posted by Richard on December 07, 2009 at 12:54 PM PST #
Hi, Richard,
I'm sorry to hear that you're having trouble following your JRE migration from JInitiator. Have you checked out the latest troubleshooting guide for mouse focus issues? It's referenced here:
Troubleshooting Mouse Focus Issues Using JRE Clients with EBS 11i
We've found that the vast majority of focus issues are resolved by following the steps in that Note. If you've applied all of the patches listed there and still have issues, please send me your SR number so that I can have someone in Development work with the Support engineer assigned to your SR.
Regards,
Steven
Posted by Steven Chan on December 08, 2009 at 01:59 AM PST #
Hi Steven
I'm having problems accessing, Note 761159.1 (for generic JInitiator desupport date) - is this a URL you can send me or a PDF or do I need to have access?
I just needed the note.
Cheers
StevenOoi
Posted by S.Ooi on December 10, 2009 at 02:02 PM PST #
We are using jinitiator 1.3.1.29. We are noticing, some client PCs [around 5 %], gets IE browser errors, IE crashings. Is it due to IE or firefox or windows problems?
Posted by Sandip Bose on December 11, 2009 at 03:23 AM PST #
Hi, StevenOoi,
I just checked Note 761159.1 -- it seems to be accessible via My Oracle Support (formerly Metalink). Are you having issues because you don't have an account for My Oracle Support?
If so, I'm afraid that Notes are available only to My Oracle Support subscribers. I'm not permitted to distribute those to non-subscribers.
It's a pretty short Note, though. It simply states that Error Correction Support (ECS) for generic JInitiator users on Windows will end as of 31-JAN-2010, and Extended Support (ES) will end as of 31-JAN-2013.
Regards,
Steven
Posted by Steven Chan on December 11, 2009 at 05:42 AM PST #
Hi, Sandip,
Sorry to hear that you're having trouble with the JRE migration. Have you gone through the latest JRE mouse focus troubleshooting guide linked from this article?
Updated Tips for Debugging Sun JRE + Forms Focus Issues for EBS 11i and 12
If you've gone through that and are still having problems with focus issues, 11, 2009 at 05:59 AM PST #
Hi Gurus,
We have custom Oracle forms application and after upgrading to SUN JRE 1.6.0_16 we started getting Row lis locked by another user issue in forms.When we switch back to Jinitiator this problem doesn't exist(code remains same).
Thanks,
Suresh
Posted by Suresh on February 25, 2010 at 01:46 AM PST #
Hi, Suresh,
Given that you're encountering an issue with a custom Forms application, I suspect that there might be some coding standards at the root cause of this. Your best bet would be to log a formal Service Request via My Oracle Support (formerly Metalink) to get an Oracle Forms specialist engaged.
Regards,
Steven
Posted by Steven Chan on February 25, 2010 at 02:15 AM PST #
Hi Steven,
Recently, we migrated to Sun JRE 1.6.0.17, Since then often having issues with IE 6.0 crashes suddenly . Referring "mshtml.dll" in the log generated. Some times users are panic when it happens. Please suggest whether this issue is addressed in the later version of JRE.
Thanks
Srini
Posted by Srini on June 18, 2010 at 12:59 AM PDT #
Hi, Srini,
Without knowing the root causes of the crashes that you're experiencing, I can't comment on whether that will recur with later releases. I would recommend upgrading to the latest JRE on a testbed desktop to see whether you can replicate your issue there. See this recent article:
JRE 1.6.0_20 Build 5 Fixes E-Business Suite Compatibility Issues
Regards,
Steven
Posted by Steven Chan on June 18, 2010 at 02:56 AM PDT #
What are the problems will be occured while migrating application from jdk 1.4 to jdk 1.6?
What are the steps needs to follow to avoid those errors?
What info should be kept in mind while migrating jdk 1.4 to jdk 1.6?
Posted by abhishek on July 26, 2010 at 07:50 PM PDT #
Abhishek,
You've referred explicitly to the JDK -- not the JRE, although you're commenting on a JRE-related article. Remember, these are two different things. The JDK resides on your EBS application tier server, and the JRE resides on your Windows desktop clients that access your E-Business Suite environment.
Assuming that you know what you're doing here, you can find complete JDK upgrade instructions for your EBS application tier linked off this article:
Java SE 6 Certified With Release 11i
If you've inadvertently confused the JRE with the JDK, you can find instructions for upgrading your JRE clients in the Note linked from the article above.
Regards,
Steven
Posted by Steven Chan on July 27, 2010 at 04:22 AM PDT #
Hi Steven,
Just wanted to get this out to you. We've migrated most of our users to the latest Sun JRE 1.6.0_20 update 5 (we waited because we also run Discoverer and wanted to use a common version for both).
One thing that we have noticed is frequent forms crashes and slowness in the forms, even though the load on the server has remained the same. We also have some thin client users accessing 11i forms over RDP and they experienced slowness as well.
The solution to the forms crashes and performance problem was to add this runtime parameter on the client side in the Java control panel applet:
-Dsun.java2d.noddraw=true
We also had done this on our older Jinitiator clients, but I didn't think we would need to do it with the newer JRE. Once we put that in it stops the intermittent forms crashes and the forms perform much better.
As always, test it out, but I just wanted to get this out there to others who may be experiencing some problems with the newer JRE.
Thanks,
Mark
Posted by Mark Coleman on September 03, 2010 at 05:04 AM PDT #
Hi, Mark,
Thanks for sharing this tip. Can you provide me with your Service Request number where this was investigated and replicated by Oracle Support? I'd like to review their analysis and see whether this has been formally reported as a bug to the Sun JRE team (or the Forms team).
Regards,
Steven
Posted by Steven Chan on September 03, 2010 at 05:21 AM PDT #
Hi Steven,
Unfortunately I didn't raise an SR for this. We've been using that parameter since JInitiator 1.3.1.18 to increase the performance of the forms interface through RDP (Remote Desktop Protocol) sessions. At that time we experienced issues with poor performance (forms slow to drag, slow data population) on thin clients connecting to a terminal server via RDP. I found the -D setting in a discussion on increasing java applet graphics performance. I thought I would give it a shot in Jinitiator and it made all the slow dragging and slow data population errors disappear.
When we began moving to the JRE 1.6 I thought we could leave that parameter behind, but right after deployment my users began complaining of forms crashes and poor forms performance, particularly in order entry when tabbing into the unit price field. Adding the -D parameter fixed the crashing and jacked up the forms performance again. This time though we weren't using RDP sessions, they were native sessions on desktop client machines, not thin clients.
I'll be glad to provide you any test data or test cases I can if necessary.
Thanks,
Mark
Posted by Mark Coleman on September 10, 2010 at 11:18 AM PDT #
Hi, Mark,
In rereading this thread, I realized that this is a workaround that you've come up with for your thin clients accessing EBS over RDP. It all comes clear now.
As you probably know, our official position is that we certify and support only Windows and Mac desktops accessing the E-Business Suite, so we don't have the infrastructure to validate this and update our official documentation accordingly.
I'm glad that you've been able to find a workaround for your thin clients. Thanks for sharing this tip with our readers. These kinds of insights are priceless for customers operating in slightly nonstandard environments, and it's great that we have a forum to share your experiences here.
Regards,
Steven
Posted by Steven Chan on September 14, 2010 at 03:35 AM PDT #
Hi Steven,
We found the parameter originally to help our thin client display performance, but we have been using it on both thin clients and Windows desktops since Jinitiator 1.3.1.18 to improve display performance and avoid forms crashing issues. When we moved to the JRE 1.6 I thought we could leave it behind, but the parameter solves several forms crash issues on the Windows desktops, so we put it back in on both.
You're correct in that originally it was for thin clients, which you guys don't officially support, but we are now using it on thin clients and Windows desktops with good results.
Just wanted to clarify, not trying to beat a dead horse! Thanks to you and all the good people at Oracle who put out this info!
Thanks,
Mark
Posted by Mark Coleman on September 15, 2010 at 11:05 AM PDT #
Hi Steven,
We are a little bit late, but now we want to change from JInitiator to JRE.
Current config: Oracle EBS 11.5.10.2 and JInitiator 1.3.1.25.
Our clients are spread all over the world and only partially controlled by us.
Currently we believe that we have not the ability to migrate all users/clients of an EBS instance at a big bang without problems. Introducing a new JRE will impact older Java applications.
Our idea is to configure our EBS to support JRE and JInit in parallel for a limited time. The intention is to support a fallback to JInitiator for clients with JRE problems to have some time to solve those issues without a fallback for all users.
We are running such a config in a test environment but Oracle does not recommend this for production.
It seems that all other customers switched all users of one EBS instance to JRE at a single blow or?
Is a step wise recommended migration strategy known by you?
Any customer experience?
Regards,
Gustav
Posted by Gustav Classen on September 16, 2010 at 11:28 PM PDT #
Hi, Gustav,
I haven't spoken to many customers about this directly. I would be very surprised if very large organizations (e.g. those with tens of thousands of EBS users) could switch over in a big bang conversion, though. I suspect that those organizations took a staged approach that allowed both JInitiator and JRE to run side-by-side.
For details about that approach, see Note 290807.1, Appendix B, "Multiple Client Java Plug-In Versions."
Good luck with your migration.
Regards,
Steven
Posted by Steven Chan on September 17, 2010 at 12:39 AM PDT #
Hi Steven,
We are planing to upgrade JDK of our EBS 11.5.10.2 configured with SSl, i would like to know if there are any precautions need to be taken before upgrading the JDK which will not impact SSL configuration.
Posted by guest on August 03, 2011 at 06:32 PM PDT #
Hi, Guest,
Upgrading your server-side JDK shouldn't affect your SSL configuration. You can refer to Note 300482.1 for pointers to EBS server-side JDK upgrade guides.
Regards,
Steven
Posted by Steven Chan on August 04, 2011 at 02:40 AM PDT #
We have migrated from oracle application server to Weblogic (10.3.2), forms (11g).
Some of the users are not able to access some part front end screen, no error message just hourglass. They have same jre like other users who are able to access application successfully.
Please advise how we can fix this issue.
Posted by vks on July 14, 2012 at 11:57 PM PDT #
Hello, VKS,
I'm sorry to hear that you've encountered an issue with this. It sounds like you're reporting an issue with a custom application and not Oracle E-Business Suite. This blog is for Oracle E-Business Suite topics, so we don't have much advice for generic issues like the one you're reporting.
Your best bet would be to log a formal Service Request via My Oracle Support (formerly Metalink) to get one of our Forms specialists engaged.
Regards,
Steven
Posted by Steven Chan on July 16, 2012 at 08:08 AM PDT # | https://blogs.oracle.com/stevenChan/entry/reminder_migrate_your_jundefinediator_clients_to_sun_jre_now | CC-MAIN-2016-36 | refinedweb | 6,123 | 66.64 |
In this beginner tutorial I will show you how to use Python programming language to write a simple command line app for sending emails via Gmail!
You will only need 11 lines of code!
Step 1: Download Python
Download Python 3.6.0 from
Step 2: Install Python & Add to Path
Open up the python installer you just downloads.
Click install, but make sure to check the checkboxes that say "Add Python to PATH" and "Install Pip"
Step 3: Install SMTPLib
- Open up your computer's command prompt.
On my Windows PC, this is done by going to Start, then typing in "CMD", clicking the "CMD" app to open it up.
2. In the command prompt, type in:
pip install smtplib
Then hit enter.
It will then install the library needed to connect Gmail to Python.
Step 4: Configure Gmail
- While logged into your gmail at gmail.com, go to
- Scroll down to the part that says "Allow less secure apps"
- Turn ON "allow less secure apps".
If you don't want to make your main gmail less secure, or if you don't already have gmail, then sign up for a new gmail solely for this purpose.
Step 5: Download the Python Script
Download the attached gmailpython.py file to a location on your computer that is easy to remember.
Or, simply copy the identical code below and paste it into your favorite text editor, then save it as "gmailpython.py" with UTF-8 encoding:
import smtplib gmailaddress = input("what is your gmail address? \n ") gmailpassword = input("what is the password for that email address? \n ") mailto = input("what email address do you want to send your message to? \n ") msg = input("What is your message? \n ") mailServer = smtplib.SMTP('smtp.gmail.com' , 587) mailServer.starttls() mailServer.login(gmailaddress , gmailpassword) mailServer.sendmail(gmailaddress, mailto , msg) print(" \n Sent!") mailServer.quit()
Step 6: Run the Script!
Open up command prompt the same way you did earlier.
type in cd ____
with the path to gmailpython.py replacing the blank line.
For example, on my laptop the command is
cd c:\users\donovan\downloads
Hit enter, then type in
py gmailpython.py
And hit enter again.
The command line app will now load, and it will prompt you for the your login details, your message, and who you want to send the message to!
Step 7: How It Works
import smtplib
That line above loads to smtplib library, which adds gmail integration to python.
gmailaddress = input("what is your gmail address? \n ") gmailpassword = input("what is the password for that email address? \n ") mailto = input("what email address do you want to send your message to? \n ") msg = input("What is your message? \n ")
These lines display a prompt for input, and store your answers in variables named "gmailaddress", "gmailpassword", "mailto", and "msg". Think of variables as nicknames for your input.
The "/n" tells the script to display a new line before the next command.
mailServer = smtplib.SMTP('smtp.gmail.com' , 587) mailServer.starttls()
The part above sets up the connection to the gmail mail server.
mailServer.login(gmailaddress , gmailpassword)
That part logs Python in to your Gmail account, taking the info from the variables that store your previous answers.
mailServer.sendmail(gmailaddress, mailto , msg)
That part sends the email message using the info from the variables that store your info.
print(" \n Sent!")
That part replies "Sent!" in the command line so you can know the code made it to that point.
Note: In Python 2.7, you don't need the parentheses around the quotes. We are using Python 3.6, which does require parentheses.
mailServer.quit()
The final part quits the connection to the mail server.
Step 8: That's All!
I hope this was interesting and educational to you. | http://www.instructables.com/id/Send-Email-Using-Python/ | CC-MAIN-2017-22 | refinedweb | 632 | 76.72 |
Introduction
Web services through deployment of Service Oriented Architectures (SOA) is increasingly more common. An SOA is several Web services working together for a common goal, and the new PHP SCA extension has been developed to lower the barrier for PHP developers to develop easily maintained Web services. You see, before PHP SCA came along, Web services development in PHP was more difficult, having no solid WSDL service support. In other enterprise languages, like the Java™ language, there are numerous methods for creating Web services, and thanks to the PHP SCA SDO extensions, better Web services support has been brought to PHP developers.
The PHP SDO module allows you to handle data in PHP in such a way that code is agnostic to the source of the data, be it flat XML data or a relational database. This helps keep your code neat and simple, and also allows you to change the source from which you ultimately pull data from for your application. Thus, data is created using an SDO, automatically translated to XML during transit to the Web service, recreated into another SDO on the receiving end for you to conveniently read and manipulate in your Web service, and vice versa with the client.
Using the PHP SCA extension, you'll learn in this article how to create a weather Web service, while using the PHP SDO extension to handle and incorporate data into your Web application. The Web service will take hardcoded data from a client you create and the weather service will return hardcoded data. You'll also see how to extract auto-generated WSDL from the Web service you create, and test your Web service using the client.
Installing the PHP SDO/SCA extensions
In order to use the PHP SDO and SCA extensions, you're going to have to install them using the pecl command line tool. Go to your PHP directory (c:\apps\wamp\php in the author's case), and type (for Windows® systems using Wamp Server 1.7.1a -- a for Apache version):
pecl install -B SCA_SDO.
The
-B flag stands for nobuild, essentially telling pecl not to build the C extensions. In UNIX®/Linux® systems, you need to leave off the
-B flag:
pecl install SCA_SDO.
For Windows users, you need to get the latest php_sdo.dll from pecl4win.php.net (if your build came with a php_sdo.dll file, it may be outdated and not work). If you're running Wamp Server 1.7.1a, then grab the one for php-5.2.1, and place it in your php/ext directory. Lastly, add the following line to your php.ini file:
extension=php_sdo.dll.
For UNIX/Linux users, pecl built the sdo library for you, sdo.so. Add it as an extension to your php.ini file as follows:
extension=sdo.so.
An finally, make sure the include path containing your php and php/PEAR directories are in the include_path directive in your php.ini file, so that when you include the appropriate SCA files later in the article the PHP processor will know where to look for the libraries. The contents of the author's are shown here:
include_path = ".;c:\apps\wamp\php\includes;c:\apps\wamp\php;C:\apps\wamp\php\PEAR".
Both the PHP SCA and SDO extensions should now be installed on your system. Note that the PHP SCA module is marked as experimental and may change without notice in a future release of PHP.
Moving on, you'll begin development of the Web service.
Developing a Web service PHP class
Now you get to build a class that will comprise the Web service. This article will show off the features of PHP's SCA and SDO extensions using a simple, hardcoded weather service. You'll use an SDO to send which areas you wish to send to the weather service to return temperatures on. The Web service will then print out the areas received, and then use an SDO to return pairs of areas and associated temperatures. First, you'll lay down the infrastructure for the
Weatherservice class.
The weather service
First, you're going to create a class with a function, and then later you'll define and annotate it. Begin with the class definition in Listing 1.
Listing 1. The
WeatherService class
<?php class WeatherService { function getTemperature($Areas) { } } ?>
Here you have the
WeatherService class and a function,
getTemperature, that gets the areas that users wish to retrieve the temperatures of passed into it as a parameter. You'll define the function next.
Using SDOs
SDOs are objects that allow you to easily handle XML data without needing to know from where it came. Define the function, as shown in Listing 2.
Listing 2. Defining the
getTemperature function
<?php class WeatherService { function getTemperature($Areas) { echo "Area list received from client:<br>"; foreach($Areas->area as $area) echo $area->state . "<br>"; echo "<br>"; $Temperatures = SCA::createDataObject('', 'Temperatures'); $Pair = $Temperatures->createDataObject('entry'); $Pair->state = 'CA'; $Pair->temperature = 65; $Pair = $Temperatures->createDataObject('entry'); $Pair->state = 'UT'; $Pair->temperature = 105; $Pair = $Temperatures->createDataObject('entry'); $Pair->state = 'ND'; $Pair->temperature = -20; return $Temperatures; } } ?>
In Listing 2 you see the areas come into the function and get printed out. You'll learn more about the schema of both the areas and temperatures data structures later. For now, just notice how each is being accessed, and also how the
$Temperatures object is created. Adding an entry to the list of temperatures simply requires that a new object be created, automatically adding it as a child to the parent. The state and temperature are then variables of each of the three new objects that you create.
Next, annotate the class with PHP annotations, effectively giving the PHP SCA extension details about this new Web service.
Adding PHP annotations
The PHP annotations are essential to completing the Web service, and are what communicates to the PHP SCA module that this class is indeed a Web service. See how the annotations are done in Listing 3.
Listing 3. Annotating the Web service class
<?php include "SCA/SCA.php"; /** * @service * @binding.soap * * @types AreasTypes.xsd * @types TemperaturesTypes.xsd */ class WeatherService { /** * @param Areas $Areas * @return Temperatures */ function getTemperature($Areas) { echo "Area list received from client:<br>"; ... return $Temperatures; } } ?>
The most important annotation is the first one,
@service, which designates this class as a Web service. The
@binding.soap annotation tells PHP SCA to use SOAP bindings for the Web service. The next two are
@types annotations, which bring in the Areas and Temperatures data structures you already used in the
getTemperature method of the Web service. These annotations basically tell PHP SCA where to get the schemas for the two SDO data structures you wish to use. The
@param annotation on the function specifies the type of the parameter passed in, and
$Areas is of type
Areas with namespace (the
Areas type is then matched to the
Areas type referenced in the
@types annotation). The
@return does the same thing as the
@param annotation, except that it specifies that the parameter is the return value. Note that you must also include "SCA/SCA.php." Doing so causes the PHP SCA module to recognize the class and its annotations as a Web service.
In the next section you'll define the schemas, as referenced in the
@types annotations.
Defining schemas
Now that the Web service is completely defined, you're going to define the two schemas referenced in Listing 3, beginning with the Areas schema.
Areas schema
You should remember this data structure the $Areas variable used in Listing 2. The schema, shown in Listing 4, tells PHP SCA SDO the inner parts to this variable and how to use it in an SDO.
Listing 4: The
Areas schema
<xs:schema xmlns: <xs:complexType <xs:sequence> <xs:element </xs:sequence> </xs:complexType> <xs:element <xs:complexType> <xs:sequence> <xs:element </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
See how the namespace also matches up with the namespace in the corresponding
@types annotation in Listing 3. The top-level element,
Areas, can contain an unbounded series of areas of type
StateType, essentially a string. And if you remember from Listing 2, that's exactly the structure being used: Iterating over a list of area, and displaying its state to the screen. Next you'll define the
Temperatures schema.
Temperatures schema
The
Temperatures data structure also was used in Listing 2 and Listing 3, and the concepts of it greatly mirror that of the previous
Areas schema. Take a look at it in Listing 5.
Listing 5. The
Temperatures schema
<xs:schema xmlns: >
See how the namespace also matches that shown in the corresponding
@types annotation in Listing 3. You should also recognize the structure and how you constructed a new
Temperatures data type in Listing 2. Remember, you first created a $Temperatures variable, and created three children elements: entry, and set the state and temperature variables, respectively.
In developing the client you'll see how to construct an
Areas data type, and display the
Temperatures data type to the browser.
Developing a client
Now all you need is a client to test it out! A simple client will do, which is what you'll learn how to code here, and how to send and receive your request in SDOs.
Creating the request
Creating the request is nearly the opposite of what you did in the Web service where you dismantled the request and created a response. In the next couple of sections you'll create a request and then dismantle the response. See how the request is created in Listing 6.
Listing 6. Creating the request
<?php include "SCA/SCA.php"; $weather = SCA::getService('WeatherService.php'); $Areas = $weather->createDataObject('', 'Areas'); $area = $Areas->createDataObject('area'); $area->state = 'CA'; $area = $Areas->createDataObject('area'); $area->state = 'UT'; $area = $Areas->createDataObject('area'); $area->state = 'ND'; ...
Again, as you did in the Web service, include SCA/SCA.php. Note how easy it is to create the Web service. You've created it in a single line of code, with the call to
SCA::getService. Note that here you've created a local Web service as the Web service is a local PHP file. See Resources for more information on other ways to create Web services, including remote ones. Moving on, you create the request, the $Areas SDO, and add three states to it: CA, UT and ND.
Next you'll send and process the request.
Sending and receiving the request
After creating the request, you can go ahead and pass it to the Web service, as shown in Listing 7.
Listing 7. Sending and receiving the request
... $Temperatures = $weather->getTemperature($Areas); echo "Received temperatures from Web service:<br>"; foreach($Temperatures->entry as $Pair) echo $Pair->state . ": " . $Pair->temperature . "<br>"; ?>
Here the request is made, and the response is stored in
$Temperatures (the same object you constructed in the Web service back in Listing 2). Lastly, you dismantle the response and display it to the user, except this time instead of just displaying the state you have two variables to display, the state and the associated temperature.
That does it. Next you'll verify that everything works!
Deploy and test
It is now time for testing. There's nothing special when it comes to deploying this slick PHP Web service. In fact, it's already up and running as long as your Web server's running, as you'll see next.
Viewing created WSDL
See the WSDL for yourself by pulling up a browser, and entering (on the author's system):.
You'll then see the WSDL of your Web service (see Listing 8), without even creating WSDL in the first place.
Listing 8. Auto-generated WSDL
<definitions targetNamespace=""> <types> <xs:schema <xs:import > </types> <message name="getTemperatureRequest"> <part name="getTemperatureRequest" element="tns2:getTemperature"/> </message> <message name="getTemperatureResponse"> <part name="return" element="tns2:getTemperatureResponse"/> </message> <portType name="WeatherServicePortType"> <operation name="getTemperature"> <input message="tns2:getTemperatureRequest"/> <output message="tns2:getTemperatureResponse"/> </operation> </portType> <binding name="WeatherServiceBinding" type="tns2:WeatherServicePortType"> <operation name="getTemperature"> > <service name="WeatherServiceService"> <port name="WeatherServicePort" binding="tns2:WeatherServiceBinding"> <tns3:address xsi: </port> </service> </definitions> <!-- this line identifies this file as WSDL generated by SCA for PHP. Do not remove -->
You can feed this WSDL into other Web services generators for other languages, such as Java, or for another one of your PHP Web services that comprise your deployed SOA. Notice the two import statements in Listing 8. These lines import the two schemas that you specified in the
@types annotations in the
WeatherService class back in Listing 3, into the above defined WSDL (see Listing 8). The rest of the first block of lines in bold font are the wrapper data types for the request and response,
getTemperature and
getTemperatureResponse, respectively. And the last line to note is the
location attribute of the
address element that specifies the location of the Web service, exactly where you pulled the WSDL from.
Next you'll run the client, and see what comes of it!
Sending and receiving the request
All right, you should be a PHP SCA SDO pro by now. This may be a little tricky at first, but once you get a feel for it, it's simple, and you may wonder why you'd need any other language for your SOA deployment needs ever again.
OK, open up a browser to the client (), and take a look at the results in Figure 1.
Figure 1. Results of running the client
It worked! In your client code you sent CA, UT, and ND, and successfully received and displayed them in the server code. You then also sent CA, UT, and ND with 65, 105, and -20 as the temperatures, respectively, as a response from the Web service, and successfully displayed the correct values back in the client.
Excellent! You're finished. Now you can brag to all your friends about how easy it is for you to create Web services.
Summary
If you're a hardcore PHP developer you've probably never seen a Web service created like that before. It's like the ease of Web services Java developers are familiar with has finally come to PHP, and it's a great thing. In this article, you:
- Successfully installed the PHP SCA and SDO extensions
- Created and annotated a Web service class
- Created a simple client, and were successful at testing your new Web service
- Successfully used and incorporated an SDO into your client and Web service
Download
Resources
Learn
- Learn more about the PHP SCA extension and its functions straight from the source -- php.net.
- Go to php.net to learn more about the PHP SDO extension and accompanying functions.
- See what IBM PHP bloggers have to say about the release of the PHP SCA module with links to more information.
- Read a good introductory article on PHP SCA and SDO.
- Visit the Apache Tuscany home page, the code behind the PHP SCA and SDO extensions, to learn more about the SCA and SDO.
- Check out this news release where IBM touts support for Apache Tuscany, a project started to simplify SOA development.
- For all your SOA and Web services needs, visit IBM developerWorks SOA and Web services zone.
- Read New to SOA and Web services to get the lowdown on what exactly SOA is and how it fits into the Web services world.
Get products and technologies
- Download the PHP SCA and SDO extensions straight from pecl.php.net.
Discuss
- Participate in the discussion forum.
Dig deeper into Web development on developerWorks
- Overview
- New to Web development
- Technical library (articles and more)
- Forums
- Open source projects
- Events
developerWorks Labs
Experiment with new directions in software development.
JazzHub
Everything you need to build great software. Click. Code. Create.
IBM evaluation software
Download software trials; experiment in a sandbox or in the cloud. | http://www.ibm.com/developerworks/webservices/library/ws-soa-scasdo/ | CC-MAIN-2015-27 | refinedweb | 2,643 | 54.12 |
Sun's posted the Java XML Pack Winter 01 Release. This bundles together the:
I've tried the latest Mozilla 0.9.7 on both Windows and the Mac. The Windows build fixes the one bug I had noticed in 0.9.6 (a minor problem involving saearch pop-up menus in the location bar). It also lets me configure cookie preferences to exclude them from sites with bad privacy policies, though perhaps that was in earlier versions and I just noticed it now. Windows Mozilla definitely feels ready for prime time.
I wish I could say the same about the Mac version though.
It's noticeably slower than IE5.0 for the Mac, and it crashed my systems within minutes of launch. Furthermore, it still has some annoying problems with AppleScript that prevent me from using it as my default browser. In particular, it cannot tell which window is in front.
get the front window returns the first window opened, not the window that is currently in front.
The Mozilla Project has posted version 0.97 of the Mozilla web browser for the usual batch of platforms. New features include basic S/MIME support, favicon support, and a Document Inspector that provides live editing of the DOM of any web document or XUL application.
Antenna House has released version 2.0 of their XSL Formatter, a Windows GUI program for viewing and printing XSL formatting objects documents. The major new features are compatibility with the final XSL 1.0 recommendation and the ability to generate PDF documents from XSL-FO documents.
XSL Formatter costs roughly $2000 for your first copy, significantly less for each additional copy. I have to say that this strikes me as vastly overpriced. For $80, the cost of an additional license, I would have bought a copy to play around with. For $400, I would have downloaded the evaluation version, checked it out, and if it seemed to work on my documents I would have bought a copy. But for $2000, I'll continue to use FOP and PassiveTeX.
I've returned to New York and my backups. Cafe au Lait and Cafe con Leche should be fully functional again.
Norm Walsh has published version 2.0.3 of DocBook: The Definitive Guide. DocBook is an XML application for technical documentation used in the Linux Documentation Project, my own Processing XML with Java, and of course the DocBook book itself. This is a minor update.
Merry Christmas, Bon Noel, Feliz Navidad, Happy Holidays,
a Festive Kwanzaa, Joyeuse Fetes,
Season's Greetings, Happy Hanukkah, a joyous Winter Solstice
and all that. I have a small present for everyone today.
Chapter 9 of
Processing XML with Java has been posted.
This chapter begins the coverage of the Document Object Model (DOM)
by discussing its underlying data model and the
Node and
NodeList interfaces.
I hope you like it. :-)
As usual, many W3C working groups have pushed out a lot of new and revised working drafts in the week before Christmas. I don't have time to analyze them all now, but if you're interested the latest are:
I may say more about some of these when I return to New York.
Yes, I know a runaway cron job replaced the December news with news from the same date last December. Possibly a crontab file I'd deleted got accidentally restored in a backup. Much more likely, I stupidly forgot to delete the old crontab file in the first place. Mea culpa. Mea maxima culpa.
I do have a copy of the old December news that got overwritten. Unfortunately, the old news is sitting in my Brooklyn apartment two thousand miles away from my parents' house in New Orleans where I'm spending the holidays, and for once I did not make complete copies of my web sites on my laptop. I tried, but Aladdin's StuffIt Deluxe crapped out when it was trying to make the necessary zip files, so I didn't get that done. I probably (no, make that definitely) should have figured out what the problem was and brought a backup with me; but I stupidly figured I could just download it off the web and didn't want to waste the extra time.
I do have a recent copy of the site on DLT tape with me in case my apartment building goes up in flames while I'm away, but unless I can find someone friendly in New Orleans with Retrospect and a DLT drive, that isn't any immediate help. There are mirror sites, but they haven't been updating since IBiblio switched to Linux and broke the mirror logins months ago. :-(
The short version is that news from the last week or two is temporarily lost in the ether. It will come back shortly before New Year's. I will still be posting new news here during the meantime. Thanks to everyone who wrote in to warn me of the problem.
The W3C XSLT Working Group has posted the first public working drafts of XSLT 2.0 and XPath 2.0. The big new feature in these releases is schema-type awareness, but there's lots more here too including improved grouping, an XHTML output method, integer and single precision arithemtic, number formatting that does not depend on Java, and way too much to talk about right before I fly to New Orleans tomorrow for the holidays. <BlatantPlug>If you want to know more about this come here me talk about it on Monday, March 11, at XMLOne London.</BlatantPlug> by which point I should have had enough time to digest the spec and decide what I think of it.
Michael Kay, the editor of the XSLT 2.0 spec, has posted the first release of Saxon 7.0, an experimental and incomplete implementation of these XSLT 2.0 and XPath 2.0 working drafts. Production use should continue to rely on XSLT 1.0/XPath 1.0/Saxon 6.5.
Microsoft's released Internet Explorer 5.1 for MacOS 8 and 9. This release makes numerous bug fixes and improvements in CSS support. Particularly notable is the ability to apply CSS style sheets to XML documents (a feature the Windows version of IE has had for several years.) Other new features include the ability to drag and drop arbitrary images and hyperlinks to the button bar.
The W3C has published four new and revised working drafts about SOAP 1.2 including for the first time a SOAP primer:
The SOAP 1.2 namespace is now and will almost certainly chnge again before the final release. The MIME type has changed from text/xml to application/soap+xml to finally application/soap (which I really don't understand the logic behind. It is still XML after all.) The SOAP schemas are now compliant with the final release of the W3C XML Schema Language. Finally, the spec now denies that SOAP is an acronym for "Simple Object Access Protocol" or anything else.
According to several people
TypeOf is a reasonable equivalent to
instanceof in Visual Basic.
Thanks to Philip Nelson, Robert A. Casola, and Rob Smith for helping out with this.
The revised question is what languages don't have a reasonable equivalent to
instanceof? So far the only ones I've found are JavaScript 1.3 and earlier and some older C++ compilers pre-RTTI. Are there any other lanaguages out there to which the DOM IDL could theoretically be compiled, but which do not have some variant of
instanceof?
Brendon McKenna showed me where to look for an equivalent of
instanceof in Perl. Short answer: it doesn't have one.
Long answer, the
ref() function
lets you check a variable's immediate class through string comparison, but not the variable's various superclasses. Update: The
isa() function will correctly compare against superclasses
even if
ref() won't.
Now I need to ask the same question for
Visual Basic. Does it have any reasonable equivalent of Java's
instanceof operator or any means determining at runtime the type of an unknown object? Please send any answers to
elharo@ibiblio.org. Thanks!
The XML Apache Project has posted the fourth beta of Xerces-J 2.0. They claim this release is "near production quality." Beta 4 fixes a number of bugs, introduces more changes to the Xerces Native Interface, provides a partial experimental DOM Level 3 implementation, and includes full XML Schema support including Post Schema Validation Infoset information.
For the next chapter of
Processing XML with Java,
I'm trying to find out if Perl has any reasonable equivalent of Java's
instanceof operator or any means determining at runtime the type of an unknown object. Please send any answers to
elharo@ibiblio.org. Thanks!
A number of XML specifications define application-specific document object models that extend the standard DOM. These include WML, SVG, HTML, SMIL, and MathML. For the next chapter of Processing XML with Java, I'm looking for parsers that can build these application specific DOMs. So far I've found that the Docuverse DOM SDK can build an HTML DOM and with some effort Xerces can be made to build HTML and WML DOMs. Does anybody know of any others? I'm particularly interested in a parser that could build a MathML or SVG DOM. Please send any suggestion to elharo@ibiblio.org. Thanks!
Simon St. Laurent's published the first alpha version of Markup Object Events (MOE), a Mozilla-licensed Java class library that supports markup processing using both events and object trees. Accorsing to St. Laurent, "MOE programs can work purely with events, purely with trees, or with combinations of both, effectively providing a "middle way" between SAX and DOM." MOE permits all nodes to have:
My initial impression is that this goes a long way toward reinventing DOM, in a slightly more concrete and Java-centric fashion, with perhaps the one major change that nodes do not have to belong to a document, but can live independently. However, MOE's
CoreComponentI really feels to me exactly like DOM's
Node interface, even to the point of using integer constants to represent node types.
VMTools 0.4 is an open source Java library for comparing and representing the differences between XML documents. It's similar to diff and patch for ASCII text, but is aware of significant and insignificant XML structure.
The W3C XML Core Working Group has just published a very poorly thought-out initial working draft of XML 1.1. This basically just describes the changes that will be necessary to satisfy the very controversial XML Blueberry requirements. There's one big change since the Blueberry requirements were published: C0 controls except for null (e.g. bell, vertical tab, formfeed, etc.) will now be allowed in XML documents. For the life of me I can't figure out what this is supposed to gain anybody.
The restrictions on name characters will be loosened considerably in XML 1.1, so that all Unicode characters which are not specifically forbidden as name characters can now be used in element, attribute, entity and notation names. This will allow native script markup in Ge'ez, Amharic, Tigre, Burmese, Cambodian, and a few other languages, as well as filling a few very minor holes in Chinese and Japanese support. However, the proposal goes way beyond this. Many undefined code points are now allowed in names, as are some very weird characters like ©, ±, 7 (&0x2077;, superscript 7), the musical symbol for a six-string fretboard, and the zero-width space.
With perhaps one exception, the working group ignored or rejected every single proposal that was made to reduce the massive damage this will do to interoperability. To summarize:
The version number will now be 1.1 instead of 1.0. Even though most of the changes in this draft have little to no effect on the vast majority of users, I expect to be hearing from publishers and readers within 24 hours about when I'll be releasing The XML 1.1 Bible, XML 1.1 in a Nutshell, etc. These titles aren't actually necessary, but I'm sure myself and other authors will waste a few acres of trees on them nonetheless.
Many documents will be published with a 1.1 version even though they do not need to be. Existing systems that attempt to process these documents will fail. Consequently, many organizations will be faced with large and unnecessary expenditures to upgrade software in order to support features most users don't actually need.
IBM will now be allowed to use non-ASCII characters as white space. This will make their lazy programmers happy because they still don't have to conform to the standards the rest of world has been happily using for over two decades. However, the rest of us will now have to deal with IBM generated XML that cannot be edited in a simple text editor and cannot be processed with our existing tools.
The W3C HyperText Coordination Group has published a note about the requirements for a Component Extension (CX) API. To quote, from the
From the early days of the World Wide Web, Web Agents had been extended to support more types of contents. The recent developments of XML and the possibility to mix multiple.
Altova has released XML Spy 4.2 Suite, a $399 payware XML editor for Windows. Upgrades from 4.0 are free. XML Spy 4.2 Suite consists of three products: XML Spy 4.2 Document Editor, XML Spy 4.2 XSLT Designer, and XML Spy 4.2 Integrated Development Environment. Version 4.2 adds SOAP support through WSDL, Oracle XML Schema Extensions, MSXML4 Support, various XSLT Designer editing enhancements, extended Document Editor APIs, and various other improvements. Version 4.0 was unusable. I'm going to test this version and see if it's any better.
Update: 4.2 is a definite improvement on 4.0. It no longer hangs for several minutes when trying to open my test documents (Docbook documents for various chapters of Processing XML with Java) so it's no longer completely non-functional. Thus now I have a real chance to actually evaluate the product and its design.
After opening my test documents, it was far from obvious how to work with them. I could browse them in a tree view fairly easily, and it wasn't too hard to add a new element declared in the DTD or a new text node. However, I could not figure out how to do something as simple as delete a word from the middle of a sentence in an existing text node. There may be a way to do this, but it wasn't obvious at first glance. It certainly wasn't as simple as selecting the word I wanted to delete and pressing the delete key.
I also found the tree view to be a very unnatural way to edit the sorts of document I write. I much prefer writing in a basic text editor like UltraEdit or BBEdit, even if it means I have to type the tags myself. Christian Gross showed me a more word processor like view of the document at Software Development in Boston last August, but it's not the default view and I wasn't able to figure out how to turn it on. I suppose I should probably read the manual.
Update 2: I found the text view that let's me edit the document more naturally by typing words in a row interspersed with tags. This is moderately useful. I loved the code-completion pop-ups for tag names. Unfortunately, depending on how you're typing in the tags, this has an annoying tendency to delete the following word if there's no white space between the tag and the following word. :-( The more word processor like document view apparently requires me to create a custom configuration file in the XSLT designer. I'm not quite sure how to do that since the XSLT designer doesn't have the customary File/New menu item, and the XSLT designer can't seem to open any of my files (DTDs, XSLT stylesheets, or instance documents). I should probably read the manual again.
Update 3: OK the online help showed me what I needed. I didn't have to resort to the manual (I'm assuming there is a manual somewhere. I haven't actually looked for it yet. :-)) Apparently, the XSLT designer should work by opening a DTD or a W3C XML Schema Language schema; and indeed I was able to get it to work with simple examples from the XML Bible. However, it simple could not handle the much more complicated real-world DocBook DTD. Consequently, this means I can't use XMLSpy to edit my books just yet. :-(
Unicode 3.2 beta data files have been posted. Version 3.2 adds 1016 new characters, new properties, additional conformance clauses, and various textual clarifications. New scripts include Tagalog, Hanunoo, Buhid, Tagbanwa, a large collection of mathematical symbols, and small sets of other letters and symbols.
The W3C HTML Activity has posted a new working draft of XForms 1.0. release are too numerous to list here, but are nicely summarized in an appendix.
The W3C/IETF URI working group has published a new working draft of Internationalized Resource Identifiers (IRI). An IRI uses Unicode to locate resources in a syntax very similar to that of URIs, and a hex-encoded mapping from IRIs to URIs is defined. However, an IRI is not a kind of URI and could not be directly used in XML documents in places where URIs are now required (e.g. system identifiers).
WH2FO is an open source Java application that processes an HTML document saved from Word 2000, and transforms it into an XML document and an XSLT stylesheet. The XSLT stylesheet can then transform the XML document into an XSL-Formatting Objects document. You can also apply a stylesheet that converts the XML back into HTML discarding all the extra markup added by Word.
PXDB is a simple Python application that takes XML files and places them into a SQL database. There are APIs for querying / altering / deleting / ordering / linking. PXDB is like a middle ground between SQL database and XML repository. One can view PXDB as a strange object database on top of SQL storage, with some elements of XML (CPath). This is a very rough alpha right now.
Netscape's released version 6.2.1 of their namesake web browser that supports XML, CSS, and XSLT. This is the first release with full native support for MacOS X. Versions are also available for Windows, classic MacOS, and various Unixes. Otherwise, it's not clear what if anything changed. It still seems based on the Mozilla code 0.9.4 code base.
The W3C XML Schema test collection has been updated with some new tests contributed by Sunt. Updated test output from both XSV and MSV/Crimson have also been posted.
The W3C DOM and HTML working groups have posted a last call working draft of Document Object Model (DOM) Level 2 HTML Specification Version 1.0. Comments are due by January 7.
The Apache XML Project has released Xerces-C++ 1.6.0, an open source XML parser that supports SAX2 and DOM2, written in reasonably portable C++. The bug news for this release is full support for the W3C XML Schema Language (modulo bugs). Also included is a FreeBSD port and many bug fixes, memory leak fixes and performance improvements.
The Apache XML Project has released version 1.1 of Batik, an open source SVG browser and class library written in Java. This release improves performance and conformance. Newly implemented features include xml:base, improved text support, improved conditional processing support and complete CSS support. Scripting and SMIL animation are not yet supported.
Apparently the xml-dev mailing list was hacked recently, and the subscriber list was deleted. It's not clear when the list will be back to normal. Even though the problem has allegedly been fixed, I for one am still not receiving any mail from the list, even though the subscription manager tells me I'm subscribed. Update: I've just started receiving mail from the list. If you still aren't getting anything, try unsubscribing and resubscribing.
Design Science, Inc. has released the WebEQ Developers Suite, a $495 payware Java toolkit for building Web pages that include dynamic math via MathML. The WebEQ Developers Suite includes five components: the Editor for authoring "presentation" and "content" MathML; the Publisher for processing HTML pages with MathML and WebTeX; the Input Control which functions as a graphical equation editor in a Web page; the Equation Server which works behind the scenes to facilitate batch processing and processing via scripts on a server; and the Viewer Control that displays MathML in any browser.
Yann Dirson's posted the first public beta of sgml2x, a bash script for formatting SGML and XML documents using DSSSL stylesheets. sgml2x requires jade and jadetex, and you'll need docbook (sgml or xml), and docbook-dsssl to make immediate use of it. It was developed as a bash script, and should run on any platform where bash runs.
The NetBeans XML team has posted the first preview release of the NetBeans TAX library. As near as I can tell, this is a Java bean that "allows structure manipulation of whole XML and DTD documents" inside the NetBeans open source Integrated Development Environment (IDE). TAX "includes event, traversal and I/O support." TAX requires a specially patched version of Xerces 2 from NetBeans.
Amelia A. Lewis noticed that the xml-dev mailing list appears to have been down since the weekend, and I verified that with a recnet message of my own. If any of the maintainers are reading this, could you please look into the problem and let us know what's happening? Thanks.
IBM's alphaWorks has released ToXgene, a "template-based generator for complex, semantically-correlated collections of XML documents. The data generation process in ToXgene is based on a conceptual description of the data to be generated (the templates). This tool is intended for cases in which the structure of the data to be generated is known, the data is required to conform to that structure, and multiple collections of documents, with varying structures, sizes and complexities, can easily be generated." In other words, it automatically produces lots of sample documents for an XML application.
XPathTester is an open source Java2 based tool for visualizing the results of XPath queries. "Type in a query, hit enter, see the resulting value displayed or nodeset highlighted in the tree."
The W3C XSL Working Group has decided to open the XSL-editors mailing list to the general public "in order to exchange views on the XSLT language and its development. In order to keep traffic to a reasonable level, it is strongly discouraged to ask general questions about the use of XSLT, which pertain to xsl-list. The moderator reserves the right to unsubscribe people who will post off-topic messages." To subscribe send em-amil to xsl-editors-request@w3c.org from the address you wish to subscribe.
I've posted the first draft of SAX Filters, Chapter 8 of Processing XML with Java here on Cafe con Leche.
This chapter covers the
XMLFilter interface and the
XMLFilterImpl and
AttributesImpl classes.
This chapter demonstrates how to write filters that modify the stream of events that flows between an XML parser and a client application.
This is a longish chapter, and some of the examples are a bit on the large side. I'm curious to know whether you think they make sense, or whether they're too long to follow. On the flip side, in several examples I've limited myself to only one class of several or even a single method, rather than including the entire set of classes needed to do something useful. I need to know if these are still comprehensible. As usual all comments are appreciated.
This is the last tutorial chapter on SAX. There'll be one more reference chapter later on. However, right now the first eight chapters form a very solid introductory text about processing XML with SAX2. If anybody notices any important topics in that domain that haven't been covered yet, I'd appreciate hearing about it. The next chapter will begin the coverage of DOM.
IBM's alphaWorks has released the Reengineering Tool Kit for Java, a tool for converting Java source code into XML documents. The XML documents aren't compilable, but they should be much easier to integrate into documentation. In fact, I may take a stab at using this to generate some of the reference appendices for Processing XML with Java. Java 1.3 or later is required. The license is unclear, but the download is free. Update: Anjan Bacchu reports that the license is non-commercial, evaluation only and will expire in 90 days.
Cafe con Leche is now available at. This is exactly the same site as, just at a different, hopefully easier to remember URL. Both URLs will be live for the foreseeable future.
IBM's Martin Presler-Marshall has published The Platform for Privacy Preferences 1.0 Deployment Guide as an unendorsed W3C Note.
David Brownell's posted the third beta of SAX2, release 2.
Release 2 is a planned bug fix release that corrects some errors in implementation classes like
AttributesImpl and cleans up the JavaDoc considerably.
In particular, many methods that had unspecified behaviors are now specified.
However, it does not change the API at all.
The first beta of DocBook 4.2 has been posted. DocBook is an XML application for technical documentation such as computer books and manuals. I'm writing my next book, Processing XML with Java, in DocBook from start to finish. "This is a backwards-compatible release that incorporates a large number of bug fixes and feature requests."
The DocBook Technical Committee has also posted version 0.1 of the XML Character Entities, a set of DTD modules that provide the entity references for numerous useful non-ASCII characters. These were rpeviously bindled with DocBook, but should now be more useful for other applications as well. These references are one of the standard parts of SGML that got cut from XML. They include:
Adobe's posted a Linux beta of their SVG Viewer browser plug-in.
David Megginson's posted the first beta of the NewsML Toolkit 1.1, an open source Java library for reading and processing NewsML documents. NewsML 1.0 is a news-industry packaging and metadata standard for exchanging multi-part news and information in multiple media using XML. Version 1.1 "is an extensive rewrite of version 1.0 released last spring: it includes full XPath support, high-level support for formal names and basis-for-choice selection, and an extensible conformance test library. Over 300 unit tests are included." The NewsML Toolkit is published under the LGPL.
The XML Apache Project has released Cocoon 2.0, an open source server side XML framework that supports XSLT and XInclude. Version 2.0 "is a complete rewrite of the first generation that removes all of those design constraints that emerged during almost three years of worldwide use."
Alex Selkirk's updated his XML Schema Toolkit to version 0.12. This is a closed source tool which can convert XML schemas to Visual C++ code.
Opera Software has released the Opera 6.0 web browser for Windows. Among many other features Opera boasts native support for XML and pretty good support for CSS Level 2. The most important new feature in this release is much better support for Unicode. A Linux beta is also available. Opera is $39.95 payware or free-beer adware (Your choice).
Mark Szpakowski clued me in that the bottom of the Tasks menu in Mozilla lists active windows. Thanks! I hadn't thought to look there.
I've installed Mozilla 0.9.6 on both my Mac and my Windows box. My initial impressions are positive. This is an incremental improvement, but not a major step forward. I haven't done speed tests myself, but most people I've heard from say that this release is a lot faster than Netscape 6.2 and somewhat fatser than earlier releases of Mozilla.
Stylesheet wise, the CSS support still needs some work. In particular, CSS tables don't seem to work with XML documents. XSLT support does seem much improved. In particular, for the first time I was able to load both XML documents and XSLT style sheets from the local file system.
Applescript support is somewhat improved. Opening URLs in new windows works again. However, Mozilla still can't figure out which window is in front, so I'm continuing to use Internet Explorer on my Mac. The lack of a Window menu is also a major shortcoming since I tend to start my day by automatically opening a dozen or so windows on diferent news sites, and like to navigate between them.
Mozilla 0.9.6 has been released for Windows, Linux, Solaris, OpenVMS, and MacOS. New features include print preview, support for .BMP and .ICO images on all platforms, and a "Search for" item on the context menu.
As has been the case for the last several releases, Mozilla includes full support for XML and CSS (and of course HTML). XSLT support is there too, but it's been quite buggy through 0.9.5, and probably still is. Don't be too surprised if you can't get this working. If you want to try, make sure you load both the XML documents and the XSLT stylesheets from a web server, not the local file system, and that the server assigns both the XML documents and the XSLT stylesheets the MIME media type text/xml.
If you want something smaller than Mozilla, check out Galeon 1.0, a recently released Mozilla-based Web browser for Gnome/Linux that throws away the mail reader, news reader, chat client, and other extraneous fluff.
The Gnu Classpath Extension Project has posted the first beta of GNU JAXP 1.0. This includes the Ælfred XML parser and supports SAX2, DOM2, and the Java API for XML Processing 1.1 (JAXP). The SAX support fixes a number of bugs that are present in most other parsers. GNU JAXP is licensed under the terms of the GNU General Public License, with the "library exception" which permits its use as a library in conjunction with non-Free software.
Sebastian Rahtz has updated PassiveTeX, his XSL-Formatting Objects to TeX converter, to support the XSL 1.0 recommendation from the W3C. The changes from the proposed recommendation to the final recommendation of XSL 1.0 are fairly minor and easy to fix (essentially one key attribute was renamed), but do affect almost everyone who uses XSL-FO.
Wizen Software has released PowerXML Pro 2.1, a payware "dynamic data-integration platform supporting information exchange...between XML and non-XML data sources. Sources include files, databases, applications, web-sites, mainframes, and web-services. PowerXML is based on industry standard XML, XSLT, and XPath technologies." This is a standalone desktop program for visually building and executing dynamic data pipelines. Pipelines can be used to combine, filter, transform, and map data between various data sources and formats. The idea's interesting, but their web site just showed white pages on my Mac. Frankly, I'd be very hesitant to trust XML solutions to a company that hasn't even mastered HTML yet.
Pricing is not published, a fairly standard scam which different companies practice for different purposes. Some vendors like to leave pricing unspecified so they can see how much they can milk out of customers, and not leave anything on the table. Other vendors do have standard pricing, but like to make you invest a lot of time listening to their sales pitch before they'll tell you what their product actually costs. That way they figure you'll be more invested in the product and less likely to rule it out immediately because it's overpriced. It's not clear which technique is in effect here. Windows, NT/2000/XP, Linux, and Solaris are supported.
From the better late than never department, I noticed that the W3C XML encryption working group last month published last call working drafts of XML Encryption Syntax and Processing and Decryption Transform for XML Signature.
Republica Corp. has submitted a note to the W3C on the DEL Data Extraction Language. According to the submission, ." It's not clear if the W3C will do anything with this, but it looks interesting.
The W3C Voice Browser Activity has published the first public working draft of Semantic Interpretation for Speech Recognition. According to the abstract, ."
The W3C/IETF XML Digital Signature Working Group has posted a first and last call working draft of Exclusive XML Canonicalization 1.0. Comments are due by December 11. Accordign to the abstract, ."
Late Night Software's released XMLTools 2.3.2, an expat-based XML parser for AppleScript. This version deliberately breaks compatiblity with other XML parsers by allowing extra white space before the XML declaration. I recommend you do not upgrade.
Late Night Software's also released version 1.0d8 of an XML-RPC library for Classic MacOS systems.
I installed Xerces-J 1.4.4 yesterday, and I'm not thrilled with it to say the least. This release
did not fix several major, well-known bugs with SAX support.
XMLReaderFactory.createXMLReader() still fails to correctly load the Xerces
SAXParser class, and the
AttributesImpl class is out of date and has at least one nasty bug in
addAttribute() that the current SAX distribution has fixed.
(I haven't reported this one yet because I can't quite put my finger on the line of code that's ine rror; but I have proved to my satisfaction
that swapping the current SAX
AttributesImpl class for the Xerces
AttributesImpl class does fix the problem.)
Worse yet, the DOM code reintroduces a bug in
cloneNode() (inability to clone documents) that had been fixed in Xerces-J 1.4.0.
Among other things, this breaks my
DOMXIncluder. I've downgraded to Xerces-J 1.4.3 for the moment.
The NetBeans XML team has posted the the second Alpha release of the NetBeans XML modules family. NetBeans is a modular Integrated Development Environment (IDE) written in Java. Features include:
NetBeans 3.3 beta 3 or later is required.
The W3C RDF Core Working Group has published a new working draft RDF Test Cases which describes "a set of machine-processable test cases corresponding to technical issues addressed by the WG."
Sun's released the Java XML Pack, an all-in-one bundle of various Java technologies for XML. This release (Fall 2001) includes the Java API for XML Processing (JAXP), the Crimson XML parser 1.1.3, the Xalan XSLT processor, and the Java API for XML Messaging (JAXM).
Sun's also posted the final release of the JAXM 1.0 Specification. JAXM is a Java API for SOAP clients and servers.
Finally, Sun's posted the second public review draft of the Java API for XML Registries (JAXR) specification. JAXR "provides a uniform and standard Java API for accessing different kinds of XML Registries. An XML registry is an enabling infrastructure for building, deploying, and discovering web services."
The Xerces-J team of the XML Apache Project has released version 1.4.4 of Xerces-J, an open source, schema validating XML parser written in Java. Xerces-J supports SAX2, DOM2, and JAXP. This is a bug fix release. All users should upgrade.
The W3C has published a candidate recommendation of Selectors (formerly CSS Selectors). ." There are a lot of new features here relative to CSS2, most importantly for XML namespace based selectors. Much of this material is discussed in Chapter 17 of the XML Bible, Gold Edition. The Candidate Recommendation Phase ends May, 2002.
Waterloo Maple has released version 7.0 of the Maple symbolic mathematics package. New features include TCP/IP, MathML 2.0, and "substantial increases in the depth and breadth of solution algorithms in key areas such as differential equations and numerical computation. It continues to lead with greater integration of key technology from the Numerical Algorithms Group (NAG) and other respected sources". Maple is $1695 payware and available on Windows and Linux.
Allin Cottrell has published dbtexmath, a set of Perl and DSSSL files that enables "literal pass-through of TeX math to jadetex, in the context of DocBook"; that is, it lets you use TeX math rather than MathML in the SGML/XML source file. This includes a utility to auto-generate PNG images for use in HTML.
Michael Kay's released version 6.5 of his open source SAXON XSLT processor written in Java.
This is my current XSLT processor of choice.
This release fixes a few bugs,
allows you to run SAXON in a secure mode where Java extension functions are disabled, and requires setting
version="1.1"
to enable XSLT 1.1 features such as
xsl:document,
xsl:script, and
the ability to refer to a result tree fragment as it it were a node-set.
The XML:DB API is an attempt to bring an ODBC or JDBC style access API to native XML databases. The API is intended to be language independent, but most early work has been done in Java. The reference implementation is basically a very simple file system based native XML database and is an easy way to get familiar with the API. Full source code is available under an Apache style license. Included with the reference implementation are some Java driver development tools, including a set of base driver classes and an early release of a test suite. Java implementations of the XML:DB API exist for dbXML and eXist and are under development for Ozone.
Opera Software ASA has posted the first beta of version 6.0 of their namesake Opera web browser for Windows. Version 6.0 focuses on prettifying the user interface including a single document interface. It also offers an option to turn off pop-up windows. Opera has suported direct display of XML and CSS since version 4.0. Opera is $39 payware or free-beer ad-ware (your choice). Upgrades from version 5.0 are free.
IBM's updated the XML Toolkit for z/OS and OS/390 with improved XML parsing capabilities including namespace, JAXP, and schema support. The LotusXSL XSL Transformations (XSLT) processor has also been added to this release.:
The Apache Cocoon team has posted the second release candidate of Apache Cocoon 2, a "complete rewrite of the Cocoon XML publishing framework that is supposed to remove all those design constraints that emerged from the Cocoon 1 experience."
Paul Prescod and ActiveState have launched the XSLT Cookbook. The idea is to get people to contribute "recipes" that other people could then take and use in their programs. In the case of the XSLT Cookbook, we are of course talking about XSLT snippets to be used in stylesheets and transformations.
XSmiles 0.45, an open source XML browser written in Java, has been posted. Some support is included for XML Parsing, XSLT Transforms, SMIL 2.0 Basic, XForms, XSL Formatting Objects, SVG, XML Events, ECMAScript, skins, and SIP Videoconferencing. This is still very much a work in progress, but is interesting nonetheless. The very different approach to XML browsing compared to converted HTML browsers like Mozilla is very suggestive.
Peter Flynn's XML FAQ has been translated into Amharic. The FAQ is presented in different document formats including HTML, PDF, and Postscript. You will need an Ethiopic Unicode font such as Jiret to read the HTML (UTF-8) format.
The Netbeans XML team has posted the first alpha of the XML modules for NetBeans, an open source integrated development environment (IDE). NetBeans 3.3 Beta 3 or later is required. Features include an XML text editor with syntax coloring and code completion, an XML tree editor, validation.
SSAX is a purely functional, semi-validating SAX/DOM/SXML parser/library written entirely in a pure-functional subset of Scheme. SSAX consists of a DOM/SXML parser, a SAX parser, and a supporting library of lexing and parsing procedures. A SSAX parser is a full-featured, algorithmically optimal, pure-functional parser, which can act as a stream processor. Scheme. The complete source code as well as benchmarks and examples have been placed in the public domain.
The dbXML project has posted what they hope is the final beta release of the dbXML Core XML database, an open source, native XML database designed to manage large collections of small XML documents. The server supports XPath queries and provides an implementation of the XML:DB XML Database API for development of client applications. The source code has been released under an Apache style open source license. Changes in this release are minor and revolve around bug fixes for enhanced stability and scalability. Interoperation with other software, in particular servlet engines such as Tomcat 4.0, has also been improved.
Adobe has released version 10 of Adobe Illustrator, a $399 payware drawing program that exports and, new in version 10, imports Scalable Vector Graphics pictures. Other new features include native support for MacOS X, vector and raster-based slicing, symbols for repeating graphics, drawing tools for lines, arcs, grids and polar grids, a flare tool for reflections and lens effects, a magic wand tool and much more. Upgrades are $149.
Version 1.0 of the XSLT Standard Library, an open source (LGPL) collection of commonly-used templates written purely in XSLT, has been released. Currently the library includes templates for manipulating various kinds of text content including dates, strings, and URIs.
The W3C DOM Activity has released three new and updated Document Object Model Working drafts:
XPathEvaluator, which should give you the rough flavor of this API:
package org.w3c.dom.xpath; public interface XPathEvaluator { public XPathExpression createExpression(String expression, XPathNSResolver resolver) throws XPathException, DOMException; public XPathResult createResult(); public XPathNSResolver createNSResolver(Node nodeResolver); public XPathResult evaluate(String expression, Node contextNode, XPathNSResolver resolver, short type, XPathResult result) throws XPathException, DOMException; }
The first part of this working draft defines how schemas in a variety of schema languages including DTDs and the W3C XML Schema Language can be represented in DOM. This is a fairly major update. Among other changes, it adds datatype constants representing all of the W3C XML Schema Language predefined primitive data types. Unfortunately the API does not feel rich enough to support user-defined data types. I'm also concerned that the API only make this information available from the schema model and not from the document model. That is, given an element declaration you can ask what type it has; but you can't ask the same question of an element instance.
The second part of this working draft defines how a program locates a parser, creates new
Document objects, and serializes documents onto streams.
James Clark's Jing is a Jing a validator for RELAX NG implemented in Java on top of SAX2. The latest release adds support for pluggable datatype libraries using the vendor-independent RELAX NG datatype library interface from the relaxng project at SourceForge.
James Clark's DTDinst is a Java program that converts XML DTDs to XML instance format,.
Daisuke Okajima's RelaxNGCC 0.4 is a GPL'd tool that generates Java source code from a RelaxNG grammar.
Jasc Software has posted the fifth preview release of WebDraw, a native SVG authoring program for Windows. Major new features and enhancements in Preview Release 5 include:
Mike Brown's released the Pretty XML Tree Viewer, an XSLT stylesheet that produces an HTML+CSS1 representation of an XML document's XPath/XSLT node structure.
Daniel Veillard has released libxml2 2.4.7 and libxslt 1.0.6, the Gnome XML and XSLT libraries. Among other things, they provide the xsltproc command. These are mostly bug fix releases.
Alexandr Korlyukov has written a Lambda-calculus interpreter in XSLT. The practical use of this is minimal, but this does constitute a proof that XSLT is Turing complete.
The W3C has released the official XML Infoset Recommendation. There do not appear to be any substantive changes since the proposed recommendation. This started out as a standard data model for all XML specifications, but got demoted to nothing more than a standard vocabulary for talking about XML. It gives names for the different parts of an XML do (most of which already had names in XML 1.0 anyway). There's not a lot of practical information here. The Infoset doesn't let you do anything you couldn't do before now. A few other specs such as XInclude are likely to be defined in terms of Infoset transformations instead of text document transformations, but that's about it.
The W3C has released version 5.2 of the Amaya web browser for Unix and Windows. Amaya supports HTML 4.01, XHTML 1.0, XHTML Basic, XHTML 1.1, HTTP 1.1, MathML 2.0, much of CSS Level 2, and some parts of SVG. It also includes an annotation application based on XPointer and RDF. It's not quite clear from the online documentation, but it looks probable that this release might add support for XML documents with CSS style sheets. I'm downloading it now to test that out. Update: XML files with attached CSS style sheets can be displayed directly in the browser. However, there are definitely some holes in CSS support.
In many ways, Amaya is a very nice browser/editor. However, the W3C mostly sees this as a test project, not as a serious end-user tool to compete with the likes of IE, Opera, and Mozilla. Consequently, the user interface is ugly, and extremely quirky and non-standard. I don't know how development on Amaya normally proceeds, but it might be worth somebody's time to do some work on the user interface, forking the project if necessary.:
Design Science has released MathType 5.0 for Windows, a $129 payware equation editor plug-in for Microsoft Word. One of its major new features is the ability to convert Microsoft Word documents containing equations into HTML with embedded MathML presentation markup. The equations can also be output as GIF images, if you prefer. A 30-day demo is available.
The XML Apache Project has released release Xerces C++ 1.5.2, an XML parser written in C++ for Windows and various Unixes. The big new feature of this release is a broader subset of XML schema support. There's also support for progressive parsing in SAX2, project files for Borland C++ Builder 5, various bug fixes and performance improvements.
Microsoft's posted a new beta of their MSXML 4.0 parser which they've renamed "Microsoft XML Core Services". This release is allegedly faster and much more standards compliant. However, there've been some disturbing reports that this parser (or perhaps the installer associated with it) disables some versions Microsoft Office. Consequently I recommend that you do not upgrade or install this. Microsoft has been informed of the problem, and may have a fix by the time you read this.
Bare Bones Software has released version 6.5 of BBEdit, the Macintosh programmer's editor I use to write this site. This release adds CSS support, an automatic language "guessing" feature to determine proper syntax coloring for tags, WML syntax checking, a new Perl compatible GREP engine, and various improvements in MacOS X. However, they don't mention any fix for what is in my opinion the biggest single hole in the current BBEdit: the inability to recognize Unicode text documents. BBEdit is $119 payware. Upgrades are $39, and cross-grades are $79.
Sun's Kohsuke Kawaguchi has released the RELAX NG Converter, a Java program that can convert schemas in a variety of languages including DTD, RELAX Core/Namespace, TREX and W3C XML Schema into RELAX NG schemas.
IBM's alphaWorks has released the IBM XSL Formatting Objects Composer (XFC). XFC is a Java program that "implements a substantial portion of XSL Formatting Objects (FO)" It can produce either an interactive on-screen display using Java2D, or an output file using PDF.
Sun's Kohsuke Kawaguchi has written the XML Instance Generator, a Java program that reads a schema file and produces valid documents. You can also produce invalid documents, too. DTD, RELAX NG, RELAX Core/Namespace, TREX and W3C XML Schema are supported.
David Brownell's posted a beta of SAX 2.0.1. This is a bug fix release, and most of the bugs fixed are in the documentation.
The W3C HTML Working Group has published the fourth public working draft of XML Events, a means of integrating event listeners and handlers with the Document Object Model (DOM) Level 2 event interfaces [DOM2].
I've posted SAX, Chapter 6 of Processing XML with Java,
here on Cafe con Leche. This chapter provides in-depth coverage of the
ContentHandler interface, and discusses some common usage patterns for SAX.
As always,
all comments are appreciated. Just email them to me at elharo@ibiblio.org.
I have two questions in particular about this chapter.
First, is the sidebar on SAX in other languages (Python, Perl, C++) accurate?
I don't use these languages routinely, so it's entirely possible I've misrepresented the actual status of SAX in these environments.
Secondly, is SAXSpider, my example of the
Attributes interface, too complex for an example at this level? Would a simpler example (say verifying all the URLs in an XHTML or RDDL document) make a better example of the
Attributes interface?
Eric S. Raymond has written doclifter, a Python program for converting legacy troff documents to DocBook."
Sun has posted a Schematron add-on for their multi-schema validator. It validates validate XML documents against RELAX NG schemas annotated with Schematron schemas.
Cisco Systems has submitted Java Specification Request 155 (JSR-155), Web Services Security Assertions to the Java Community Process. The goal is to "provide a set of APIs, exchange patterns & implementations to securely (integrity and confidentiality) exchange assertions between web services based on OASIS SAML." Assertions could include credentials, authentication, authorization, and sessions; and are based on top of XML digital signatures.
IBM's alphaWorks has updated three of its XML tools to fix some bugs in an underlying library and improve Unix support. The updated programs are:
I don't think there's any new functionality in any of these.
The W3C has released the 1.0 Recommendation of XSL Formatting Objects (XSL-FO). XSL-FO is a page description language like PostScript written as an XML application. The normal use scenario is that you write an XSLT stylesheet that transforms an input XML document into an XSL-FO document. The XSL-FO document describes how content should be styled, laid out, and paginated. You would then convert the XSL-FO document into a more convenient format such as PDF, PostScript. or TeX, from whence it could be viewed or printed on paper.
The spec lists the following changes.
The XML Protocol Working Group is seeking contributions to the SOAP Version 1.2 Test Collection. The tests are intended to prove (or perhaps disprove) that SOAP 1.2 meets its goal for conformance requirements, and that implementations exist for each of its features.
XInclude.net (whoever that is) has published a GPL'd XInclude implementation for the Microsoft XML Parser. At first glance, it looks roughly equivalent to my XInclude processor for Java; i.e. it can include complete documents but not parts thereof because it does not support XPointer. There are some conformance bugs in the XInclude.net program, but they're not too large.
The problems I noted with the Macintosh version of Mozilla on Friday (complete failure to display almost all Web pages) appear to have been a conflict with Steve Falkenburg's WebFree, a shareware control panel that filters ads. Disabling it restored Mozilla, and also fixed some problems I had selecting text in Netscape 4.7. Furthermore, Netscape used to fall apart once I opened more than a dozen or so simultaneous windows, and it hasn't done that since I turned off WebFree.
WebFree hasn't been updated in four years. I certainly hope it will get an update soon. Since I started using it, it's blocked over 10,000 ads. When I turned it off I was amazed at how ugly and annoying a lot of my favorite web sites suddenly became. Still, if WebFree is destabilizing my system, then it's got to go. It's time to start looking for alternative ad blocking software. Fortunately Mozilla itself now can block pop-up windows, though not yet inline ads.
I'm happy to note that the W3C has decided to continue work on its new patent policy rather than rushing to a premature conclusion. A second public Last Call for the W3C Patent Policy Framework is planned. Very importantly, free software luminaries Eben Moglen and Bruce Perens are joining the Patent Policy Working Group (PPWG) as invited experts.
The XML Apache Project has posted a release candidate of FOP 0.20.2, an open source XSL-FO to PDF converter.
Version 0.9.5 of the open source Mozilla Web browser has been released for the usual batch of platforms (Windows, Linux, MacOS, Solaris, etc.) New features in this release include:
The History and Mail & News applications now allow you to reorder columns with drag and drop.
Warnings in the JavaScript console now show the text of the offending line.
Venkman, the JavaScript Debugger is now available in complete installer builds.
A new experimental Tabbed Browsing feature. Press Ctrl+T to open a new tab.
SOCKS proxies (both v4 and v5) can now be used with all protocols except MailNews.
A new Site Navigation Bar for navigating sites that use the LINK element (like Bugzilla buglists.) Choose the menu item View | Show/Hide | Site Navigation bar | Show As Only Needed to make the toolbar show up automatically when you visit pages that use the LINK element. (Could this be adapted to work with extended XLinks?)
Mozilla has been my default browser on Windows and Linux for several months now, with only occasional crashes and a few minor cosmetic glitches, particularly involving lists. However, in 0.9.4 the Mac version was completely non-functional. Hopefully, that's improved in 0.9.5. I'm downloading it now and I'll let you know.
I'm pleased to announce the release of the XML Bible, Gold Edition. At just barely under 1600 pages, this XML Bible, Gold Edition has arrived at pretty much all bookstores that carry computer books including Amazon, FatBrain, and Barnes & Noble. The list price is $69.99, though most stores are offering their usual discounts. If you need to special order it, the ISBN number is 0-7645-4819-0, and it's written by me, Elliotte Rusty Harold. I'll get the web pages for the Gold edition online here at Cafe con Leche soon, but in the meantime the sample chapters from the second edition are pretty much what's been printed in the Gold edition. In fact, the updated schemas chapter I've posted here was actually taken from the manuscript for the Gold edition. more.
James Anderson's posted cl-xml 0.915, a collection of Common LISP modules for XML parsing and serialization including a validating, namespace-aware XML parser. There's also XPath and XQuery support.
The W3C XML Protocol Working Group has posted two new working drafts for SOAP, SOAP Version 1.2 Part 1: Messaging Framework and SOAP Version 1.2 Part 2: Adjuncts. Previously this was a single monolithic document. Part 1 describes the SOAP envelope and SOAP transport binding framework. Part 2 describes the SOAP encoding rules, the SOAP remote procedure call (RPC) convention, and a concrete HTTP binding. I haven't read the entire specs yet, but I do notice that SOAP is still using local, unqualified child elements in the fault codes. Could somebody please fix this brain damage before it spreads? Thanks. There's really no reason not to put all SOAP defined elements in the appropriate SOAP namespace.
The W3C HTML workinng group has posted the first public working draft of the second edition of XHTML 1.0. Like the second edition of XML 1.0, this draft does not propose changing the language in any way (there's already an XHTML 1.1 after all). It merely clarifies and corrects errors in the specification.
The first alpha of the Gnome 2.0 window manager for Linux has been posted. New features include:
Sun's posted a beta of the Star Office 6.0 word processor/spreadsheet/presentation/drawing suite. The native file format for this package is XML.
The open source Open Office equivalent for this release is OpenOffice.org Build 638c. This build offers greatly improved stability, English spell checking and thesaurus, and full online help.
I'm at XMLOne in San Jose this week. I've posted the notes for my presentations here including:
Software Development 2002 West is being held April 22-26 in San Jose, California, and I have once again signed on to chair the XML track. The call for papers to anybody who'd like to participate in the XML or any other track.
The audience at this show consists primarily of working programmers with a bias toward Java and C++, mostly on the Windows platform though Unix/Linux is well represented as well. At East this year, I noticed a lot of interest in .Net; and there's a .Net track at West as well, so we're definitely interested in presentations about XML in the .Net environment (and other things in .Net as well, though I'm not personally responsible for that). Web services is a big focus as well, though again that goes in a separate track that I'm not responsible for.
When it comes to XML, we find that our attendees really like introductory tutorial sessions. For example a tutorial on the W3C XML Schema Language that covered the basics and assumed no prior experience with schemas would be useful. An advanced session on schema best practices, however, would probably not be of interest to most of our attendees and might be better saved for one of the XML-specific conferences like XMLOne or XML 2001. At this stage it is OK to assume basic knowledge of XML, well-formedness, and DTDs. You do not need to begin your talks with "this is what a tag is", "this is what an attribute is", etc.
Most sessions at SD are 90 minutes. We also have room for a few full-day tutorials. However, for these we prefer speakers who have a good track record presenting at previous SD conferences, so if this is your first time with us, it would be better to submit proposals for 90-minute seminars. We're also accepting proposals for BOFs, panels, and similar events. If you're interested, please fill out the form at If you have any questions, send them to me in e-mail. Thanks!
The W3C P3P Specification Working Group has returned the Platform for Privacy Preferences 1.0 (P3P1.0) Specification to Last Call working draft due to substantive changes made during the candidate recommendation period. The new last call ends October 15. P3P allows Web sites to express their privacy practices in a standard XML format that can be retrieved automatically and easily interpreted by browsers.
I'm flying to San Jose tomorrow for the XMLOne conference so updates are likely to be sporadic until Friday. However, San Jose isn't nearly as interesting a town as Amsterdam so unlike last week I should find some time to check my e-mail and update my sites. :-)
The W3C Document Object Model working group has posted an updated working draft of the DOM Level 3 Core Specification. I didn't notice any major changes in this draft compared to the last one, but so far I've only skimmed it.
The Resource Description Framework (RDF) Core Working Group has posted the first public working draft of RDF Test Cases, "a set of machine-processable test cases corresponding to technical issues addressed by the WG. This document describes the test cases that will fullfill (when the test cases are completed) that deliverable but it does not contain the test cases themselves. The test case are available at."
The W3C Internationalization Working Group has pushed the Character Model for the World Wide Web back from Last Call to simple working draft status. This document "provides authors of specifications, software developers, and content developers RDF Core Working Group has published the first public working draft of RDF Model Theory. According to the abstract:.
Honestly, I didn't understand half of this document, which is full of references to things like the "Strong Herbrand Lemma" and "N-triples syntax". Still, if you're a mathematician who specializes in graph theory, you might find this amusing. The word of the day is "skolemization". Just don't ask me to explain what it means. :-)
The W3C XML Schema Working Group has published an updated working draft draft of XML Schema: Formal Description. According to section 1,
This formalization.
If you're of the opinion that this might have been a good thing to do before the schema speicifcation was finished, well, let's just say you're not alone.
Hewlett-Packard's FOA is a GUI XSL-FO authoring tool written in Java that assists with pagination, page sequences and creates the transformation elements to convert multiple XML content files into XSL-FO. FOA generates an XSLT stylesheet that reads multiple XML documents and applies the style from multiple Attribute Set files according to the transformation elements that you have defined.
jfor is an open-source XSL-FO to RTF converter written in Java. The current version is 0.5. As with all such tools available today, support for all parts of the XSL-FO spec is incomplete. Currently, jfor has limited support of blocks, inline elements, lists, tables and images.
James Clark has released Jing, an open source validator for the RelaxNG schema language written in Java that supports the August 11, 2001 draft of the RELAX NG Specification.
Daisuke Okajima's released RelaxNGCC 0.3, a tool for generating Java source code from a given RelaxNG grammar. By embedding code fragments in the grammar, you can take appropriate actions while parsing valid XML documents against the grammar. This approach is similar to yacc, bison, or JavaCC.
I've posted version 1.0d8 of my XInclude processors for DOM, SAX, and JDOM.
The only API change is that the XIncluder class for JDOM is now named
JDOMXIncluder to parallel
SAXXIncluder and
DOMXIncluder.
It was originally just called
XIncluder because it was the first one I wrote, but I'll probably use that name for a generic driver that uses a command line argument to select which API to use.
Internally, the major change in this release is that I've now implemented
substantially better heuristics for correctly detecting the encoding of text
files included with
parse="text".
The dbXML project has posted the second beta release of the dbXML Core XML database, an open source native XML database designed to manage large collections of small XML documents. The server supports XPath queries and provides an implementation of the XML:DB XML Database API for development of client applications. This beta fixes various bugs.
The W3C Device Independence Activity has published its first public working draft, Device Independence Principles. According to the abstract, "This document celebrates the vision of a device independent Web. It describes device independence principles that can lead towards the achievement of greater device independence for Web content and applications." The goal is to allow web pages to be presented not just to different Web browsers, but to telephones, PDAs, kiosks, digital paper, fax machines, televisions, and other radically different hardware.
The W3C/IETF joint URI Planning Interest Group has published t a note on URIs, URLs, and URNs: Clarifications and Recommendations. According to the abstract:.
It makes interesting reading. I recommend it for anyone who's ever been confused about the difference between URLs, URIs, and URNs, and exactly what makes a legal URI anyway.
The W3C CSS Working Group has published the first public working draft
of the Backgrounds module for CSS Level 3.
Properties in this document would be used to specify background colors, images, and so forth. New properties added since CSS2 include
background-size,
background-clip, and
background-origin.
The W3C P3P Working Group has published the last call working draft of the Platform for Privacy Preferences 1.0 Specification. P3P is an XML application browsers and server can use to exchange information about web site privacy policies and user choices for what information they're willing to share according to what preferences. Comments are due by October 15.
The W3C User Agent Accessibility Guidelines Working Group has posted the candidate recommendation of User Agent Accessibility Guidelines 1.0. According to the abstract:.
Sun's posted the proposed final draft (version 0.94) of the Java API for XML Messaging Specification. As usual, it's PDF format only. JAXM implements the Simple Object Access Protocol (SOAP) 1.1 with Attachments.
Apropos Toy & Tool Development has released RoustaboutXT 2.0, a $300 payware Quark XPress XTension that imports and exports XML from Quark. This release adds full import/export capabilities with support for anchored text and pictures; and a hitch feature to allow the XTension to be used as traditional text filter for use with Applescript and batching XTensions. Upgrades from version 1.0 are free.
Apropos has also released version 2.0 of XPress XML, a $50 payware Quark XTension that also imports and exports XML from Quark but is much less customizable. Version 2.0 also adds the "Hitch" feature.
I've returned from XMLOne Amsterdam. Several speakers couldn't make it due to the attacks on September 11. Consequently those of us who did get there ended up talking more than we had planned. I had planned to talk for three hours total, and ended up tripling that. Talks I gave included:
The last one was written by Wendell Piez of Mulberry Technologies. I just delivered the lecture from Piez's notes because he couldn't make it to the show. You'll have to ask him if you want a copy of the notes.
The Apache Cocoon team has posted the first release candidate of the Apache Cocoon 2.0 XML publishing framework. Version 2.0 is supposed to "remove all those design constraints that emerged from the Apache Cocoon 1 experience."
Michael Kay's released version 6.4.4 of his Saxon XSLT processor. This release fixes 13 bugs, updates Saxon to work with FOP 0.20.1 and JDOM 0.7, and adds a few performance optimizations that "will give a very substantial speed-up to a rather small number of stylesheets." Saxon is written in Java, but a Windows executable version is also available.
The W3C XML Core working group has published a new working draft of the XML Blueberry Requirements. This document proposes a new, incompatible version of XML that allows characters introduced in Unicode 3.0 and later to be used in element and attribute names. (They can already be used in character data.) Furthermore, it intends to allow the use of certain mainframe line ending control characters in tag white space as well.
There are no significant changes in this draft. The real purpose of this draft seems to more clearly express the working group's motivation that "Discriminating against languages simply because their scripts were not encoded in Unicode 2.0 is inherently unjust." The working group continues to ignore the costs this will impose on the existing XML community, and indeed considers any cost-benefit analysis to be immoral.
Numerous objections that were raised against the earlier draft set of requirements remain unanswered, including:
The working group is pretending that this is 1995, that nobody has any investment in the existing infrastructure, and that anything less than the best solution imaginable today in 2001 is unjust and unacceptable. But it's not 1995. People do have huge investments in the existing XML syntax. Changing it now has real costs that will harm real people. The working group refuses to even consider these costs or to tally up the benefits expected and compare them to the costs. They have decided that this will be done and that no justification is necessary.
The XML Linking Working Group has published a new Candidate Recommendation of XPointer. At first glance, the XPointer syntax and semnatics does not seem to have changed. However, the specification document has been cleaned up, and some points have been clarified, though you still have to read between the lines to figure out how to write an XPointer that selects a point.
Theodore H. Smith has released ElfData 1.11 for MacOS, a $55 payware XML editor. This release mostly fixes bugs and improves performance and appearance. This release also adds syntax coloring.
Tony Graham's posted revision 0.2 of xslide, an Emacs major mode for editing XSL stylesheets . Features of xslide revision 0.2 include:
I've posted Reading XML, Chapter 5 of Processing XML with Java. This chapter is a broad overview of the various parsers and APIs available for processing XML documents. It provides example of DOM, SAX, JDOM, dom4j, and ElectricXML and discusses the relative advantages and disadvantages of each. SAX and DOM will definitely be covered in more detail in future chapters.
The coverage of dom4j and ElectricXML was directly inspired by comments from Cafe con Leche readers I received on earlier chapters. After exploring these APIs in more detail, I found some major design flaws in ElectricXML so it probably won't be covered past this chapter. dom4j actually looks pretty well designed though, and may be the best of the non-standard APIs. I need to try it on a tougher problem like my XInclude processor and see how it holds up. I'm also debating whether I should add a section to this chapter on kXML, a parser that doesn't implement any of the standard APIs but will run in J2ME environments.
Mozilla 0.9.4 has been released with fixes for 1,467 bugs. As usual it's available on Windows, MacOS, OpenVMS, Solaris 8 and Linux. New features include the ability to disable the JavaScript window.open() method during page load and unload events to eliminate those annoying pop-up and pop-under ads. (This should be turned on by default!) I found 0.9.3 to be significantly less stable than earlier releases. Hopefully, this release fixes the problems I was experiencing.
Delta tells me that my flight to Amsterdam is still scheduled to take off on time tomorrow, so I guess I'm going to go the airport and hope. If the FAA does let it leave the ground, I'll see some of you at XMLOne next week.
Slashdot's posted a nice review of XML in a Nutshell. I'm going to try to participate in the discussion, but the general slowness of the net today is making it hard.
Wolfgang Meier of the Darmstadt University of Technology has posted version 0.6 of eXist, an open source native XML Database with pluggable storage backends and support for fulltext searching. This is mainly a bug fix release. However, there are some new features including client side support for the XML:DB XML Database API. More volunteer developers are needed.
My Speakeasy DSL went down yesterday afternoon as a side effect of Tuesday's attacks. Several other ISPs in the area are affected as well. Apparently a backup generator overheated, and nobody can get to the site to repair it. For the moment I'm on a dialup connection. To complicate matters, I'm scheduled to leave Sunday for the XMLOne conference in Amsterdam. I don't know if I'm going to be able to get out or not; but whether I do or not updates are likely to be a little sporadic here for the next week or so.
Also, if there's anybody out there who's planning to be in Amsterdam next week and would be willing to cover my schemas talk for me if I can't make it, please drop me a line. I'd be happy to share my notes with you. It's a pretty standard, two hour intro to schemas talk. I'm also scheduled to deliver a session on Cutting Edge XML Programming, but that's a much more idiosyncratic session wandering all over the map including SAX 2.1, DOM3, XPath 2.0, XSLT 2.0, and XQuery.
Fourthought, Inc. has released version 0.11.1 of the 4Suite 0.11.1 and 4Suite Server 0.11.1 open source libraries for processing XML in Python. 4Suite "provides support for XML parsing, several transient and persistent DOM implementations, XPath expressions, XPointer, XSLT transforms, XLink, RDF, XInclude, XUpdate and ODMG object databases." 4Suite Server "features an XML data repository, metadata management, a rules-based engine, XSLT transforms, XPath and RDF-based indexing and query, XLink resolution and many other XML services. It also provides transactions and access control features. Along with basic console and command-line management, it supports remote, cross-platform and cross-language access through CORBA, WebDAV, HTTP, FTP and other request protocols."
Altova's released version 4.0 of XML Spy, their popular $399 payware XML editor. New features include:
fixed,
redefine,
abstract,
nillable, and
xsi:nil
I tested the last public beta of this release and, and I've seen reports that this is still true in the final release version. If you're using XML Spy 3.5, I reocmmend you don't upgrade until at least the next bug fix release. If you're not using XML Spy, I recommend you stick with whatever you are using until at least the next major release.
I'm still feeling a little shocked from the bombings yesterday. The magnitude of this is still seeping in. Personally, I feel quite fortunate. So far all my friends, family, and colleagues seem to have come through OK. There's still one person I need to check on. (Update: I got in touch with her this afternoon and she's fine.) For those of you who aren't New Yorkers, just know that a lot of people worked in the towers at all levels from CEO to janitor. Everyone in New York knows someone who worked there, often many people. This attack really cuts across all levels of the city. As somebody (I forget who. It might have been Giuliani.) said on the news last night, this attack did not single out whites or blacks or Jews or Arabs or Christians or Muslims or Chinese or police officers or civilians or citizens or foreign nationals or immigrants or any other group. This was an attack on all of us.
This has been the main topic of discussion on many of the mailing lists I participate in, with topics ranging from XML to Unicode to computer book publishing. None of these are political lists. Mostly the list moms seem to be willing to let the discussion flow without worrying too much about how off-topic it is. That's important in times like this. Sentiment seems to be divided about 50-50 between the "Let's get revenge and bomb somebody, even if we aren't sure exactly who" and "Let's focus on catching the criminals, and try to understand why this happened." Private e-mail about my comments yesterday is about equally divided.
I wish I could say that the television media showed an equal diversity of opinion, but I'm afraid that's not true. CNN, CBS, and the local stations would only interview the same white war mongers and law enforcement agents who kept insisting that we needed to start bombing people before we even knew who was responsible, that we needed to repeal the restriction against assassination (James Baker), and that we were going to have to give up our civil liberties. Dissenting voices like Noam Chomsky, Howard Zinn, or Norman Siegel were even more absent from the air waves than they normally are.
I finally found some intelligent rational discussion on Channel 54, BET. They were interviewing Al Sharpton, Jesse Jackson Sr., and others who had a much more cautious view. It was the only place in the mass media where I saw any recognition that there were likely reasons this attack occurred, and that we needed to address the root causes as much as the symptoms. It was one of the few places on TV I saw any concern for avoiding civilian casualties in the inevitable retaliation for this attack. The white mass media likes to portray people like Sharpton and Jackson as fringe nutcases. What was apparent last night was that the fringe is a lot more reasoned, informed, and honest than the mainstream. If either of them runs for anything again, they've got my vote. We need more people like this.
I promise I'll get back to Java and XML tomorrow. Right now I'm just having a little trouble focussing on such things.
I'm continuing to watch the spin about the attacks today. The level of racism and Anti-Arab hysteria seems to be rising slowly through the day, though there's still no evidence of the race or nationality of the criminals. And of course even if it does turn out that the terrorists were in fact Arabs, that's no justification for retaliatory attacks against Arab countries and civilians.
Many people are calling this an act of war and comparing it to Pearl Harbor. In reality, this isn't even close. Pearl Harbor was a deliberate attack by the military forces of a hostile nation. In all likelihood, no nation and no government was behind this assault. That of course, is what terrorism means: a violent assault by non-government individuals and groups for political purposes. When nations commit violent assaults against civilian populations, it's not called terrorism even though the effects are much worse.
I'm also hearing a lot of talking heads from the FBI and other law enforcement agencies blaming this attack on the openness of our society, our rights, and our civil liberties. Of course the obvious implication is that we need to reduce these and unleash law enforcement to combat attacks like today's. In truth, of course, a police state would have done nothing to prevent today's attacks or one in the future.
I've also watched pictures on the news of Palestinians celebrating in the street. A few people have expressed concern that Americans are hated around the world, and that consequently we need to beef up our defenses. Nobody seems willing to ask the question of why we're so hated that school children are celebrating the violent murder of thousands of people. The answer, of course, is that while what happened today is completely new to the American experience, it's not at all new in many other places around the globe. In Palestine, in particular, the people have been brutally assaulted and murdered by terrorist planes for decades. Many of those planes are American made and/or paid for with American dollars. The attacks today may or may not have been retribution for the decades of oppression of Palestinian people, but we should not be particularly surprised that the oppressed take a little glee in a successful attack on a previously invulnerable oppressor.
The real solution cannot be found in retaliation. Violence only begets more violence. While I hope that any living collaborators in this attack are captured and severely punished, I see no point in going to war against Palestine, Afghanistan, or anyone else. Terrorist actions of this nature are inevitable as long as the United States persists in its decades long suppression of legitimate aspirations for self-rule around the world. This is nothing new. The U.S. actively backed repressive client states in Greece, in Italy, in Guatemala, in Nicaragua, in El Salvador, in Vietnam, in the Philippines, in Iraq, in Iran, in Palestine, and many other places. The only thing that surprises me is that it's taken this long for responses on our home soil to reach this magnitude. Until the U.S. is willing to honestly address why we're hated, no security measures will be sufficient.
Update: after a few hours of watching the coverage on the news and listening to people on various mailing lists, mostly New York local, it seems increasingly probable that we're going to go to war with somebody even if the country we're attacking had nothing to do with the attack. The most likely target of opportunity seems to be Afghanistan. Based on past experience, there probably won't be any real war, just a bunch of planes dropping bombs from a couple of miles up. This would solve nothing. That a few idiots without government support killed possibly hundreds of American civilians is not an excuse for us to retaliate by killing several hundred civilians in their country who had equally little to do with this.
I'm sitting here in New York switching between CNN and local channels. I just saw the second tower of the World Trade Center go down. This is truly horrible. I know many people who work there. I'm hoping they're alright. I think there was a Sun office there, although I don't remember off the top of my head whether it was in one of the towers or one of the three smaller buildings. It might even have been a local Sun reseller. One of the local user groups had meetings there, though I stopped attending after the security screening refused me admission one night because I wasn't on the list of attendees. Either way, I hope everyone got out. The attack happened relatively early in the morning on an election day here in New York so maybe the buildings weren't as full as they might have been. We can only hope. (I just heard the election has been postponed.)
So far the coverage I've seen has been relatively restrained. Oklahoma City taught most networks that they couldn't automatically blame the Arabs for every terrorist attack. Maybe some politicians learned their lessons too and we won't hear the calls for immediate retaliation against some target before we even know whose responsible for this horror.
Longer term there are going to be a lot of calls for higher security measures at airports, restricting travel from unfriendly nations, more surveillance cameras, and various other Big Brother measures. It's important to remember that none of these did any good today. After the last bombing, the World Trade Center had some of the tightest security of any general office building in New York; and it didn't help. We don't know yet what happened at the airports where the planes left, but all the requirements that people show ID and go through various security checkpoints didn't stop this either.
Whoever was immediately responsible for this atrocity is undoubtedly dead along with any passengers who may have been on the planes. We may never know their names, and we certainly won't be able to exact vengeance on them. I'm also afraid though that somebody's going to be brought to trials for this, whether they're actually responsible or not. If we can indeed find the murderers responsible for this act, then they deserve to be put in prison for the rest of their natural lives. However, I'm very worried that the government can't find the people responsible, then they'll find somebody anyway, no matter how tangential their connection to the actual bombers. We have to be wary of show trials designed to do nothing more than assuage our desire to make someone pay.
The W3C HTML Activity. has posted a new working draft of the XForms 1.0 specification. draft are too numerous to list here, but are nicely summarized in an appendix to this draft.
The W3C Web Accessibility Initiative Protocols and Formats Working Group has published a working draft of XML Accessibility Guidelines. From the.
The W3C has promoted SMIL Animation to full Recommendation. According to the abstract, this specifies an "animation functionality for XML documents.. It describes an animation framework as well as a set of base XML animation elements suitable for integration with XML documents. It is based upon the SMIL 1.0 timing model, with some extensions, and is a true subset of SMIL 2.0. This provides an intermediate stepping stone in terms of implementation complexity, for applications that wish to have SMIL-compatible animation but do not need or want time containers."
The Resource Description Framework (RDF) Core Working Group has posted the first public Working Draft of Refactoring RDF/XML Syntax. The document records the process of updating the grammar in the Resource Description Framework (RDF) Model and Syntax Specification, showing the changes step-by-step.
xmlsecurity.org has published an open source implementation of Canonical XML in Java. It has also started work on an implementation of XML Signature. Currently only source code is available. You'll have to compile the package yourself.
Norm Walsh has released version 1.44 of his XSLT stylesheets for Docbook, that I use to generate both the HTML and PDF versions of Processing XML with Java. This release fixes various bugs including some nasty ones involving the handling of dingbat characters such as curly quotes.
Keith Isdale's released xsldebugger 0.4, a GPL'd gdb-like tool to debug XSLT stylesheets built on top of libxslt. It currently runs on Windows.
The W3C has posted the final recommendation of the Scalable Vector Graphics (SVG) 1.0 Specification. Changes since the proposed recommendation appear mostly editorial.
Adobe's posted the first beta of version 3.0 of their SVG Viewer browser plug-in for Netscape and Internet Explorer on Mac and Windows. This release should be closer ot full conformance with the 1.0 Recommendation. Newly supported parts of SVG include:
color-profile,
marker,
title,
view, and
switchelements
color-profile,
marker,
marker-end,
marker-mid,
marker-startCSS properties, the
@mediaCSS rule, and the
mediaattribute for
styleelements. The values
all,
screen, and
imageelement now supports links to static SVG files
ElementTimeControl::beginElement,
ElementTimeControl::endElement,
getCTM,
getElementsByTagNameNS, and
getBBoxmethods and the
SVGMatrixclass from the SVG DOM.
Other new features include:
in-GmbH's Sphinx SVG is a $253.58 drawing program that can export (but not import) SVG graphics.
Altova's posted a public beta of XML Spy 4.0, a payware XML editor. Registration is required to download the beta and beta testers should not expect a free copy when the product is released. New features include:
fixed,
redefine,
abstract,
nillable, and
xsi:nil
This is the first version of XML Spy I've tried in a while, and overall I. Maybe they'd work with simpler, less complex documents. Perhaps this will get fixed in the next release, but XMLSpy still seems substantially more difficult to use than a simple text editor like jEdit.
Speaking of jEdit, version 0.4 of the jEdit XML plug-in has been released. New features in this release include support for catalog files in the XML Catalog or OASIS SOCAT formats and a new new "XML Insert" window that lists elements and entities declared in the DTD. jEdit 3.2.1 is required. Check your jEdit Plug-Ins dialog to install.
James Tauber and Daniel Krech have released Redfoot 1.0, "an open source (BSD-license) framework for building distributed data-driven web applications with RDF and Python." Redfoot includes:
The W3C XML Schema Working Group has has released the W3C XML Schema Test Collection. Both positive and negative expected outcomes are tested with respect to a range of core XML Schema features. More tests are forthcoming and more are desired.
Fabrice Desre has posted version 0.2 of XSLTDoc, an XSLT stylesheet documentation generator. XSLTDoc is an XSLT stylesheet that analyzes another stylesheet and builds a clean documentation on it. whiling doing some lint-style sanity checks. New features in version 0.2 include:
I've now successfully installed Internet Explorer 6 on my NT box and have been able to check out its support for XML (or lack thereof). I've also received a number of reports from readers.
First the good news: IE6 does seem to support XSLT 1.0. I haven't run it through extensive testing but it did correctly render all the simple XML + XSLT 1.0 examples I took from the XML Bible 2nd edition. It does recognize the namespace. This is about two years too late, but better late than never.
Now for the bad news (and there's a lot of it):
At first glance, CSS support for XML does not seem to be significantly improved. For instance,
display: table is still not supported.
Microsoft still labors under the illusion that there is a MIME media type text/xsl. IE does not recognize the actual MIME types text/xml and application/xml+xslt as identifying XSL stylesheets.
The XML parser built-in to IE is thoroughly broken. It accepts some malformed documents as well-formed. It rejects many real-world well-formed and even valid XML documents as malformed, most embarrassingly the first edition of the XML 1.0 specification itself.
Bottom line: any doubt that the IE team at Microsoft actually cares about standards has been erased. More than three years since XML 1.0 was released and almost two years after XSLT 1.0 was released, IE still does not correctly implement these specifications. Even though the XML parser group at Microsoft provided the IE group with a relatively standards conformant XML parser/XSLT processor, the IE programmers deliberately chose to cripple it rather than support standard XML!
The excuses that the IE team simply made a mistake in interpreting the spec, or that their software shipped before the specs were finished are no longer tenable. The only reasonable interpretation of Microsoft's actions is that the IE developers believe it's more important to maintain compatibility with broken, beta, Microsoft proprietary experiments than to support proven, reliable, standard specifications. They do not exist in a culture that rewards compliance with specifications. At most they care about compatibility with other Microsoft software. They are simply not willing to expend any effort to improve compatibility with the rest of the world. In the future, one must assume that Microsoft will implement only those parts of XML specification that they like, and that they will change. modify, extend, and break those parts of the specs they don't like. Conformance to standards is simply not a virtue in the Microsoft world.
The W3C has formed the Web Ontology Working Group, part of the Semantic Web Activity, to develop a language that extends language - a comparison of DAML+OIL to XML, XML-schema, and RDF-Schema is available.
Sun's posted the second beta of the Java API for XML Messaging (JAXM). JAXM implements the Simple Object Access Protocol (SOAP) 1.1 with Attachments. This version of the JAXM specification adds messaging Profiles "to establish a foundation for supporting a family of higher level standards-based messaging protocols. An example of a Profile would be an implementation of ebXML Transportation, Routing, and Packaging Message Handling Service or the W3C's XMLP layered on JAXM."
Microsoft's released Internet Explorer 6.0 for Windows. I haven't tried it yet. Would anyone care to comment, particularly on its XML and XSLT support? Does it finally support XSLT 1.0 in its default installation? Does it actually recognize the correct MIME media type (text/xml) for XSLT style sheets? And is CSS support improved to the level currently available in Mozilla and Opera?
Update: the first responses are coming in and it seems that Microsoft has once again deliberately chosen not to conform to XML 1.0. IE6 does use MSXML3, but it instantiates it in a "backward compatibilty mode" where it inherits MSXML's bugs including not recognizing character references after and allowing the illegal C0 control characters such as null and vertical tab. I'm still waiting to hear whether they support XSLT 1.0 or not.
James Strachan's released dom4j 1.0, an open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework with full integration with DOM, SAX and JAXP. This release adds:
I'm back from Vermont, Boston, and the Software Development 2001 East show. The show was a little smaller this year following the dot-bomb, and some of the classes had very small audiences; but overall it was still a good time, and there were a few interesting developments.
Howard Katz clued me into Quip, a free-beer implementation of the XML Query Language from Software AG. It can query against the Tamino database or a local collection of XML documents. I'll probably demo this in my Cutting Edge XML Programming session at XMLOne Amsterdam in a couple of weeks. The current version is 1.5.1.
I also spent a lot of time working on my XInclude processors at the show.
Nothing like having to give a demo of a product to inspire you to finish it up.
I fixed some serious bugs in the SAX
XIncludeFilter
and added support for the detecting the encoding of text files to
all three versions (SAX, DOM, and JDOM). I also improved the error reporting
and handling across the package. All users should upgrade.
Of course as always seems to happen, in the course of implementing the "last feature" I noticed several things I hadn't seen before in the specification. The big ones related to XInclude's usage of the infoset, particularly unparsed entity and notation information items. If an XInclude processor is required to pass these along, then it's basically impossible to implement XInclude fully in either DOM or JDOM, because they don't expose these properties in the necessary places. SAX can do it, but not in a streaming fashion. In essence, handling XInclude requires you to build your own infoset compatible, XPointer addressable, tree-model for an XML document. Yuck. I'm hopeful that this is a result of an unclear specification document rather than the actual intent of the working group.
However, if it does turn out that full infoset support is required for XInclude handling, Lynda van Vleet and Kirill Gavrylyuk's presentation to me suggested an interesting approach. For the OASIS XSLT conformance testing project, they've defined an XML serialization of the infoset which is not, as you might think, the original XML document. For example, suppose the original XML document looks like this:
<?xml version="1.0"?> <!-- Simple XML Document --> <msg:message msg:Phone home!</msg:message>
Then its infoset serialization looks like this:
<document> <children> <comment> <content>Simple XML Document<content> </comment> <element> <namespaceName></namespaceName> <localName>message</localName> <children> <text>Phone Home!</text> </children> <attributes> <attribute> <namespaceName></namespaceName> <localName>date</localName> <normalizedValue>19990421</normalizedValue> <attributeType>CDATA</attributeType> <specified>true</specified> </attribute> </attributes> <inScopeNamespaces> <namespace> <prefix>msg</prefix> <namespaceName></namespaceName> </namespace> </inScopeNamespaces> </element> </children> </document>
The OASIS Group canonicalizes this representation so they can compare the infosets of two different documents produced by two different parsers. For XInclude, I'd use XSLT to combine and process the documents , possibly along with a couple of extension functions. Finally, the entire result could be written out as a serialized XML document. This is not nearly as efficient as my current more direct approach, but something like this might be the only reasonable way to achieve full conformance to XInclude.
Currently, the OASAIS group is using XSLT to generate this representation which misses some parts of the Infoset that the XPath data model doesn't include, particularly the unparsed entities and notation information items I'm concerned about. However, it would be easy enough to generate this from SAX.
The W3C XML Query Working Group, XML Schema Working Group, and XSL Working Group have produced the first public working draft of XQuery 1.0 and XPath 2.0 Functions and Operators. According to the abstract, ."
The W3C DOM Working Group has posted a new draft of the XPath API for DOM Level 3. The design of the API has changed and is no longer dependent on XPath 2.0.
The W3C XSL Working Group has published a proposed recommendation of the Extensible Stylesheet Language (XSL) Version 1.0 (XSL-FO). The document lists the following 15 non-editorial changes.
Review ends September 25, 2001. I'll probably wait to update the
online XSL-FO chapter from the XML Bible until FOP's been updated to support the changes.
Mostly these are pretty minor. I think the only ones that affect the Bible chapter are the name changes from
master-name to
master-reference
and
space-treatment to
white-space-treatment.
The W3C has posted a new working draft of XSLT 1.1 simply to note that development of this version has ceased in favor of XSLT 2.0. Specifically,
NOTICE:As of 24 August 2001 no further work on this draft is expected. The work on XSLT 2.0 identified a number of issues with the approaches being pursued in this document; solutions to the requirements of XSLT 1.1 will be considered in the development of XSLT 2.0 [XSLT20REQ]. Other than this paragraph, the document is unchanged from the previous version.
The XML Apache Project has posted the second beta of Xerces-Java 2.0.0, an open source XML parser. This is primarily a bug fix release. However, a new XNI parser configuration interface has been added to allow the creation of "pull" parser configurations. In addition, more XNI documentation has been written that explains how to re-use the standard Xerces2 parser components. Xerces2 supports XML 1.0, Namespaces, DOM Level 2 (including events, traversal, and range), SAX 2.0, and JAXP 1.1. Xerces2 does not yet support XML Schema and has removed support for the deferred DOM implementation..
Daniel Veillard's added XML Catalog support to the libxml/libxslt (1.0.3/2.4.3) XML parser/XSLT processor libraries for Linux. Several bugs in other areas have also been fixed in this release.
Fabrice Desre has released XSLTDoc, an XSLT stylesheet documentation generator. This tool is itself an XSLT stylesheet that analyzes another stylesheet and builds a clean documentation on it. It also makes some sanity checks.
Daniel Veillard's added XML Catalog support to the libxml/libxslt (1.0.3/2.4.3) XML parser/XSLT processor libraries for Linux. Several bugs in other areas have also been fixed in this release.
I've posted the notes from my various presentations this week at Software Development 2001 East including:
I'm leaving for Software Development 2001 East shortly, so updates may be a little sparse here over the next week. A lot depends on what sort of Internet access I have at the conference and in my hotel room at the Sheraton Boston.
The W3C DOM Working Group has published a new working draft of Document Object Model (DOM) Level 3 Events Specification.
The W3C Speech Working Group has published the Last Call Working Draft of Speech Recognition Grammar Specification for the W3C Speech Interface Framework.. Last Call ends September 28, 2001.
I've posted the first development version of a SAX-based XInclude program
I wrote in Java. This is believed to be a complete implementation of the XInclude working draft with the exception of XPointer support.
It is somewhat more complete than the DOM and JDOM versions I posted earlier.
In particular it detects invalid values of the
parse attribute and supports the
encoding attribute for included text documents.
I'll probably add these features to the DOM and JDOM versions soon.
I'll be talking about all three of these programs next week at Software Development East in Boston. Registration is still open, and we're also looking for a few more volunteers to help out with distributing class evaluations and doing general gopher work in the sessions. If anybody is interested in volunteering in exchange for free admission to the conference, (You get one day at the conference for each day you volunteer, and of course when volunterring you get to attend the sessions you're assigned to.) please email Nicole Garbolino at ngarbolino@cmp.com.
Converting Flat Files to XML, Chapter 4 of Processing XML with Java,
has been posted.
This chapter covers reading data in a variety of non-hierarchical forms including CSV text files and relational databases, and converting that data into well-formed, potentially valid XML documents. Topics covered include
StreamTokenizer and
StringTokenizer, XSLT, SQL, XQuery, servlets, designing tree data structures in Java,
and the U.S. Federal Budget.
As always,
any comments you have would be appreciated. I'm particularly interested in knowing whether you can follow the examples as written or whether more explication or input data is required.
The Apache XML project has released Xerces-J 1.4.3,
an open source XML parser written in Java. This is a bug fix release.
According to IBM's Neil Graham
"The largest difference between it
and Xerces-J 1.4.2 is that the Xerces-J DOM implementation has been
Reorganized to separate the Core functionality (new classes:
CoreDOMImplementationImpl,
CoreDocumentImpl), from the complete DOM
(
DOMImplementationImpl,
DocumentImpl). It also incorporates general
bugfixes to schema support as well as fixes to allow it to operate better
on OS/390."
New features are being developed exclusively in the Xerces-J 2.0 tree.
The joint W3C/IETF XML Signature Working Group has published a Proposed Recommendation of XML-Signature Syntax and Processing. This describes a mechanism for digitally signing all sorts of electronic files (not just XML documents) and embedding those signatures in XML documents. Comments are due by September 17, 2001.
The dbXML project has posted the first beta release of the dbXML Core XML database, an open source native XML database designed to manage large collections of small XML documents. The server supports XPath queries and provides an implementation of the XML:DB XML Database API for development of client applications. Major changes in this release include proper namespace support for XPath queries, updates for the latest XML:DB API and many bug fixes. No further feature additions are planned prior to a production release of dbXML 1.0.
IBM's alphaWorks has posted updated version of several products. The latest version of the XML Schema Quality Checker offers full support for identity constraints, fixes some bugs, clears up a few error messages, and enhances performance when validating schemas.
The XML Generator fixes a few bugs primarily involving command line use. This is a tool to generate valid XML documents from a DTD.
Finally, version 3.2.1 of the XML Parser for Java includes many bug fixes and several performance improvements. This is essentially a repackaged version of Xerces-J, which itself is based on a lot of IBM work.
Ovidiu Predescu's released XSLT-Process 2.1, a minor mode for GNU Emacs/XEmacs which adds XSLT processing and debugging capabilities. New features in this release include:
Currently the Saxon and Xalan Java XSLT processors, and Apache FOP are supported. XSLT-Process has been tested on XEmacs, versions 21.1.14 and 21.4.3, and GNU Emacs 20.7.1, under both Linux and Windows 2000. The package is free software distributed under GPL.
The XML Apache Project has released Xalan-C++ 1.2, an open source XSLT 1.0 processor written in C++. This version of Xalan-C++ was built with, and includes Xerces-C 1.5.1. Binaries are available for Windows, Linux, Solaris, AIX, and HP/UX.
The W3C has published a first and last call working draft of the W3C Patent Policy Framework. Boiled down, what this says is that all W3C members have to tell the working groups what relevant patents they hold. There's no obligation to offer any sort of license to anybody on any terms. Frankly, this is far too weak. I would prefer a policy that stated that all W3C members must dedicate all relevant patents to the public domain, but short of that it would probably be enough to say that all W3C members must offer royalty-free licenses to all implementers. However, since the W3C is bought and paid for by its corporate members the chance of this happening is virtually nil. Comments are due by September 30.
James Clark has posted an experimental non-XML syntax for the RELAX NG XML Schema Language. According to Clark, "It's quite similar in many ways to the type syntax of the current XQuery 1.0 Formal Semantics Working Draft." A Java program that can translate this syntax into RELAX NG's XML syntax is provided.
Norman Walsh has written some Java classes that implement the OASIS XML Catalogs Committee Specification for SAX EntityResolver and JAXP URIResolvers.
James Tauber and Dan 'eikeon' Krech have posted Redfoot 0.9.9, a framework for distributed RDF-based applications, written in Python. Redfoot. Acccording to Tauber, "0.9.9 should be viewed as a beta for 1.0 (to be released in the first half of September). We would appreciate as much feedback on 0.9.9 as possible to help make 1.0 as stable and easy to use as possible."
Sun's posted the Java API for XML Registries (JAXR) v0.6 Specification as well as an early access implementation. JAXR is a Java API for accessing different kinds of XML Registries for web services eventually including ISO 11179, OASIS, eCo Framework, ebXML and UDDI. Currently detailed bindings are provided for ebXML and UDDI. JAXR 1.0 is planned to become an optional package for the Java 2 Standard Edition. Commennts are due by September 13, 2001.
The XML Apache Project has released FOP 0.20.1. This is an open souurce XSL Formatting Objects to PDF converter written in Java. This release fixes a major bug in yestreday's 0.20.0. Most users should upgrade. You should remember that although FOP is very popular, it is far from production quality. Many XSL-FO features ar enot yet implemented, or are implemented only partially. If something doesn't work like you expect, it's probabaly a bug in FOP. Please don't bother reporting these things on non-FOP mailing lists like xsl-list or docbook-apps.
The OASIS RELAX NG Technical Committee has posted version 0.9 of RELAX NG, a schema language for XML. Both a comprehensive specification and a tutorial are available. Two months have been allocated for public comment and implementation. According to the tutorial, changes from the previous version include:
IBM's alphaWorks has released version 1.5.0 of their XML for C++ parser. This is based on the Apache Xerces XML C++ Parser V. 1.5.0. It adds support for a subset of the W3C XML Schema language, fixes some bugs, and speeds up performance.
I've posted Writing XML, Chapter 3 of Processing XML with Java. This chapter teaches you how to output XML documents from your programs. Topics covered include output streams, writers, Unicode, servlets, XML-RPC clients, SOAP clients, Latin, and rabbits taking over the world. As alway, comments and corrections are much appreciated.
The XML Apache Project has released FOP 0.20.0 (web site not yet updated). This is an open souurce XSL Formatting OPbjects to PDF converter written in Java. This release is a small improvement over 0.19.0. It did fix several of the most annoying bugs I've encountered while writing Processing XML with Java including some problems with embedded images and extra indentation in the first line of code examples. However, it's still eating all the blank lines in my source code; and there do seem to be some new bugs involving external fonts so you may want to hold off upgrading for a while if you're satisfied with your existing installation.
The Institute for Applied Information Processing and Communications (IAIK) has released the IAIK XML Signature Library (IXSIL) 1.0. IXSIL is a Java class library for creating and verifying XML based digital signatures. IXSIL supports the Candidate Recommendaiton syntax of XML-Signature Syntax and Processing. IXSIL is 800 euros payware.
The W3C Core XML Working Group has published the Proposed Recommendation of the XML Infoset. At first glance, there do not appear to be any major changes since the candidate recommendation, though I do wish working groups would publish change lists between versions.
The XML Infoset is an effort to define what is and is not significant about an XML document. For example, the content of an element is significant. Whether or not that content came from parsed text, an external entity, an internal entity, or a CDATA section is not. If this had been published right after Namespaces in XML had been released, then it might have been more useful. However, the fact is we're already awash in different models of what matters in an XML document including SAX, DOM, and XPath, all of which are subtly incompatible with each other.
Edwin Goei's written a FAQ for the Java API for XML processing.
Microsoft's posted Internet Explorer 5.5 Service Pack 2 and Internet Tools. I haven't found the release notes yet, so I'm not sure exactly what's changed in this revision. The download page says this "includes improved support for DHTML and CSS" and "allows you to use Connection Manager as your default dialer when Dial-Up Networking is already installed." I advise caution with this release. I've already seen one unconfirmed report that this release disables Netscape-style plug-ins and that only ActiveX controls work. Henry Rzepa noticed the same thing in the beta of Internet Explorer 6.
The Apache XML Project has posted the first beta quality release of Xerces 2.0.0, an open source XML parser written in Java. The Xerces2 beta release has been greatly improved since the alpha release with an updated Xerces Native Interface (XNI) core; the addition of the parser pipeline and configuration interfaces to XNI; and completely re-written documentation, including lots of new information about XNI. Xerces2 supports XML 1.0, Namespaces, DOM Level 2 (including events, traversal, and range), SAX2, and JAXP 1.1. It does not yet support schemas and has removed support for the deferred DOM implementation. According to Andy Clark, ."
The SYMM Working Group at the W3C has released the final recommendation of the Synchronized Multimedia Integration Language (SMIL) 2.0. SMIL is an XML application for describing interactive multimedia presentations. "Using SMIL 2.0, an author can describe the temporal behavior of a multimedia presentation, associate hyperlinks with media objects and describe the layout of the presentation on a screen."
They've also published the first public working draft of an XHTML+SMIL profile. This adds (optionally) a subset of SMIL 2.0 to XHTML. SMIL modules inlcuded in this profile are animation, content control, media objects, timing and synchronization, and transition effects. Both DTDs and schemas for this are provided.
One new feature I missed yesterday when announcing Netscape 6.1 is support for browser side XSLT. There's still not a large enough installed base to use client side XSLT in production, but at least this will make writing books about it somewhat easier.
Netscape's released version 6.1 of their flagship web browser for Windows, MacOS, and Unix in English, German, and Japanese. This release fully supports XML and CSS, though not yet XSLT. New features include support for Hebrew on Linux and Windows and Arabic on the Arabic version of Windows as well as autotranslation between English, French, German, Russian, Japanese, Italian, Spanish, Portuguese, and Chinese. Cookie management is much improved, as are various kinds of autocompletion in forms and the location bar.
This release is a huge improvement over the disastrous Netscape 6.0. If you're still using Netscape 4.x or IE, you may want to check it out. If you're using Netscape 6.0, you definitely need to upgrade. On the other hand I'm still partial to Mozilla.
James Strachan's posted dom4j 0.9, an open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework. This release adds full support for the Jaxen XPath engine, improved output via XMLWriter, JAXP and SAX filters, and various bug fixes.
eksmile 1.0 is a free-beer Xerces-J based XML/Schema/DTD editor.
The French translation of XML in a Nutshell has been published. The title is still "XML in a Nutshell". The ISBN is 2-84177-143-1. It costs 39 euros, and should be available from all the usual sources of French books including amazon.fr. I do notice, however, that Chapters seems to have stopped selling non-English books at their online store. Can any one recommend a good online store for French-language books in North America? Update: Aaron Staup Cope suggested I check out Camelot. They do sell French-language computer books, but they don't seem to have the French translation of XML in a Nutshell in stock yet.
The WAP Forum has released a draft of the WAP 2.0 architecture specification for public review. WAP 2.0 will be based on XHTML and CSS, rather than the current WML, though some sops will be thrown to backwards compatibility. WAP 2.0 also uses straight TCP/IP, HTTP/1.1, and TLS rather than WAP's existing custom protocols. This is all good and should help open up the WAP world to a broader variety of content providers. However, none of it addresses the fundamental flaw in WAP: cell phones are designed to support audio not text. Until this is fixed, WAP will continue to fail.
On the not so good side, WAP 2.0 promises that "Push technology allows trusted application servers to proactively send personalized content to the end-user, such as a sales offer for a product a person might be interested in buying, a new email notification, or a location-dependent promotion." In other words WAP 2.0 is spam-enabled.
Norm Walsh has posted version 1.4.2 of his XSLT stylesheets for Docbook. This is primarily a bug fix release. I've been using these to produce both the HTML and XSL-FO versions of Processing XML with Java.
Mozilla 0.9.3 has been released for the usual batch of platforms. This is primarily a bug fix release. I found Mozilla 0.9.2 to be a step backward from Mozilla 0.9.0. Hopefully, this release restores some of the stability that was lost in 0.9.2.
In related news, Galeon is a Gecko based browser specifically for Linux Gnome. Galeon uses the Gecko rendering engine, but replaces most of the rest of the browser built on top of that. It focuses on providing just a browser, no email client, chat program, news reader, calendar manager, or food processor. It's just a browser, and consequently loads much faster than megaware programs like Mozilla and IE. Because of licensing problems, it does require that you have Mozilla installed separately, however. It's not quite ready for nondeveloper end users yet, but it looks very promising for the future.
Version 0.5 of of the open source eXist XML database has been released. XML is either stored in the internal, native XML-DB or an external realtional database. The search engine has been designed to provide fast XPath queries, using indexes for all element, text and attribute nodes. This release introduces a pure Java implementation of the native XML storage backend, which is better optimized for efficiently storing, indexing and retrieving XML. The server now provides access by XML-RPC calls as well as HTTP, supports document collections and integrates well with Cocoon2.
Norm Walsh and O'Reilly have released DocBook: The Definitive Guide under the GNU Free Documentation License. The current version is a "work in progress"; but mostly covers document DocBook XML V4.1.2 with the EBNF, HTML Forms, MathML, and SVG modules. I've been using this as a reference while writing Processing XML with Java, which is itself written in Docbook XML 4.1.2.
The W3C has published working drafts of SVG 1.1/2.0 Requirements and SVG Mobile Requirements. I'm pleased to see that the requirements include "SVG may allow CSS units in the polylines, polygons, paths and transforms." and "To allow or include relevant enhancements from target domains such as GIS/Mapping, CAD/Design, Mobile, Printing and Web Design." Hopefully, someone on the working group realize that CAD and GIS Mapping require the ability to define sizes in real world units rather than onscreen units. There's a lot of other neat stuff here too, like rotations and word wrapping. I just pray that backwards compatibility with the brain damaged coordinate system in SVG 1.0 doesn't prove to be too big a millstone around SVG 2.0's neck.
ElCel Technology released version 0.12 of their XML Validator and Canonical XML Processor, command-line applications for Windows and Linux. This release adds HTTP proxy server support, more character encodings, and an up-to-date implementation of the latest OASIS XML catalog specification.
Bob Mcwhirter has posted SAXPath beta 4. SAXPath is an API (with default XPathReader implementation) for generic XPath parsing, which reports grammar productions in the form of call-back events. SAXPath is to XPath as SAX is to XML.
Roger L. Costello
and Roger Sperberg have published an ISBN
xsd:simpleType
definition. It defines the legal ISBN values for every country in the
world.
The Text Encoding Initiative Consortium (TEI-C) has posted. Comments are due by mid-September.
The Institute of Medical Informatics has released a new version of their DTD to XML Schema translator and xsbrowser tool for creating human readable documentation of XML document types represented from a schema.
The W3C CSS Working Group has posted
the first public working draft of
CSS3 module: Fonts.
New properties addes beyond those of CSS2 include
font-effect (effects include
emboss, engrave, and outline),
font-smooth
(whether or not to antialias fonts),
font-emphasize-style,
font-emphasize-position, and
font-emphasize.
Peter Murray-Rust and Henry Rzepa have announced a new suite of tools and demonstrations for the Chemical Markup Language (CML). These include:
JUMBO was the first XML browser/editor
and CML was perhaps the first serious XML application.
However, they've always been severely hampered by a lack of documentation.
This release is much improved in this area, but it's still not complete.
The new FAQ is very helpful, but all the links to further documentation
for the individual elements such as
atom
seem to be broken.
I've been spending a lot of time lately with Docbook and XSL-FO as part of the ongoing development of my next book, Processing XML with Java. To that end, I've been putting the various XSL-FO engines on the market through their paces. I'm trying to find one that will actually let me produce the complete, finished book from my Docbook source code and Norm Walsh's XSLT-to-XSL-FO stylesheet. I thought I'd share my experiences here.
So far, I've experimented with four different XSL-FO processors: the Apache XML Project's FOP, Sebastian Rahtz's PassiveTeX, the Antenna House XSL Formatter 1.1E, and RenderX's XEP. Two are implemented in Java, one in native Windows code, and one in TeX. FOP and PassiveTeX are open source. Antenna House and XEP are payware. Here are my experiences with each:
FOP was the first XSL-FO engine and is certainly the most popular. It's open source and far easier to install than PassiveTeX, the other open source alternative. However, of the ones I was able to actually test it produced by far the worst output. It had the most annoying formatting troubles. For example, it ate all the blank lines in my source code examples and put extra indentation at the front of the first line of each example. I've noticed that probably more than half of the bug reports on the Docbook-APPS mailing list about the Docbook XSL-FO stylesheets can actually be attributed to bugs in FOP. FOP is improving rapidly -- one major bug I noted in footnote handling was fixed in the last couple of weeks while I was performing my tests -- but it's clearly not even an alpha quality release yet. A lot of work needs to be done before FOP can be recommended for more than experimentation.
I was unable to get XEP to run. It was totally non-functional, and did not produce any output. I know some other people have gotten it to run -- the PDF version of the XSL specification was produced with XEP. However, it simply did not work for me at all. However good the XEP engine may be at converting XSL-FO documents to PDF, its horrible user interface and incomprehensible installation procedure eliminated it from my consideration.
PassiveTex did a very good job formatting most of my document. There were a few issues involving improperly scaled images, but those were easily fixed by adding some width attributes to my source XML document. Once that was done, the only major bug was a failure to properly calculate page numbers in the table of contents. There was also one quirky instance where the first bullet point in a list was not indented quite right, but this didn't seem to occur in other bulleted lists.
The downside to PassiveTeX is that it depends on a "decent modern TeX setup"; and TeX is invariably a nightmare. If my Linux distribution hadn't included TeX by default, I would have been lost. As it is, I consider myself lucky to have been able to get PassiveTeX running; and it still fails one time out of every two. This is probably due to TeX's unusual multipass architecture. You sometimes have to run TeX a second time to get the links and cross-references right. In my case, the first pass succeeds but the second pass invariably fails. Thus I never get proper cross-references to page numbers in the table of contents and elsewhere. Otherwise, the output produced is quite attractive
The Antenna House XSL Formatter produced very attractive output, on a par with that generated by PassiveTeX and much better than FOP's. I noticed no major flaws or cosmetic bugs. Antenna House also claims they're the only formatter able to handle mixed writing-modes such as "tb-rl" for Chinese/Japanese/Korean, though I didn't test that.
Most importantly, Antenna House had by far the easiest installation and the nicest user interface of all the formatters tested. More work is still needed, but at least I could conceive of giving this formatter to a non-programmer end-user. The others all have effectively non-existent user interfaces, and horrible installation procedures. The Antenna house formatter was the only one of the four that took me less than an hour from download to first use.
The downside to this otherwise excellent engine is that it's Windows only and based on Windows graphics primitives rather than PostScript or PDF. It displays on the screen very nicely, and prints nicely too. However, it does not produce a PDF document that I can send to my editor or a typesetter.
Bottom line: none of the formatters are yet suitable for producing a finished product. None of them can replace TeX or QuarkXPress. You might be able to publish a simple book with these, but you'd have to design your book and style sheet so that you avoided the bugs and unimplemented features of the processor. Antenna House probably produces the most polished output, and I'd use it if all I wanted to do was print out a document from my laser printer. However, since I need PDF files I can send to my editors and download to a typesetter, my choice for the time being is PassiveTeX.
Sun's released the Sun Multi-Schema XML Validator, a Java tool that validates XML documents against several kinds of XML schemas. It supports XML DTDs, TREX, RELAX Namespace, RELAX Core, RELAX NG and a subset of W3C XML Schema language. It can be used through a command-line interface or as a class library from inside your own programs.
The TM4J Project team has posted TM4J 0.5.0, an open source (Apache license) topic map engine written in Java. This class library provides a simple set of interfaces with which topic maps may be created and manipulated as well as imported from and exported to XML files using the XTM syntax.
The W3C CSS Working Group has published an initial working draft of CSS3 module: the box model.
This is a direct outgrowth of the CSS Level 2 box model. There are a few
new properties, mostly to deal with vertical writing. These include
display-model,
display-role, and
float-displace as well as
new
:expanded and
:collapsed pseudo-classes.
In addition, some CSS2
properties have been subdivided into more fine-grained properties,
though the old CSS2 properties remain as shorthands.
Ronald Bourret's posted a list of XML data binding resources based on some initial work by Sean Sullivan and Brendan Macmillan.
Altova has posted a public beta of XML Spy 4.0, a $199 payware XML IDE for Windows. New features in version 4.0 include expanded ODBC database access functionality, enhanced user interface customization, a new plug-in architecture for 3rd party developers, support for the final XML Schema Recommendation, and a more WYSIWYG editor. As usual, beta testers who volunteer their time and systems to help debug XMLSpy will most likely receive bupkus for their efforts, and still have to pay $199 for the final release.
I've posted XML Protocols, Chapter 2 of Processing XML with Java. This chapter covers XML-RPC, SOAP, and related technologies. As always your comments are much appreciated. Just email them to me at elharo@ibiblio.org. Thanks!
Michael B. Allen's posted domc 0.3, an opens source implementation of the Document Object Model Level 1 (DOM1) in ANSI C. It depends on the the Expat XML Parser Toolkit.
The Apache Cocoon team has posted the 2nd beta of Apache Cocoon 2.0. "Apache Cocoon 2.0 is a complete rewrite of the Cocoon XML publishing framework that is supposed to remove all those design constraints that emerged from the Apache Cocoon 1 experience....This release marks API stability of the project. The next release will primarily focus on documentation."
James Strachan's posted version 0.7 of dom4j. dom4j is an open source library for working with XML, XPath, and XSLT on the Java platform using the Java Collections Framework with full integration with DOM, SAX and JAXP. This release adds support for the SAXPath API for the parsing of XPath expressions and fixes various bugs.
The W3C Synchronized Multimedia Working Group has published the Proposed Recommendation of SMIL Animation. This spec describes "an animation framework as well as a set of base XML animation elements suitable for integration with XML documents. It is based upon the SMIL 1.0 timing model, with some extensions, and is a true subset of SMIL 2.0." The review period ends August 16, 2001.
IBM's alphaWorks has released UDDI Registry, a "UDDI-compliant registry for Web services in a private intranet." It runs on Windows NT, 2000, and Linux.
Netscape's released Communicator 4.78. This is a minor update that improves mousewheel support on Windows, improves support for Sun Java plug-in and runs on Solaris 2.8 and AIX 5.x. A few bugs are fixed. In addition, on Windows AOL Instant Messenger is upgraded to version 4.3 Flash Player to version 5. There's no public support for XML as is customary in the 4.x Netscape series.
The W3C SVG Working Group has published the Proposed Recommendation for Scalable Vector Graphics (SVG), an XML application for two-dimensional line art such as cartoons, blueprints, technical drawings, businenss graphics, or anything else you'd produce with Visio/KIllustrator/CorelDraw/PowerPoint/etc. There's no change document, and I haven't read through the entire spec yet, but I don't expect the changes are too major.
I am disapoinnted that they didn't change the underlying model for how coordinates are measured. I didn't really expect them to. Nonentheless I think the definitions used for pixels, inches, user units, and the whole coordinate space are feet of clay for the rest of the specification. They've already been proven to confuse developers, and I think they're going to make SVG less generally useful than it should be. In brief, it's impossible to assign an absolute size to a picture. I cannot say that the chair I draw is one meter tall and half a meter wide. Thus there's no way to guarantee that the chair I draw will fit in the door of the house you draw. What I think is needed is a way of specifying the actual physical dimensions of a picture, and a preferred scale factor for moving that drawing onto the screen. The model they've chosen is suitable for single-file line art on Web pages, but not for more complex technical drawings and pictures that are built from many different pieces by many different artists. Some of the problems I noted are under consideration for changes in SVG 2.0. However, the problems are rooted so deep in the foundations of SVG that I don't know that they can be fixed in a backwards compatible way.
I am looking for native speakers of Khmer, Burmese, Amharic, or the other Ethiopic languages who have some experience with XML and who are willing to answer a few questions about your use of XML and the need for native markup in these languages. Alternately, if you're not a native speaker, but you have spent a significant amount of time in Cambodia, Myanmar, Ethiopia, or Somalia working with or teaching computer related technologies, I'd also like to talk to you. If you fall into any of these categories, please drop me a line at elharo@ibiblio.org, and I'll send you my questionnairre. Your answers will be used as input for the Blueberry efforts at the W3C. Thanks.
IBM's alphaWorks has updated their P3P Policy Editor to fix "numerous installation problems" and add a platform-native program to launch the P3P editor.
Does anybody know a quick way to specify in a W3C XML Schema Language
schema that an element
(call it
value) can have type
xsd:double except for
Inf, -Inf, and NaN. In other words I want to restrict it to
all legal IEEE 754 values except Inf, Nan, and -Inf.
I could use a pattern, but frankly that seems like overkill,
especially given all the different forms floating point numbers can take.
In essence, i'm looking for a reverse union. I want to say that every
xsd:double
except these three values is allowed.
Suggestion to elharo@ibiblio.org.
Thanks!
Nenie XML 0.1 is a non-validating XML parser for Eiffel. Unlike eXml, Nenie XML is written in pure Eiffel. Nenie XML does not support SAX or DOM, relying on its own API instead.
The W3C CSS Working Group has published drafts of two new modules for CSS Level 3, Values and Units and Cascading and inheritance. The Values and Units module "describes the various values and units that CSS properties accept. Also, it describes how 'specified values', which is what a style sheet contains, are processed into 'computed values' and 'actual values'." This version of the module does not introduce any new features, merely rewriting the equivalent parts of CSS level 2 in the form of a CSS3 module. However, new features are planned for a future version. The Cascading and inheritance module ."
Ken North reports that Camelot Communications has laid off its staff and cancelled all future events including XML DevCon London, and iFive (XML DevCon, SQL Summit, Web Services Summit) later this year.
The W3C/IETF joint XML Digital Signature Working Group has posted the first working draft of Exclusive XML Canonicalization Version 1.0. This is a revised canoncial form that is supposed to allow individual elements to be cut and paste from one document to another while maintaining the same canoncial form. Currently, the canonical form of an element can change based on namesapces in scope that are not actually used. Thsi is a problem for applications that want to sign only a part of a document such as the Body of a SOAP message rather than the entire document. The problem here is real. It's not, however, clear to me that the propsed solution actually works in the face of namespace declarations used in attribute values (XSLT, Schemas) and element content (SOAP).
IBM's alphaWorks has updated their XML Parser for Java with support for the W3C XML Schema Recommendation 1.0. It also includes updated JAXP support and other enhancements. To a very good approximation, this is a repackaged version of Xerces-J (which IBM did most of the work for anyway.) In brief, if you want to pay IBM to support your parser, use this. Otherwise use Xerces-J.
Eric van der Vlist has released an RTF output method for the open source XT XSLT processor. This is a very simple serializer that writes a XML representation of RTF as a RTF document.
Opera Software has posted a beta of the Opera 5.12 web browser for OS/2. Among many other features Opera boasts native support for XML and pretty good support for CSS Level 2.
libxslt, the Gnome XSLT library, has reached version 1.0.0. libxslt is believed to implement all the XSLT-1.0 constructs, support a few "common" extensions and provide an extension framework. It also includes a simple to use command line interface 'xsltproc' with an XSLT profiler. This is free software available under the LGPL and an alternative that allows it to be easily embedded in commercial products. It is written in C and should port easily to most Unixes and perhaps Windows.
IBM's alphaWorks has updated their XML Schema Quality Checker to version 1.1.85 to fix various bugs and improve Solaris 2.7 and Windows 98 usability.
The W3C XML Protocol Working Group has published two new working drafts on the XML Protocol Abstract Model and SOAP Version 1.2. SOAP." I'm disappointed that this draft fixes exactly none of the problems I noted in SOAP 1.1 including:
However, perhaps I can push to get some of this fixed before SOAP 1.2 goes gold. I'm writing Chapter 2 of Processing XML with Java right now, which is all about XML Protocols and SOAP, so I'm spending a lot of time thinking about this sort of stuff.
Beta 7 of JDOM has been posted. JDOM is a Java-centric API for processing XML documents. This release adds:
createXXX()methods to simplify subclassing)
detach()method for all tree objects
setName()and
setNamespace()methods on
Element
The API is in general not compatible with beta 6, so you will need to rewrite your code to upgrade to beta 7. The same basic functionality is there so mostly it's a matter of changing some method names.
Software AG's released QuiP, a prototype of XQuery, the W3C XML query language. QuiP can be used either with text-based XML files or for queries against the Tamino native XML database. Quip conforms to the June 7, 2001 working draft of XQuery. It sample queries and data files, syntax diagrams in the online help, and a GUI.
Howard Katz has released XML Query Engine 1.0, a $625 full-text search engine component for XML based on XQuery. XML Query Engine is a compact (roughly 160K), embeddable component written in Java. It has a straightforward programming interface that lets you easily call it from your own Java application. Collections to be searched are limited to 32,768 documents, each of which can contain up to 32,768 elements.
The XML Benchmark Project has released Xmark, a framework intended to help analyze XML query processors. The benchmark consists of
For the second chapter of Processing XML with Java, I'm looking for simple examples of public services that expose an XML-RPC interface. The ideal service would be one that accepted a stock symbol and returned the current price. Anything else that was equally simple would also be helpful. (I found such a thing in SOAP but not XML-RPC.) I'm aware of the services at UserLand and Meerkat. Anything else you can point me to would be appreciated. As usual, just email suggestions to me at elharo@ibiblio.org. I've already received a number of very helpful comments on and corrections to the first chapter that I'll be incorporating soon.
Late Night Software's released XML Tools 2.2, an expat based XML parser for Applescript. This release adds native support for MacOS X.
Michael Kay's released version 6.4 of his SAXON XSLT processor written in Java. This release adds support for JDOM, speeds up transformations by about 20%, and restores compatibility with Java 1.1 and the Microsoft VM. Thus Instant SAXON (the Windows executable version) works again.
James Strachan has released version 0.6 of
dom4j, an open source library for working with XML,
XPath and XSLT in Java.
I've received a couple of requests to cover dom4j in
Processing XML with Java, and
I'm thinking about it.
It may depend somewhat on time and page count.
SAX, DOM, and TRAX are the must-carries for this book. JDOM is probable.
Other APIs will depend on available space and reader interest.
I would like people's input on what to cover beyond the basics,
though please realize I probably won't have the time or space to cover
everything. Thus adding
dom4j, ElectricXML, or other APIs might mean dropping JDOM.
Also, please keep in mind that topics not specifically related to writing
Java programs to process XML are out of scope for this book and won't be covered.
Thus I will not, for example, cover XPath 2.0 or XQuery. You can always email
your suggestions and commments to me at
\.
Rick Jelliffe's released the Topologi Schematron Validator, a GUI interface for validating XML documents against DTDs, Schemas, and Schematrons. This product runs only on Windows and MSXML 4.0 is required.
I'm pleased to announce my latest book project, Processing XML with Java. I'm more excited by this project than I've been by any book in a long time. This is a comprehensive tutorial covering all aspects of Java programs that read and write XML documents. It picks up where the XML Bible left off, and covers SAX, DOM, JDOM, XML-RPC, SOAP, JAXP and as many other acronyms as I can cram into seven hundred pages.
Processing XML with Java will be published by Addison-Wesley next Spring. So why am I announcing it now? Because the entire book is going to be written and posted here on Cafe con Leche first! Every word, every figure, every piece of code is going to be published in HTML right here. Chapter 1, XML for Data, is available now. Other chapters will follow about one per week. The entire book will be updated and corrected several times a day as I write it.
There's no fee or registration required to read the book. Just start reading at page 1 and go from there. I do hope you'll send in any comments or corrections you have as you read, and I certainly hope you'll consider buying a paper copy next year when the book is released; but for now the book is completely free. In the immortal words of Abbie Hoffman, "Free means you don't have to pay."
Opera Software has released version 5.12 of its namesake Opera web browser for Windows. This is mostly a bug fix release witha few minor new features. Opera features pretty good support for XML+CSS.
Mozilla 0.9.2 has been released with the usual support for XML, CSS, XSLT, etc. Mostly this is a bug fix release. I've been using Mozilla as my primary browser on Windows for a couple of months now, and I've been quite satisfied with it. Maybe it's time to switch my Mac over as well. Can anyone comment on the Applescript support in Mozilla for the Mac?
Log Markup Language (LOGML) is an XML application for describing log reports of web servers based on the eXtensible Graph Markup and Modeling Language (XGMML).
The W3C XML encryption working group has published the first public working drafts of XML Encryption Syntax and Processing and Decryption Transform for XML Signature.
XML
Encryption
specifies a process for encrypting data using any algorithm or key length
and representing the result in XML. The data encrypted can be any binary
data at all, though XML documents, individual XML elements,
and XML element content can also be encrypted.
The encrypted data is stored in an
EncryptedData element
which either contains
the Base-64 encoded encrypted data
or points to it with a URI.
A "decryption transform" allows verification of
XML Signatures verification when both signature
and encryption operations are performed on an XML document.
The W3C has approved XML Base and XLink as official recommendations. I haven't read every word of the specs yet, but so far it doens't look like they're any significant changes since the proposed recommendation. Everything in the XLink Chapter from the XML Bible, second edition, should still be accurate.
IBM's released version 3.5.0 of their XML for C++ parser. This supports SAX2 and DOM2.
Sun's posted version 0.92 of the Java API for XML Messaging (JAXM) Specification. (PDF format as usual.) This is baiscally a Java API for SOAP 1.1.
Microsoft's posted a public beta of Internet Explorer 6 for Windows. This release features support for numerous XML and XML-based technologies including P3P, DOM1, CSS1, XSLT 1.0 (allegedly) and more. Windows 98, NT 4.0, or Windows 2000 is required. Windows 95 does not seem to be supported.
The W3C User Agent Accessibility Working Group has posted new drafts of User Agent Accessibility Guidelines 1.0 and Techniques for User Agent Accessibility Guidelines 1.0.
I've updated my DOM-based XIncluder to fix
a bug involving including XML documents with
parse="text".
The fix is implementation only. The API is unchanged.
In brief some < and &
characters were getting double escaped so they
came out as
< and
&
instead of
< and
&.
The XML Apache Project has released version 1.4.1 of the Xerces-J XML parser (my parser of choice.) Besides bug fixes, 1.4.1 adds:
xsi:schemaLocationand
xsi:noNamespaceSchemaLocationattributes in the instance documents.
James Strachan's posted dom4j 0.5. dom4j is an open source library for working with XML, XPath and XSLT on the Java platform using the Java Collections Framework with full integration with DOM, SAX and JAXP. This release fixes assorted bugs and adds:
NodeComparatorfor comparing documents by value
DocumentHelper.parseText( String );
Branch.normalize()method for normalizing
Textnodes
Element author = element.addElement( "author" ) .addAttribute( "name", "James" ) .addAttribute( "location", "UK" ) .addText( "James Strachan" );.
The second proposal for breaking backwards compatibility with existing parsers is much more serious, and requires a more thoughtful response..
I've posted Chapter 24, Schemas, from the XML Bible second edition. This updated version corrects some errors from the printed book as well as adding additional new material about binary data types, simple type derivation, and attribute declarations. Overall, this is a complete introduction to the W3C XML Schema Language. Enjoy!
Elcel Technology has posted version 0.11 of their XML command-line tools, an XML Validator and Canonical XML Processor. These run on Windows and Linux platforms. Version 0.11 adds support for entity resolution using XML catalogs. Registration is required.
The United States National Institute of Standards and Technology (NIST) has published published several hundred tests for XSLT, XPath, and XSL Formatting Objects. These will eventually be integrated into the official OASIS XSLT/XPath suite.
Adobe's localized their SVG Viewer browser plug-in to eleven new languages. It now supports English, Danish, French, Italian, Spanish, Dutch, Norwegian, German, Swedish, Portuguese, Chinese, Japanese, Korean, and one language I couldn't identify, Suomeksi. (Update: Greg Phillips tells me that "Suomeksi" is the Finnish word for "Finnish".)
Matt Seargent's released version 1.4 of AxKit, an application server module for Apache, designed for building web sites using server-side transformations of XML based content. It contains many features for delivering the same content to different devices, and also for building dynamic content for different devices. It features a number of transformation and language modules including XSLT, Apache XSP and XPathScript. AxKit also implements a high performance cache architecture that ensures cached content can be delivered at close to static HTML speeds.
CL-XML is a collection of Common LISP modules for XML parsing and serialization. XPath and XQuery modules are also included.
Ovidiu Predescu's XSLT-process is a minor mode for GNU Emacs/XEmacs which transforms it into a powerful editor with XSLT processing and debugging capabilities. With this mode you can:
Either SAXON or Xalan-J is required.
The dbXML project has released version 0.9 of the dbXML Core XML Database, a native XML database designed to manage large collections of small XML documents. The server supports XPath queries and uses an implementation of the XML:DB XML Database API for development of client applications. Features added include an XML:DB XUpdate implementation for updating XML documents, SAX support in the API and a compression mechanism to increase performance between the client and the server. The server is now considered feature complete. Source code for the dbXML Core is now available under an Apache style license.
The W3C Document Object Model Working Group has posted the first public Working Drraft of Document Object Model (DOM) Level 3 XPath Specification Version 1.0. This describes a standard XPath interface for DOM parsers. There isn't as much here as I'd hope. There are methods for converting DOM nodes to XPath booleans, strings, numbers, nodes, and node sets but no functionality for finding the nodes that match a given XPath expression within a document. Maybe TRAX can pick upnthe slack there?
The XML Apache Project has released Xerces-C 1.5.0 with partial support for the W3C XML Schema Language. However, this is not nearly as complete as the support in Xerces-Java Support is roughly as follows, according to the Xerces-C web page:
- Partial Simple type support
- Yes: atomic simple type
- No: union and list
- Partial Complex type support
- Yes: choice, sequence
- No: group, all
- Element and Attribute Declaration
- No: any/anyAttribute
- SubsitutionGroup
- Subset of Built-in Datatypes
- Primitive Datatypes: string, boolean, decimal, hexbinary, base64binary
- Derived Datatypes: integer
- xsi Markup
- Yes: xsi:nil
- Yes: xsi:schemaLocation and xsi:noNamespaceSchemaLocation
- No: xsi:type
Additional Experimental Features (not tested and subject to change, use as is)
- Complex type derivation support (simpleContent and complexContent).
- Element and attribute re-use using "ref".
- Include support
- Import Support
Other features in the Schema recommendation such as "redefine", "identity constraints" and others which are not mentioned above, are not supported yet. Also, particle and model group constraint checking is not yet fully implemented. But development is continuing and we target to implement all the features of the current XML Schema Recommendation before end of this year. Please note that the date is tentative and subject to change.
Netscape's posted the first public beta of version 6.1 of its namesake web browser for Mac, Linux, and Windows. The main new feature in this release is allegedly much improved stability compared to the roundly panned Netscape 6.0.
RELAX Next Generation (RELAX NG) is an XML schema language being derived from combination of Murato Makoto's RELAX and James Clark's TREX. The OASIS RELAX NG committee has just published a RELAX NG tutorial. James Clark has released JING,a RELAX NG validator written in Java.
The W3C XML Query Working Group has released five new working drafts covering the XML Query Language:
Particularly notable is the unification of the XPath 2.0 and XQuery data models, and XQueryX a well-formed XML encoding of the more SQL like XQuery language.
The W3C Forms Working Group has posted a new working draft of XForms 1.0. XForms is a totally remodeled design for Web forms that work not just in traditional browsers but also in television sets, personal digital assistants, cell phones, and even paper. It depends on XML and schemas.
Mozilla 0.9.1 has been released for the usual trio of platforms (Linux, Windows, Mac). This release fixes a number of important bugs. Feature-wise this release is the first to support XSLT, "although the implementation is still incomplete and has bugs." In addition, the Modern skin has been overhauled with a lighter and smoother look with all new icons and widgets. The new status bar which combines the old taskbar and statusbar into one toolbar thus freeing up screen real-estate. IBM contributed bi-directional text support for Hebrew and Arabic, although Arabic shaping only works on Windows just now.
The W3C Document Object Model (DOM) Working Group has published a revised working draft of Document Object Model (DOM) Level 3 Abstract Schemas and Load and Save Specification. "Abstract Schema" is the new term for what was formerly known as "content model". It includes DTDs and W3C XML Schemas and potentially other schema languages as well.
The W3C has published a note about XML Linking and Style that discusses the integration of XSL with XLinks, among similar issues. The question of whether links are styles or semantics is one that's been causing strife inside W3C working groups for some time. Of course the real answer is "Yes". Style and semantics aren't nearly as cleanly separable in the real world as they are in Tim Berners-Lee's vision of the Web. This is just one manifestation of that problem.
I've updated my DOM and JDOM XInclude processors to support the latest May 5 Working Draft of XInclude. This means you'll need to change you XInclude namespace URI to. The DOM version is working again, though you'll need to use Xerces 1.4 or later. Other parsers may work as well. Earlier versions of Xerces do not.
I think this is now an accurate implementation of the full XInclude specification except for XPointer support. This required changing the API to work primarily with lists and node lists rather then directly with elements and nodes. However, the API should not need to change again to support XPointer. Merging in XPointer support should be an internal implementation detail. The software processes my files successfully, but formal testing has been minimal so let me know if you spot any problems.
The W3C Synchornized Multimedia Working Group has elevated Synchronized Multimedia Integration Language (SMIL) 2.0 to a Proposed Recommendation. SMIL is an XML application for interactive multimedia presentations. It's suported by RealPlayer and various other tools. SMIL 2.0 adds a lot of features to SMIL 1.0, and divides the DTD into a modular framework. It also provides a schema for SMIL. Proposed Recommendation review ends July 5, 2001.
The W3C Document Object Model (DOM) Working Group has posted a
revised working draft of
DOM
Level 3 Core. This describes the basic
Element,
Node,
Attr, and other interfaces
used in DOM. In this arena, DOM3 mostly fills a few holes in DOM2 without really changing very much.
Sun's posted the Java Architecture for XML Binding Working Draft (JAXB, previously known as Project Adelard) specification Version 0.21. I must admit this strikes me as a fairly pointless endeavor. I just can't figure out why I'd want to use this instead of SAX/DOM/JDOM/dom4j. But maybe I'll feel differently once I've had a chance to actually look at it. An early accecss implementation is available on the Java Developer Connection (registration required).
I've posted four chapters from the recently released second edition of the XML Bible here on Cafe con Leche:
These are the complete updated chapters that appear in the printed book. All have been significantly revised since the first edition two years ago. The XPointers chapter in particular has been updated from the revised first edition chapter I've had posted here for the last year or so, though all four are somewhat more current than what I've previously published. I also plan to publish one more chapter, Schemas, here in a month or two.
I used Upcast to convert the Word documents to XHTML, and then used XSLT to convert the XHTML into something readable. There may still be a few bugs in the process. The pictures are a little small and fuzzy, but should be mostly legible. I'll fix that when I get a minute. Otherwise, please let me know if you spot any formatting idiosyncracies.
I'm still looking for a good Word-to-XML/HTML converter. Upcast gets me part of the way there, but a very complex XSLT stylesheet was still needed to finish the job. I ruled out Logictran's RTFConverter even though it did a much better job than Upcast of producing readable HTML on my first pass because it lost all information about styles. My Word documents use styles very heavily to allow almost semantic markup of documents, and I can't afford to convert that into pure visual presentation.
In possibly related news, Adobe's posted a beta of Save As XML Plug-In for Macintosh for that adds five file convversions to Acrobat 5.0 :
This plug-in requires tagged PDF file, whatever that is. According to Adove, "A tagged Adobe PDF file can be generated from Microsoft Office 2000 applications, by using the Acrobat 5.0 Web Capture feature to convert a website to Adobe PDF, by using the Make Accessible Plug-In, or by sending PostScript+pdfmark through Acrobat Distiller. The structure which the creating program embeds in the PDF file will come back out in the XML or HTML generated by the Save As XML Plug-In."
I've posted the main Web pages for the XML Bible, 2nd edition. Besides the usual "Buy this book" propaganda, you'll find the complete source code for all code listings in the book.
IBM's alphaWorks has released XML Registry/Repository, a data management system that provides services for XML artifacts including DTDs, schemas, stylesheets, and instance documents. User can use XRR to obtain an XML artifact automatically, search or browse for an XML artifact, deposit an XML artifact with or without related data, and register an XML artifact without deposit. Users can search of registered objects based on their metadata. It's not totally clear from IBM's site, but this appears to be some sort of service running on IBM's servers, rather than a software product you download and install within your own organization, though apparently there is client software you need to use to access IBM's servers.
The W3C HTML Working Group has released the final recommendation of XHTML 1.1, Module Based XHTML. With just a couple of exceptions, the language described here is the same as HTML 1.0. However, the DTD structure is much more amenable to merging with other XML applications like Scalable Vector Graphics and MathML.
The Mozilla Project's released a new beta of Fizilla, a MacOS X port of the Mozilla web browser. I haven't tested it, but I assume it has roughly the same level of XML support as Mozilla 0.9.
Opera's posted a new beta of their eponymous Opera web browser for the Macintosh. I haven't tested it, but I assume it has roughly the same level of XML support as Opera 5 for Windows. Unicode and Java support are lacking though.
Representatives from a number of Linux distributions and major development projects are in the process of developing the XML/SGML addendum to the Linux Standards Base specification. A primary focus of the present discussion concerns the methods used by XML tools to locate resources, how these differ from methods used by current SGML tools, and the implications of the differing SGML/XML requirements regarding directory structures, configuration issues, etc. If you'd like to contribute to the discussion, please subscribe to the LSB-xml-sgml mailing list.
James Strachan's released dom4j 0.4, an open source Java library for processing XML. This release includes
Microsoft's released an update to Internet Explorer 5.1.1 for Mac OS X. This browser supports direct display of XML documents with attached CSS style sheets. It is a fully Carbonized application.
I'm pleased to announce the release of the much anticipated second edition of the XML Bible. It's available now from Amazon, FatBrain, and other purveyors of computer books. This edition was extensively revised on almost every page. Every section and example was brought completely up to date with the state of the art in XML in 2001, and many new chapters were added. There are four completely new chapters in this edition covering:
Many other chapters were totally revised to bring them up to date with the latest version of various specifications, including:
I am now happy to say that this book is almost completely in-sync with all the latest XML specifications including the second edition of XML 1.0, XSLT 1.0, XPath 1.0, and the latest drafts of XLink and XPointer. (The one exception, unfortunately, are a few bugs in the later parts of the schemas chapter, particularly with regard to attribute declarations. That's the penalty for working on the bleeding edge. But even so, the vast majority of the examples in the schemas chapter are completely current with XML Schemas 1.0. I'll post the updates for the schemas material here soon.)
Perhaps most importantly, I rewrote almost every word, sentence, and paragraph to make the exposition clearer, the examples shorter, and the XML terminology more accurate. Mixed content finally gets its due. External DTDs are now emphasized in preference to internal DTDs, and everywhere I'm careful to distinguish between document type definitions and document type declarations. Mozilla and Opera are now used throughout the text as well as Internet Explorer. Since the first edition was released a year and a half ago, XML has gone from a bleeding edge technology to a solid. well-tested, and well-proved foundation of many of today's technologies. The second edition of the XML Bible reflects the increased maturity and stability of XML.
This is in every way a much better book than the first edition. If you liked the first edition, you'll love this edition. If you didn't like the first edition, you may find that the second edition fixes what bothered you about the first. The second edition is still only $49.99 even though it's more than 200 pages and 20% longer than the first edition. There is unfortunately no upgrade path, as is the case for most paper books. However, I will be posting some of the updated chapters here at Cafe con Leche in the near future, and the usual discounts do apply. Amazon and FatBrain are selling it for $39.99. Bookpool doesn't have it in stock yet but should get it soon. Amazon almost always sells out of my new books within a few hours of me announcing one here, but generally gets more instock much more quickly than they say they will. It will not take 4-6 weeks to get your copy. Many brick-and-mortar bookstores still have the first edition on the shelves. You can recognize the second edition by the robot on the cover. (A special prize goes out to the first person who successfully guesses just what that robot has to do with XML and the content of the book.) If you need to special order it, the title is XML Bible, 2nd Edition. The ISBN number is 0-7645-4760-7, and it's written by me, Elliotte Rusty Harold.
The W3C CSS Working Group has posted a new working draft of the Introduction to CSS3. The changes appear to be quite minor.
The XML Apache Project has released version 1.4 of Xerces-J,
an open source XML parser written in Java.
The big new feature in this release is support for
the final Recommendation of W3C XML Schemas.
Previous versions only supported the out-of-date
Candidate Recommendation from October of last year.
There are still a few bugs in schema support, but all the big holes
in schema support have been filled.
The two remaining major issues are
xsd:any and
ID type elements.
The Apache Batik team has released Batik 1.0, an SVG viewer written in Java. Batik 1.0 supports most of the static SVG features, linking, and some scripting. New features since the last beta include:
There's a new hidden feature on Cafe con Leche and Cafe au Lait this month.
If you view the source code for this page you'll notice that
the individual dates all have
id attributes like this:
<dt id="news2001May15">Tuesday, May 15, 2001</dt>
This means you can now link to the news from a particular date, at least in an HTML
4.0 compatible browser that supports
id attributes
as fragment identifiers.
(Netscape 4 has problems with these.)
I started adding these on May 8. Eventually I may try to figure out a regular expression that
will let me add this to all
the old news, but the format should be fairly consistent going forward:
id := "news" + 4digitYear + monthName + 2digitDate
Version 0.4 of the eXist XML database has been posted. eXist provides pluggable storage backends, storing XML either in a relational database or using a native backend. eXist has it's own XPath implementation with full text support. Changes since version 0.3 include:
The W3C XML Core Working Group has posted the last call working draft
of XML Inclusions (XInclude) Version 1.0.
XInclude allows you to build large XML documents out of smaller XML documents that
are themselves well-formed and potentially valid.
Changes in this release are fairly minor.
The big one is that the namespace is now and the default prefix is
xi
(though as always the prefix can change as long as the namespace
URI remains the same). The functionality and model seems essentially the same.
The W3C CSS Working Group has published two new modules from CSS Level 3:
The dbXML project has posted version 0.6 of the dbXML Core XML Database. dbXML Core is an open source native XML database designed to manage large collections of XML documents. The server supports XPath queries and uses an implementation of the XML:DB XML Database API for development of client applications. The source code has been released under the GNU Lesser General Public License. This release focuses on code cleanup, bug fixes and documentation.
The W3C XML Core Working Group has promoted the XML InfoSet to Candidate Recommendation. This specification "defines an abstract data set called the XML Information Set (Infoset). Its purpose is to provide a consistent set of definitions for use in other specifications that need to refer to the information in a well-formed XML document". There do not seem to be any functional changes in this draft. Comments are due by June 15.
The Institute for Applied Information Processing and Communications (IAIK) has released the first public beta of the IAIK XML Signature Library (IXSIL) 1.0. IXSIL is a toolkit that enables Java developers to create and verify XML digital signatures. IXSIL is based on the April 19, 2001 W3C/IETF Candidate Recommendation of XML-Signature Syntax and Processing.
James Strachan's posted version 0.3 of dom4j, an easy to use, open source Java library for processing XML with Java. This is primarily a bug fix release with some performance enhancements. New features include:
OutputFormat.createPrettyPrint()method to create standard pretty printing of XML documents
matrix-concat()XPath extension function
Version 0.3 of the XSLT Standard Library has been released. The XSLT Standard Library is a collection of commonly-used templates written purely in XSLT.
IBM's alphaWorks has updated their Web Services Toolkit to version 2.3. This release adds a private UDDI registry and enhancements to the WSDL Generation Tool to support COM. WSTK 2.3 is WSDL 1.1 spec compliant. SOAP encryption, UDDI4B (UDDI for Browser), and a Digital Signature handler are also included.
The following warning comes from the USISPA, the US Internet Service Providers Alliance, and was forwarded to me by someone who generally seems to know what he's talking about. Please read, and then call your congressman. The bill itself is available on Thomas.
Date: Friday, May 11, 2001 6:43 AM
From: "Debra Sweezey" <dsweezey@yahoo.com>
Fourthought has posted an alpha of 4EXSLT, an add-on module for the open source 4Suite that implements the entire initial collection of EXSLT functions and elements for the 4XSLT processor. EXSLT is an effort by the community of XSLT users and implementers to develop a common collection of XPath extension functions and XSLT extension elements that provide useful facilities beyond that provided by the official XSLT recommendation. The initial set of extensions includes tools for math, set manipulation, writing XPath extension functions in XSLT itself, multiple document output, conversion to node set and checking XPath object type.
Mozilla 0.9 has been released. New features in 0.9 include:
MacOS 8.6 or later, Windows 95 or later, or a reasoonably current Linux are required.
I've been using Mozilla 0.8.1 a lot lately, and found it very stable and useful. This is certainly the best XML browser on the market, bar none. Right now it supports XML, DOM2, CSS, and HTML 4. In the future I suspect it to get even stronger with native suport for real XSLT, MathML, SVG, XHTML, and more. It's gotten a bad rep because a lot of people confuse it with Netscape 6, a truly abominable product on the order of Microsoft Bob. However, although Mozilla and Netscape 6 are derived from the same code base, they are actually quite different browsers. Mozilla is far more stable and less spam-ridden than Netscape 6.
Michael Kay's released version 6.3 of SAXON,
an XSLT processor
written in Java. Version 6.3
implements the
javax.xml.parsers package in JAXP 1.1 as well as the
javax.xml.transform. Furthermore,
Saxon now supports the EXSLT modules
Common, Math, Sets, an Functions. The full list of extension
functions is:
exslt:node-set()
exslt:object-type()
math:min()
math:max()
math:highest()
math:lowest()
set:difference()
set:intersection()
set:distinct()
set:leading()
set:trailing()
set:has-same-node()
plus two new elements:
func:function
func:result
Jonathan Borden's written an an HTTP Extension Framework Namespace for RDDL."
Sun's released the Sun XML Datatypes Library, a Java class library for validating strings against W3C XML Schema simple types and converting those strings into Java objects.
IBM's alphaWorks has released Xeena for Schema, a syntax directed XML editor for editing schema-valid XML documents. This only supports a subset of the October 2000 Schema Candidate Recommendation. It does not support the XML Schema Language 1.0 released a few days ago.
Fourthought, Inc. has released version 0.11 of 4Suite, a collection of open source tool for processing XML in Python. It provides support for XML parsing, several transient and persistent DOM implementations, XInclude, XPath expressions, XPointer, XSLT transforms, XLink, RDF and ODMG object databases. CORBA is no longer required. There are many usability, documentation, performance and architectural improvements.
Fourthought, Inc. has also released version 0.11 of 4Suite Server, an open source XML data server. It features an XML data repository, a rules-based engine, and XSLT transforms, XPath and RDF-based indexing and query, and XLink resolution.
Eric van der Vlist has posted XSLTunit 0.1, the first alpha release of an open source framework to do unit testing of XSLT templates.
Josh Lubell of the National Institute for Standards and Technology has released XSLToolbox, an open source collection of XSLT stylesheets that currently contains two tools:
Henry S. Thompson and Oriol Carbo have initiated work on the W3C XML Schema Test Collection to coordinate "test suites for W3C XML Schema processors created by different developers." If you've got tests to contribute, send email to www-xml-schema-tests@w3.org.
Tim Berners-Lee has approved the W3C XML Schema Language as an official recommendation. It is available in three parts:
At first glance, there do not appear to be any significant changes since the last Proposed Recommendation.
I've updated my XInclude processor to version 1.0d4.
This is
written in Java and requires the current CVS version of JDOM.
Today's release doesn't add a lot of functionality.
About the only new feature is that comments and processing
instructions that are outside the root element of an included document
are now included.
However, it makes major modifications to the API.
The big difference is that the
resolve() method now returns
a
List of nodes instead of an
Object that is a node.
This is necessary prerequisite for XPointer support
because an XPointer may point to more than one node.
Update: I just noticed that my latest changes to XIncluder exposed a bug in JDOM. The effect is that included elements are included in front of the elements they're supposed to be after. I've submitted a patch for the JDOM bug. Assuming it's accepted and integrated, the new XIncluder should work as expected.
I've updated my XInclude processor. This is written in Java and requires the current CVS version of JDOM. This release fixes one major bug (the position of comments and processing instructions outside the root element is now maintained). Furthermore, I've cleaned up the code and rewritten a lot of the JavaDoc. Most importantly, this release is now more conformant with the Working Draft XInclude specification. In particular when it encounters an error with an included document, it throws an exception and gives up. It no longer puts an error message in the including document. (I still think this should be a user configurable option. Maybe in the next release.) The one major feature left to add is XPointer support. I've got a pretty good idea now how to do this, and hope to get to it soon.
I also fixed the DOM version. However, in the process I discovered some bugs in Xerces-J involving cloning documents. I have reported the bugs and am hopeful that they'll be fixed in Xerces-J 1.4. Meanwhile, my fixed version won't work at all until the bugs in Xerces get fixed, so I haven't uploaded it yet. I recommend you use the JDOM version instead.
IBM's alphaWorks has released the XML Schema Quality Checker, a Java program that checks for problems in W3C XML Schemas.
IBM's alphaWorks has released the XML Security Suite, an experimental implementation of a proposal for the W3C XML Encryption spec. It allows you to encrypt and decrypt arbitrary binary data, XML elements, or the content of thean XML element. It's written in Java, and is officially supported on Windows and Linux but will probably run on other platforms.
James Tauber and Daniel "eikeon" Krechogies have released Redfoot, an open source current version is 0.9.6.
The XML Encryption Working Group has published its first public working draft of XML Encryption Requirements. This document lists the design principles, scope, and requirements for a standard means of encrypting XML documents, and embedding encrypted documents (both XML and non-XML) in XML documents. The scope includes syntax, data model, format, cryptographic processing, patents and other intellectual property, algorithms, human factors issues, and interaction with other XML specifications such as the Document Object Model, XML Canonicalization and XML Digital Signatures.
Adobe's released Acrobat 5.0, its $250 payware portable document creation tool. Acrobat Reader 5.0 is free-beer. This version adds the capability to save the contents of PDF files into other formats such as RTF, TIFF, JPEG, and PNG. It supports 128-bit encrypted password protection and digital signatures, and can restrict editing and printing (though that's not too hard to break.) Acrobat forms can now be talk to databases through XML. Acrobat 5 also improves accessibility a bit by supporting high-contrast display settings and Windows-based screen readers, though it's still far less accessible than native XML or HTML with appropriate uise of style sheets.
Microsoft's posted "Technology Preview" (i.e. a beta) of MSXML 4.0, an XML parser/XSLT processor for Windows and Internet Explorer. This release features tentative support for the W3C XML Schema Language as well as experimental (and non-standard) integration of schemas with XPath and XSLT.
It is very difficult to get this version to replace IE's default MSXML 2.0 or a previously installed MSXML 3.0. The xmlinst program that could replace version 2.0 and 2.5 with version 3.0 doe snot work with version 4.0. Chris Bayes posted some instructions for hacking the registry to make IE use MSXML 4.0 on the xsl-list mailing list, though his post doesn't seem to be available in the archives yet.
ElCel Technology has released their Canonical XML Processor, a free-beer command-line tool for Windows and X86 Linux that converts XML documennts to canoncial form as described by the Canonical XML 1.0 Recommendation.
Once again I'm chairing the XML track for Software Development 2001 East. This year the show has moved to Boston, and will take place from August 27-31. Besides the change in venue, this year also sees the introduction of the co-located Web Services World, which I'm not involved with; but which some of you might also be interested in submitting proposals for.
This is a hardcore developers show, but not a deep XML show. Attendees are looking for meaty, technical, how-to presentations on specific technologies like schemas, DTDs, SAX, DOM, JDOM, XLinks, XQuery, Schematron, RELAX, etc. Some things we are NOT looking for (at least in the XML track) are very broad analyses of business cases for XML, introductions to XML itself, very academic presentations on hypertext theory, or advanced seminars that assume attendees are already intimate with schemas, XLinks, XSLT, and so forth. Of course this is all relative to the knowledge level of the audience. At this point, I think we could probably justify an advanced DTDs talk that discussed modularization using parameter entity references and namespaces. However, we probably wouldn't accept the same talk if it used schemas instead of DTDs because few people in our audience know a lot about schemas yet. On the other hand, we would be interested in a basic intro to schemas.
In other words, this is a show geared towards working programmers, not a show geared toward academics, managers, or XML experts. We find our attendees come to this track to learn about XML, not because they already know a lot about XML and want to debate the finer arcana, so aim your talks at beginner and intermediate users, not the people who regularly post to this mailing list and write for XML.com. Ideally, we want a broad mix of technologies and presentations so attendees can walk in the first day of the show knowing nothing about XML, and walk out the last day having a solid grasp of what all the pieces of the XML puzzle are, how they fit together, and know enough to start using them.
We have approximately one dozen 90-minute slots to fill. We are also open to intermediate level, 1-day tutorials on special topics like XSLT or Schemas. For the most part, we'll be looking for experienced speakers to fill these. If this is your first time presenting at a conference like this, it would be better to start with a couple of seminars rather than a full-day session.
You can submit abstracts online. The deadline for abstracts is May 1, 2001. Please submit your abstracts as soon as possible. Abstracts which are selected will receive notification by email no later than May 15. Unfortunately, due to the volume of abstracts we receive, we cannot notify every submission regarding their status.
The W3C/IETF joint XML Digital Signature working group has released the second Candidate Recommendation of XML-Signature Syntax and Processing. This defines an algorithm for signing XML and other documents using public key encryuption schemes and hash codes, embedding those signatures in XML documents and embedding the signed documents in the digital signatures. From the draft:
This version contains many bug-fixes, clarifications, and improvements for DTD/schema extensibility and re-use. It reflects resolution of recent (and past) issues and the Schema Proposed Recommendation. As warned in the previous Candidate Recommendation, the minimal canonicalization algorithm has been removed because the Working Group could find no implementation. This specification is considered to be very stable. The W3C Namespace Policy requires that if a change in the namespace makes previously valid or compliant instances and implementations invalid, the namespace must also change. Since the clarifications do not substantively affect valid instance syntax or implemented features, the namespace has not been changed.
This phase is scheduled to end May 19, 2001.
The W3C Document Object Model (DOM) Working Group has revised two open working drafts for DOM3:
The W3C Voice Browser Working Group has published the first public working draft of Call Control Requirements in a Voice Browser Framework. According to the document itself,."
IBM's alphaWorks has updated their P3P Policy Editor to support Java 1.3.0. This release is compatible with the Platform for Privacy Preferences Candidate Recommendation.
The W3C XSLT Working Group has announced a decision to skip XSLT 1.1 and go straight to 2.0. In my opion, this is a mistake. Despite some initial controversy over language-specific extension function bindings, XSLT 1.1 offered a great opportunity to pick the low hanging fruit and clean up a few problems with XSLT 1.0 in a fairly quick fashion without compromising future development. XSLT 2.0 seems like a lot bigger project, and overall more risky than XSLT 1.1. I would have preferred to finish the easy improvements first without making them depend on much more complex things like XPath 2.0 and schema awareness.
Ipedo, Inc. is looking for private beta testers for the Ipedo XML Database, a native XML database with XSLT processing. Featured in this release include:
If you want to participate in the beta program, send email to Samantha Cichon, samantha@ipedo.com.
Adobe's released the final version of the Adobe SVG Viewer 2.0, a plug-in for Netscape and Internet Explorer on both Windows and the Mac that allows you to view Scalable Vector Graphics (SVG) pictures embedded in Web pages. In the near future, the Adobe SVG Viewer will ship with RealNetworks' Real Player. and Adobe Acrobat and Acrobat Reader, which shoudl be a big step toward jump-starting SVG adoption.
Opera Software has released version 5.10 of their namesake Web browser for Windows that supports direct display of XML documents with attached CSS style sheets. Opera imporves DOM and CSS support. Other new features include Flash, skins, a new progress display and stop button, gesture based mouse navigation, improved window handling, more configurable and accessible privacy preferences, and assorted bug fixes. Opera is $39 payware without ads or free-beer with ads, your choice.
ElCel Technology has released a command line XML Validator for Linux and Windows written in C++. Registration is required.
XTooX is an an open source XLink processor. that reads out-of-line extended XLinks and folds them into the documents that they are pointing to.
XML::Xalan 0.06, a Perl interface to the Xalan C++ XSLT processor, has been released.
I've heard occasional bad things about Sys-Con Media, the publishers of the Java Developer's Journal and the XML Journal among other magazines, for a few years now. For the most part I've ignored the rumors and whispers since I haven't had any particular relationship with or interest in them. However, last year I spoke at a couple of Sys-Con branded conferences, XML DevCon New York and San Jose, though these were actually run by Camelot Communications. At some point after that Sys-Con had a falling out with Camelot. A contract dispute broke about between Camelot and Sys-Con, various lawyers exchanged nasty letters, and legal proceedings were initiated, though these seem to be mandatory arbitration rather than actual lawsuits.
I wouldn't even know any of this was taking place except that in a rather unusual stunt someone decided to be very public about the dispute. Earlier this year an unidentified person sent a series of emails from a Hotmail account to speakers at various Camelot conferences slamming Camelot for alleged non-payment of money owed to Sys-Con. The email address used, camelotcomc@hotmail.com, was designed to make it appear at first glance that the communication came from Camelot Communications itself.
I mostly shrugged off the initial emails, and didn't pay them much attention. I have no idea whether Sys-Con's claims have merit, nor do I much care. Sadly this is often how business is done in the U.S. today. It's not really a surprise, and doesn't have much of an effect on independent contractors like me working for either company, at least not in the normal course of things. However, what did shock me and convince me that Sys-Con had crossed the line was an email I and many other people received last week as part of XML-J April Digital Edition, a free-subscription electronic newsletter about things XML. What specifically bothered me was the following "news item" that ran as the lead story:
TODAY's NEWS: XMLDEVCON 2001 OPENS TODAY IN NEW YORK WITH EMPTY CLASSROOMS AND DISAPPOINTING TURNOUT ON THE EXHIBIT FLOOR!
(April 9, 2001) - XMLDevCon 2001 opened today in New York, with empty classrooms, and a disappointing turnout on the exhibit floor. Organizers of XMLDevCon promoted the expected attendance of the show to be more than 4,000 delegates. However, one of the classrooms that XML-J visited this morning, showed approximately one dozen attendees. (See photo news..)
-> continued:
At the time I was on the other side of the country at the SDExpo West show; but when I returned I made some inquiries of a number of people who were at the show, and they all agreed that the story was grossly inaccurate. There were over 2,000 attendees at XML DevCon New York; and although this was fewer than attended last summer, it was still a good-sized crowd. As always happens at such shows some classes were fuller than others, and some were quite packed.
There really wasn't much of a story here in the first place. To the extent that there was a story, it was hardly a significant one. I doubt that the XML-J Digital Edition would even have covered it, much less covered it in the way they did, except for one thing: Sys-Con is currently involved in a dispute with Camelot. I can't help but believe that Sys-Con is deliberately slanting their editorial content to support their position in the dispute. Worse yet, they're doing it without any acknowledgement to the typical reader that they are in such a dispute. Most subscribers would have seen this as merely another news story, without realizing the biases that lay behind it.
I don't mind Sys-Con using their newsletter to get out their message. However, doing so in such a deceptive and misleading fashion really bothers me. It makes me question whether I can trust anything in a Sys-Con publication. If they give a product a good review, is it only because the manufacturer bought an ad? If they give a product a bad review, is it only because they have a dispute with the manufacturer? These are real issues in journalism, but for the most part there's a presumption of innocence. Sys-Con has lost that presumption. This story makes it clear that the business and legal end of the company trump the editorial.
Before this whole mess erupted, I was debating whether to attend or speak at the Sys-Con JavaEdge show in New York and the XMLEdge show in Santa Clara this fall. I was leaning toward going to JavaEdge since it's local, and skipping XMLEdge since it's not. But after this mess, my mind has been made up. I don't want anything to do with Sys-Con, their conferences, or their magazines. I won't speak at their conferences. I won't write for their magazines. Whatever the merits of their original claim against Camelot, the PR campaign they have pursued in support of it is bad enough. The mixing of that PR campaign with their editorial content is indefensible. This is not a publisher or company I want to be involved with in any way.
The W3C Internationalization Working Group has released the Proposed Recommendation of Ruby Annotation. Ruby are short runs of text alongside the base text, typically used in Chinese and Japanese documents to indicate pronunciation or to provide a short annotation. This specification defines markup for ruby as an XHTML module.
ElfData's released XML Editor, a $70 payware XML editor (what else?) for the Mac that supports DTD validation. From the screenshots it looks like another tree-based editor. (When are developers going to realize that this is not the right user interface for an XML editor? Have any of them done any user testing? They all seem to be competing with each other based on how fast they can race in exactly the wrong direction. A good XML editor shoudl hide the structure of XML documents, not expose it.) XML Editor is $50 through April 25.
Version 0.2.1 of the open source XSLT Standard Library has been released. This is a collection of commonly-used templates written in pure XSLT 1.0. Changes since v0.1 include:
dom4j is yet another open source Java library for working with XML. The current version is 0.2. The main new features of this release are:
It looks interesting. The obvious comparison is with JDOM. It uses
interfaces rather than classes (a minus for most developers) but does have
Node and
Text interfaces which JDOM does not, and which I
need in my work. However, the parent relationshipo for nodes is only optional,
which strikes me as a big minus.
On the other hand, there's integrated XPath support which I consider a big plus.
JDOM may get this in version 1.1. These are just the results of a cursory first glance at the
API docs. A more detailed look will have to wait till a little time opens up.
Still, open source competition is a good thing.
Revision 0.2 Beta 3 of xslide, an Emacs major mode for editing XSL stylesheets has been released. Features include:
The W3C DOM Working Group has posted a new public working draft of Document Object Model (DOM) Level 3 Events Specification. This specification defines a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure and style of documents. DOM Events Level 3 builds on DOM Events Level 2. It's defined in IDL with bindings for Java and ECMAScript.
I have a sudden need for a vector format (e.g. EPS) drawing of the Mozilla dinosaur. If anyone knows where I can find such a thing please let me know. Thanks!
The W3C HTML Working Group has released the official recommendation of Modularization of XHTML. This document "specifies an abstract modularization of XHTML and an implementation of the abstraction using XML Document Type Definitions (DTDs). This modularization provides a means for subsetting and extending XHTML, a feature needed for extending XHTML's reach onto emerging platforms." In other words, it lets you use create subsets of XHTML that leave out pieces you don't like such as tables or frames while adding new pieces you do need such as Scalable Vector Graphics (SVG) or MathML.
I've posted the notes from my talks at Software Development 2001 West this week, including:
I've given variations of these at many other conferences over the last year. The biggest change at this show was updating the schemas talk to cover the March 30 Proposed Recommendation of XML Schema.
Sun's released version 1.1 of the Java API for XML Processing (JAXP) specification. This essentially describes DOM2 core, SAX2, TRAX, and a few factory classes for finding a parser and bootstrapping new documents. This may become a standard part of the Java class library in the near future.
The W3C HTML Working Group has advanced XHTML 1.1 - - Module-based XHTML to proposed recommendation. This specification defines a new XHTML document type based on the module framework and modules defined in Modularization of XHTML. XHTML 1.1 is intended as a "forward-looking document type cleanly separated from the deprecated, legacy functionality of HTML 4 [HTML4] that was brought forward into the XHTML 1.0 [XHTML1] document types." Changes since XHTML 1.0 strict include:
xml:langattribute replaces the
langattribute.
nameattribute of the
aand
mapelements has been replaced by the
idattribute.
rubycollection of elements has been added.
The installed base of web browsers is not ready for these changes. HTML 3.2 and earlier is going to be with us for a long time to come.
I'm leaving tomorrow (Saturday) for the Software Development West show in San Jose. I should have at least occasional Internet access while I'm at the show, but updates may still be a little slow for the next week.
Mozilla 0.8.1 has been released for the Mac, Linux, and Windows. This browser supports XML, CSS, and simple XLinks. I plan to use it for most of my presentations next weeek at the SD West show. Mozilla is open source.
IBM has ported Mozilla to OS/2 under the name "IBM Web Browser". This port includes a spell checker and Flash plugin. While the browser is a fee based product, IBM has also released an open source version which is available at mozilla.org.
Windows and Linux betas of DocZilla have also been released. DocZilla is a component add-on for Mozilla based browsers which includes an XML and SGML Parser, a DTD Parser, and support for HyTime links and CALS tables.
Also this week, Netscape released Communicator 4.7.7; but this release has no real XML suport, just some assorted bug fixes.
The W3C CSS Working Group has posted the first public working draft of Media Queries. According to the draft:.
The W3C XForms Working Group has posted a new draft of the XForms Requirements. This specification describes requirements for the next generation of Web forms to replace today's HTML forms.
Henry S. Thompson of the University of Edinburgh has updated XSV schema validator to support the latest Proposed Recommendation version of the W3C XML Schema Language.
Thompson has also released XSU, an online XSLT-based tool which upgrades XML Schema documents from the 2000/10/XMLSchema to the 2001/XMLSchema namespace, implementing all the changes from the one to the other.
Jeni Tennison's announced a new website and mailing list for the EXSLT iniative. EXSLT is an open community initiative to standardise and document XSLT extension functions and elements. The extensions are broken down into a number of modules including Common, Math, Sets and Functions. One aim of EXSLT is to get the implementers of XSLT processors to standardise the functions that they make available, so that stylesheets can be more portable.
Alex "Achtung" has localized the FOP XSL-FO-to-PDF converter to support Russian. This is actually quite a big job, involving fixing somem bugs with Cyrillic encodings, adding a dozen embedded Cyrillic fonts, and a Russian hyphenation engine.
Version 0.1 of the XSLT Standard Library has been released. This is an open source (LGPL) collection of commonly-used templates written in pure XSLT 1.0. This initial release seeks "to promote the library, establish the engineering standards for the library and also acts as a Call For Participation. Anyone who has useful XSLT templates and feels that they may be of use to a wide range of XSLT developers and applications is invited to submit their templates for inclusion in the library." There are three mailing lists for the project:
XML Cooktop 2.200 is a free XML development environment for Windows that allows you to write and test style sheets, XML documents, DTDs, and XPATHs. Version 2.200 improves the installer, asks before overwriting file associations, and supports more XSLT processors.
Microsoft has released a service pack for their MSXML 3.0 XML parser/XSLT processor that fixes assorted bugs.
The W3C Schema Working Group has revised the
XML Schema Language
Proposed Recommendations. The only notable change in this draft
is that the
number type has reverted to its
original name of
decimal.
Microsoft and Verisign, two companies with deservedly poor reputations for designing and managing secure systems, as well as webMethods, have submitted a note to the W3C on a proposed XML Key Management Specification (XKMS). According to the abstract,).
I haven't had time to read through the entire specification, but technical merit aside, I think it should be rejected on intellectual property (IP) grounds alone. The submitters seeem to want to make some unspecified IP claims on the technologies described in the spec, and are not willing to open up those technologies for free and unconstrained use by anyobne who wants to use them.
James Tauber's released PyTREX 0.7.0, at a clean-room implementation of Tree Regular Expressions for XML (TREX) written in Python. This is the first feature complete release.
webMethods has written a schema for XSLT 1.0 in the W3C XML Schema Language Candidate Recommendation syntax.
IBM's alphaWorks has updated their XML Diff and Merge Tool with bug fixes and a more customizable comparison function. Element comparison works better when sibling nodes have different positions under their parent. Also, one can specify which attributes to look at when determining matching nodes.
Unicode 3.1 has been released. The primary new feature of Unicode 3.1 is the addition of 44,946 new encoded characters. Together with the 49,194 already existing characters in Unicode 3.0, that comes to a grand total of 94,140 encoded characters in Unicode 3.1. The new characters cover several historic scripts, several sets of symbols, and a very large collection of additional CJK ideographs. Unicode 3.1 also features new character properties, and assignments of property values for the much expanded repertoire of characters.
The XML 1.0 specification anticipated this development and is ready to handle these characters.
However many parsers, including all those written in Java, depend on APIs that are not
Unicode 3.1 ready. For instance, any parser or API that uses a
Java
String
to store XML text will fail when confronted with the new characters.
James Kass has posted Code2001, a freeware TrueType font covering some of the scripts in the new Plane 1, including Old Persian Cuneiform, Deseret, Tengwar, Cirth, Old Italic, and Gothic. It works in WordPad in Windows 2000, but apparently not yet in IE.
There's an interesting article from Clay Shirky in the September Business 2.0, entitled XML: No Magic Problem Solver that I missed when it was originally published, so I wanted to comment on it now. In essence, the article points out something I've been telling people for a long time: XML does not relieve you of the necessity to talk to the people you want to exchange data with to agree on the format you'll use to exchange it. However, Shirky gets one thing in this article very, very wrong. He actually claims that XML makes it harder to do this, not easier, and that is completely wrong. Specifically what he says is,
Sad XML Truth No. 1: Designing a good format using XML still requires human intelligence. The people selling XML as a tool that makes life easy are deluding their customers--good XML takes more work because it requires a rigorous description of the problem to be solved, and its much vaunted extensibility only works if the basic framework is sound.
Sad XML Truth No. 2: XML does not mean less pain. It does not remove the pain of having to describe your data; it simply front-loads the pain where it's easier to see and deal with. The payoff only comes if XML is rolled out carefully enough at the start to lessen day-to-day difficulties once the system is up and running. Businesses that use XML thoughtlessly will face all of the upfront trouble of implementing XML, plus all of the day-to-day annoyances that result from improperly described data.
In fact, XML does mean less pain and it does require less work. Shirky's mistake is assuming that we could somehow live without rigorous descriptions and sound frameworks before XML existed. In fact, they were just as necessary then as now. It's just that XML makes it a lot easier to build rigorous descriptions and sound frameworks than when you had to start from scrtach with ASCII or (worse yet) raw bytes.
The reason XML is so widely used is that the designers of XML did a wonderful job of solving exactly those data exchange problems that nobody cared about and only those problems that nobody cared about. Let me explain. No one really cares whether lines end with a carriage return or a line feed or both. No one really cares whether fields are separated by a tab or a comma. No one really cares whether Unicode is encoded in UTF-8 or UTF-16. All the common alternatives are equally good. Prior to XML, however, before you could exchange data with someone, you needed to agree on answers to these and many similar questions, none of which had anything to do with the business case for exchanging the data. Furthermore, whatever underlying format you eventually agreed on (tab-delimited UTF-16 with carriage return line feed pairs separating lines or something else), you then had to write your own tools to process that data.
Once XML enters the picture, however, all these questions are answered. You don't care what line separator is used. You don't care what encoding is used. You agree that fields are separated by tags. And you use any of a variety of free tools to parse the data. You still need to spend time talking to the organizations you're exchanging data with to agree on what goes in the fields, what the fields are named, and what the data means; but you had to do all that anyway before XML, and XML doesn't make doing it any harder. In fact XML makes it all considerably easier. As soon as you've said, "The underlying format of our application is XML," you've answered a lot of questions that must be answered although noone really cares what the answer is. You can then move on to questions like "What is the valid range of prices?" which are much more important to the business. XML isn't a magic problem solver for all the problems of information exchange, but it pretty magically solves 10-20% of any given problem, and that's a significant improvement.
The IETF XML Digital Signatures Working Group has released RFC 3075 on XML-Signature Syntax and Processing. XML Signatures provide integrity, message authentication, and/or signer authentication services for data of any type, whether located within the XML that includes the signature or elsewhere. This is now a Proposed Standard Protocol. It is being jointly developed by the IETF and the W3C. Presumably the W3C version of this draft will be released soon. (The last W3C draft was a candidate recommendation in October of last year.)
The W3C XML Protocol Working Group has posted the second public working draft of XML Protocol (XMLP) Requirements. For those who haven't been following this, XML-RPC begat SOAP 1.0 which begat SOAP 1.1 which is currently pregnant with XML Protocol. Each successive generation adds some complexity while filling numerous holes and gaps in earlier generations. However, they all do more or less the same thing: allow you to make a method call to a remote system by sending an XML document over HTTP.
I'm at the O'Reilly Java conference right now, and XML Protocol seems to be the sleeper subject; that is, the topic that's not actually discussed in any sessions but is whispered about a lot in the hallways and at lunch, by people who aren't quite sure what to make of it, but suspect it's going to be very important.
During the course of this discussion, I had a revelation about XML-RPC/SOAP/XML Protocol: These are all nothing like remote procedure calls. These technologies have very little if anything to do with RPC/RMI/CORBA/DCOM/etc. They are neither players nor competitors in that space. The name of the first iteration of this technology, XML-RPC, was misleading in that respect. Instead, what this really is, is CGI POST. However, instead of sending the web server an x-www-form-urlencoded query string, you send the server an XML document. This is not a simplification of RPC. It's a complexification of CGI! I even hinted at this in Java Network Programming when I noted that there was no particular reason the body of a POST request had to contain an x-www-form-urlencoded query string, and that it indeed could contain something else as long as you controlled both the client and the server. I didn't follow up on that then or imagine that the body might be an XML document; but now that I have realized that, SOAP et al. make a lot more sense, and seem a lot easier to understand and explain.
The IETF/W3C XML Signature Working Group has released Canonical XML 1.0. Canonical XML defines an algorithm for converting an XML document to a sequence of bytes in such a fashion that two documents with the same byte-for-byte canonical form may considered to be in some sense the same. The canonical form normalizes a number of insignificant details like attribute order, whether single or double quotes are used to surround white space, and so forth. Changes in the final release of this specification are primarily editorial. There's only one very minor substantive change dealing with the Unicode decomposition of the Hebrew letter YOD with HIRIQ.
The W3C XML Core Working Group has published a second last call working draft of the XML Infoset. The Infoset tries to "provide a consistent set of definitions for use in other specifications that need to refer to the information in a well-formed XML document". The big changes in this draft are the elimination of
You now just see the post-parsed character data with no indication of how any individual character was encoded in the document.
The W3C HTML Working Group has published the first public working draft of Modularization of XHTML in XML Schema. This provides a schema for XHTML 1.1.
IBM developerWorks has posted an MP3 of an XML and Web Services panel I participated in at the International Conference for Java Development in New York a few weeks ago. You can listen to me dis WML. Other panelists included Alex Chaffee, David Megginson, Gerry Seidman, and Jay Walters.
Wolfgang Meier's released eXist, a "repository and retrieval engine for XML documents build on top of an relational database". Currently exist supports MySQL and Oracle. eXist provides structured retrieval of arbitrary XML documents with support for fulltext search. This release (0.3) adds Oracle support, speed-ups, a redesigned XPath parser, increased thread safety, and connection-pooling.
I've posted the updated notes from my tutorials yesterday at the O'Reilly Conference on Java:
These are essentially the same talks I gave a couple of weeks ago at XMLOne in Austin.
The W3C XML Schema Working Group has published the first public working draft of XML Schema: Formal Description. According to their draft,
This.
Version 0.6.5 of the Python/XML distribution has been released. This is more or less a beta release. The Python/XML distribution contains the basic tools required for processing XML data using Python. The distribution includes parsers and standard interfaces such as SAX and DOM, along with various other useful modules. Python/XML currently contains:
Changes in this version include:
xml.utils.booleantype distinguishes boolean from integer values.
DocumentFragmentinterface, and correctly sets the
ownerDocumentproperty.
James Tauber's released PyTREX 0.6.0, at a clean-room implementation of Tree Regular Expressions for XML (TREX) written in Python.
Robert C. Lyons has invented the Turing Machine Markup Language (TMML), an XML application for describing programs for Turing machines. He's also written a TMML interpreter in XSLT that executes Turing machine programs described in TMML documents, thus proving that XSLT is indeed Turing complete.
The Apache XML Project has released Xerces-J 1.3.1, an open source XML parser written in Java that supports DOM2, SAX2, and JAXP. This release supports more of the Candidate Recommendation of the W3C XML Schema Language, but does not yet suport the more recent Proposed Recommendation. A few bugs were also fixed.
The Apache XML Project has also released Xalan-Java 2.0.1, an open source XSLT processor written in Java. This adds several new new command-line parameters, two new streamlined sample servlets, and fixes assorted bugs. It supports XSLT 1.0.
I'm back from XMLOne London. While there I talked about schemas and XLinks and XPointers. I'll have the revised notes up a little later today. The schemas talk in particular featured a lot of new material I hadn't previously talked about including facets and the changes in the March 16 Proposed Recommendations.
I apologize to those of you who wrote in to say you were worried about my absence. I expected the conference to have much better Internet connectivity than it actually did. In fact, without a local London dialup there was effectively no way for me to update my web sites. I could check my email, but only barely. I was very disappointed that the conference did not provide a place for me to plug my laptop into so I could work while at the conference. In the future, I'm going to be cutting down on the conference appearances I make, and one criterion for choosing which ones to attend is going to be the Internet access they provide.
Tomorrow I leave for the O'Reilly Java Conference in Santa Clara. Last year the O'Reilly conference had much better Internet connectivity than any other conference I've ever been at, so I should be able to maintain Cafe con Leche and Cafe au Lait while there.
IBM's alphaWorks has released XSLerator, a tool written in Java to generate XSLT style sheets from mappings defined using a visual interface. XSLerator supports mappings with extended conversion functions including iterations, conditions, joins, variables, and XPATH functions. Some knowledge of XSLT is required.
The W3C Schema Working Group has elevated their XML Schema Language to Proposed Recommendation. Changes since the candidate recommendation are fairly minor and include:
uriReferenceis now
anyURI
binaryhas been replaced by
hexBinaryand
base64Binary
yearare now prefixed with a
gas in
gYear
IBM's submitted a note with no official status to the W3C requesting that Unicode C1 control character character #x85 NEL (new line) be redefined as white space and a line ending character in XML documents. It is currently allowed in XML documents but cannot appear in tags and a few other places carriage retruns and line feeds can appear. This is apparently causing problems for XML parsers on OS/390 where ASCII FTP transfers change carriage returns and linefeeds to a NEL.
This is a horrible idea, and I hope the W3C rejects it firmly. Adopting it would break essentially every XML parser on the planet. The proper fix for this problem is for IBM to start using real UTF-8 and ASCII on their systems, rather than asking the rest of the world to adapt to their brain damaged, non-standard software. Software that transfers XML files to OS/390 (or any other) systems should not be rewriting it without an understanding of the syntax of XML documents. Translations that treat XML documents as plain text files are bound to cause problems. Any software that's not XML-aware should not attempt to change XML documents.
The W3C Device Independence Working Group has published a last call working draft of Composite Capability/Preference Profiles (CC/PP): Structure and Vocabularies. This is an RDF vocabulary for describing user agent (browser) and proxy capabilities and preferences. Topics include:
The CC/PP vocabulary uses URIs to refer to specific capabilities and preferences. It covers:
IBM's alphaWorks has updated their XML Diff and Merge Tool to support Java 1.3, fix a few bugs, and add support for id and name attributes in merely well-formed documents that don't have DTDs and thus can't declare attributes to have ID type.
One of the problems with attending six conferences in a little over six weeks is that it becomes very difficult to keep up with the more complex developments in the XML world. While I was busy pouring over the XPath 2.0, XSLT 2.0, and XQuery 2.0 working drafts so I could discuss them in last week's Cutting Edge XML Programming session, several other people were busy trying to extend XSLT 1.0 in a different direction to allow extension functions to be written in pure XSLT. I haven't fully digested all this work yet, but it looks interesting.
The first such effort is Jeni Tennison's EXSL, User-Defined Extension Functions in XSLT. EXSL defines extension elements and functions to support user definition of extension functions using XSLT. Uche Ogbuji's written an implementation for 4XSLT. The current version is 0.1.
David Rosenborg of Pantor Engineering AB has counter-proposed Functional XPath (FXPath). He's already produced a sample implementation for Michael Kay's SAXON. The current version is 0.3.
The W3C CSS Working Group has published the first public working draft of CSS3 module: Color. This draft brings together in one place the color parts of previous W3C Recommendations including HTML 4 and Cascading Style Sheets (CSS) levels 1 and 2. It also adds several new CSS3 properties for opacity, ICC color profiles, and rendering intent of image content.
The same working group has also
updated the Syntax of CSS rules
in HTML's 'style' attribute working draft.
This document describes the history, grammar, cascading order and profiles for
CSS fragments in the
style attribute.
I've posted the updated notes from all my talks at XMLOne in Austin last week. These include:
XML Fundamentals, a three hour introduction to XML and related technologies
Processing XML with SAX and DOM, a three hour introduction to writing Java programs to manipulate XML documents
XML Hypertext, a two hour discussion of XLinks, XPointers, XML base, and XInclude
XSLT, a 90-minute introduction to writing Java programs to manipulate XML documents
Cutting Edge XML Programming, a three hour seminar covering more or less whatever seems to be newest and hottest on the day I give it. This time I covered the XML Infoset, DOM Level 3, and XQuery.
O'Reilly's stopping development of the WebSite web server for Windows, as well as the companion WebBoard product. They're looking for buyers for these products, but personally I don't see that they have much place in a world dominated by the open source Apache web server, which O'Reilly's done not a little to promote and even uses on many of its own web sites. Next target for Apache: Microsoft's IIS.
Meanwhile, here's a suggestion for Tim: If you can't make a go of WebSite and WebBoard with a payware business model, why not open source them? I doubt WebSite could compete effectively with Apache, even as open source, but there are a lot of sites (like mine) that would be very interested in an open source WebBoard.
Jonathan Borden's updated the draft specification for the Resource Description Discovery Language (RDDL, pronounced "riddle"). According to Borden,
This version contains only relatively minor edits and clarifies the URL persistence policy. The URLs for the well known natures and purposes were a mix of and. Now only and are specified and should be used as these will be subdivided in subdirectories in the future.
He's also posted an RDDL
directory of other
RDDL
documents. Finally,
Borden's also begun work on a
RDDLClassLoader for
Java.
This extends
java.net.URLClassLoader.
The constructor reads an RDDL
directory to get a list of Java
CLASSPATH URLs having a specified purpose
such as "xslt-extension".
The W3C Synchronized Multimedia Working Group has posted a new working draft of the Synchronized Multimedia Integration Language (SMIL 2.0) Specification. SMIL 2.0 has two goals:
SMIL 2.0 is modularized, much as XHTML 1.1 is. One of the big changes additions to this release of the spec is a full complement of modules defined in XML Schemas, rather than just the DTD modules of previous working drafts. To the best of my knowledge, this is the first non-schema spec to make real use of the W3C XML Schema Language.
I'm leaving today for the XMLOne show in Austin. Consequently, updates may be a little spotty here until I return on Friday. However, assuming I can get reasonable net access at the show, I'll try to keep things fresh here.
The Apache XML Project has released version 1.1 of Xalan-C++, an XSLT processor written in C++. This release offers a "greatly simplified C++ API and C API for performing standard XSL transformations" as well as fixing bugs and upgrading performance. Binaries are available for Windows, Red Hat Linux 6.1 , AIX 4.3, HP-UX 11, and Solaris 2.6.
The Unicode Consortium has revised the draft technical report covering Unicode 3.1. The main change in Unicode 3.1 are many new characters, including characters with code points greater than 65,535 for the first time. Unicode will no longer effectively be a two-byte character set.
Michael Kay's released version 6.2.1 of the open source SAXON XSLT processor written in Java. SAXON supports all of XSLT 1.0 and features preliminary support for parts of XSLT 1.1 as well as numerous extension functions. This release fixes a number of bugs.
RenderX has released version 2.2.1 of the payware XEP XSL-FO-to-PDF converter. New features in this release include:
fo:markerand
fo:retrieve-marker
fo:float[@float="before"])
xsl-footnote-separator
fo:leader
An evaluation version witha 10-page limit is available..
The W3C Platform for Privacy Preferences (P3P) Preference Interchange Language Working Group has published a new working drafts on A P3P Preference Exchange Language 1.0 (APPEL1.0). APPEL is a ." APPEL is expressed in XML.
The W3C CC/PP Working Group has published a revised working draft of Composite Capability/Preference Profiles (CC/PP): Structure and Vocabularies. A CC/PP profile is a description of device capabilities and user preferences that can be used to tailor content for that device. CC/PP documents are written in RDF.
Fourthought, Inc. has released version 0.10.2 of
4Suite, a collection of open source tool
for processing XML in Python.
It provides support for XML parsing, several
transient and persistent DOM implementations, XPath expressions,
XPointer, XSLT transforms, XLink, RDF and ODMG object databases. This is mostly a bug-fix and general clean-up release.
There are new
search-re() and
base-uri() XSLT extension functions.
Fourthought, Inc. has also released version 0.10.2 of 4Suite Server, an open source XML data server. It features an XML data repository, a rules-based engine, and XSLT transforms, XPath and RDF-based indexing and query, and XLink resolution. Again this release focuses mostly on bug fixes and code and documentation clean-up as well as usability improvements and more test cases.
The O'Reilly Network's published my latest article, RDDL Me This: What Does a Namespace URL Locate?. This article explores the Resource Description and Discovery Language.
The W3C has released Mathematical Markup Language 2.0 (MathML) as an official recommendation. Changes since MathML 1.0.1 include:
XML namespace support
New mathematics style attributes on token elements:
mathvariant,
mathsize,
mathweight, and
mathcolor
New presentation elements:
mglyph,
menclose
and
mlabeledtr
Browser support is still lacking.
The W3C HTML Working Group has published the Proposed Recommendation of Modularization of XHTML. In my opinion, this is simply far too early for a proposed recommendation because a very key component, the schema implementations, is still completely omitted. This specification needs to be held back until schemas are finished. Review ends 22 March 22, 2001.
During last week's XLinks and Namespaces seminars at XML DevCon, I gave my usual spiel about how "All the specifications are defined in terms of URIs, but only URLs are used in practice." Eventually, however, this will change with the advent of Uniform resource Names (URNs). URNs depend on the concept of individual URN namespaces (not the same as XML namespaces!). The IETF URN Working Group has posted a new Internet draft on URN Namespace Definition Mechanisms defining URN namespaces and the mechanisms for establishing new ones.
IBM's alphaWorks has released XML for C++ 3.3.1, which is based on the Apache Xerces XML C++ Parser v1.3.0. This parser supports DOM2 and SAX2. This release adds bug fixes, speed ups, and AS400 iSeries binaries.
I'm back from XMLDevCon London 2001. where a good time was had by all. I've posted the notes from my talks on XLinks and Namespaces. Tomorrow I'll be catching up with all the news that piled up while I was away.
XQuery, the W3C XML Query Language, is a functional language for extracting information from XML documents and databases. Think of it as XPath crossed with SQL. The W3C XML Query Working Group has just published five documents describing XQuery:
According to Jonathan Robie, "The first three documents should be reasonably accessible. The last two are more mathematical." I hope to talk about all of these in my Cutting Edge XML Programming talk at XMLOne Austin next month. I'll certainly cover them in my Advanced XML tutorial at SDExpo West in April.
The Gnome Project has posted libxslt-0.2.0, the second beta release, of this XSLT processor library for Linux written in C. It supports most of XSLT 1.0 except for
document()
key()
XSLT-process 1.2 has been released. XSLT-process is an Emacs minor mode that allows you to invoke an XSLT processor of choice on a buffer, displaying the result in an additional buffer. Currently supported XSLT processors include Xalan 1.x, and Saxon 5.x and 6.x. Changes since 1.1 include:
The W3C Forms Working Group has published a new working draft of XForms 1.0. XForms are a proposal for the next generation of HTML forms, with much broader support for platforms of varying capabilities such as desktop computers, television sets, personal digital assistants, cell phones, computer peripherals and even paper. XForms can collect information that meets the constraints of various schema data types including:
In adddition, it derives Currency and Monetary types from String. These can be further constrained with facets as in schemas. Another interesting and useful feature of XForms is a dynamic constraints language that enables you to define integrity constraints that act over multiple fields. For instance, "the total value of an order can be defined in terms of a computation over other values such as unit prices, quantities, discounts, and tax and shipping costs." The language used to do this is XPath. Time permitting, I'm going to try to whip up a few notes on this for my bleeding edge presentations at either XMLOne in Austin or SDExpo West in San Jose.
In a very unusual move, Sun Microsystems is seeking a patent office reexamination of one of their own patents, U.S. Patent No. 5,659,729, that may (or may not) affect XPointer. Prior art should be sent to 729-patent@east.sun.com for use in the reexamination and possible revocation of the patent. They are also seeking suggested changes to the licensing terms they've proposed for this patent. It sounds like Sun really wants to do the right thing here, so if you have any prior art, please help them out.
The W3C XSL Working group has published working drafts of the requirements for XPath 2.0 and XSLT 2.0. Suggested requirements for XPath 2.0 include:
Must semantics string matching using regular expressions using the regexp syntax from schemas
Must add support for XML Schema primitive datatypes
Should add support for XML Schema: Structures
Suggested requirements for XSLT 2.0 include:
Must maintain backwards compatibility with XSLT 1.1
A stylesheet
In addition, the following two are explicitly not goals:
Simplifying the ability to parse unstructured information to produce structured results.
Turning XSLT into a general-purpose programming language
I plan to talk about some of these proposals in my Cutting Edge XML Programming post-conference tutorial at the XMLOne conference in Austin next month.
Sun's released version 1.1 of JAXP, the Java API for XML Processing. This is essentially SAX2, DOM2 Core, Trax, and a few factory clases for finding a parser.
Mozilla 0.8 has been released for the usual batch of platforms. Mozilla supports XML, CSS, and simple XLinks, among many other features. New features in this release include Find and Replace.
Robert X. Cringely has retracted last week's claim, which I reported here, that Adobe has laid off the Framemaker team. Apparently Adobe was quite demonstrative in their personal response to him that there was nothing to the story. It may have been based on an old Internet rumor. The furor over the alleged layoffs did bring one interesting fact to light that I was not aware of before. According to Bob Ducharme, FrameMaker is much better at exporting XML than at importing it. Maybe now the still-hard-at-work FrameMaker team can add this for the next release?
Bill LaForge has released version 4 of Quick. Quick is a data modeling system for Java that can generate and process XML by converting arbitrary object structures into trees of XML elements. Quick works with Java Beans and Bean Property Editors. Changes in this release include :
Mike Brown and Jeni Tennison have released the ASCII XML Tree Viewer, an XSLT style sheet that shows the node structure of an XML document in the form of plain text "ASCII art".
The W3C XML Core Working Group has published the XML Fragment Interchange Candidate Recommendation. This spec attempts to address the question of what to do with pieces of XML documents that are not themselves complete well-formed XML documents and may be missing key components like entity declarations, encoding information, default attribute values, and namespace mappings. The Candidate Recommendation Phase is scheduled to end April 30, 2001.
The W3C DOM Working Group has published a new working draft of the Document Object Model (DOM) Level 3 Content Models and Load and Save Specification. The first part of this spec uses IDL to define interfaces for accessing grammars (DTDs and schemas) as object trees. The second part defines a platform independent means to parse and serialize XML documents. As far as I know, no parsers have really tried to implement this yet, though the Load and Save parts are partially derived from ideas in JAXP.
I'll be talking about new features in DOM3, including Content Models and Load and Save, on the last day of the XML One Conference in Austin next month. Time permitting, I may try to work some XML Fragment material into the session as well.
Netscape's released version 6.0.1 of their namesake web browser for Mac, Windows, and Unix. This is a bug fix release to improve stability and address a few user interface issues. XML and CSS support is pretty much the same as in version 6.0.
The Apache XML Project has released FOP 0.17, an XSL-FO-to-PDF converter written in Java. This release features numerous bug fixes, and much tighter conformance to the XSL-FO Candidate Recommendation. I haven't had time to test out all the new features, and the web site isn't updated yet, but I do remember that footnotes were promised for this release.
Opera Software has released Opera 5.0 Beta 6 for Linux. This is an ad-supported web browser with support for XML+CSS. They've also updated the Windows version to 5.0.2. Opera is $39 without the ads.
The Gnome Project has posted the first public beta of libxslt, an XSLT processor shared library for Linux. At this time libxslt is incomplete and undoubtedly buggy, but it's got enough to be useful. Extension functions and elementsd aren't really supported yet, but most standard XSLT elements work. A few attributes are missing here and there.
The Gnome Project has also updated the libxml XML parser shared library for Linux to version 2.3.0. This is a bug fix release.
The W3C has published an interesting note on Common User Agent Problems. While Microsoft and Netscape compete with each other in features, they've more or less ignored a number of glaring problems in their browsers. This document identifies myriad user-interface deficiencies in common web browsers, most of which have been problems for years. Examples include:
Stated this bluntly, these are really obvious problems. Perhaps this note will nudge vendors to address a few.
Several people wrote in to tell me that Adobe had responded to Cringely's article. It's important to note, however, that nothing in Adobe's press release actually says that Cringely was wrong. In particular, it does not deny that Adobe laid off the FrameMaker team. In my opinion, that missing denial is far more suggestive than the original report. I suppose it's possible Adobe laid off all or most of the FrameMaker team for reasons unrelated to a lack of commitment to the product, but that seems unlikely to me.
I've posted a minor update to Chapter 16 of the XML Bible, XLinks. Mostly this version improves the formatting of the XML examples, but a few bugs and mistakes were fixed as well. The chapter is now current with the December 20, 2000 Proposed Recommendation of XLink.
IBM's posted refreshed versions of several products on alphaWorks including:
A couple of bugs have been fixed in the XML Lightweight Extractor (XLE). XLE allows a user to annotate a DTD to associate its various components with underlying data sources. Then it can extract data from the data sources and assembles the data into XML documents conforming to that DTD.
Version 2.0.0 of the LotusXSL XSLT transformation engine is based on Xalan-J 2.0.0
The DirectDOM Development Kit for Netscape 6 has been released, and the Development Kit for IE was updated. DirectDOM technology allows a Java developer to build applet GUIs using the browser UI instead of Swing or the AWT. Only Windows is supported.
I've posted a minor update to Chapter 15 of the XML Bible,
XSL Formatting Objects.
This just corrects a few minor errors and misconceptions. Mostly it
addresses changes in the Candidate Recommendation draft that I missed on my first read-through a couple of
months ago. Most significantly, boolean properties that used to have the values
yes and
no, now have the values
true and
false.
Nokia's released version 2.1 of the Nokia WAP Toolkit, a free-beer PC-based environment in which developers can write, test and de-bug WAP applications. This release adds a phone simulator is provided for the Nokia 6200 and 7100 Series phones. Registration is required.
Robert X. Cringely's reporting that Adobe has laid off the FrameMaker team. That doesn't bode well for future development and support of the XML-enabled word-processor/page layout program. FrameMaker has filled a unique niche in technical documents over the years. If it goes, we'll be down to TeX and XML.
Matt Seargeant's released AxKit 1.2, an XML application server based on mod_perl. You can find all the details you need to know about AxKit at It's also available on CPAN in the Apache modules directory.
The W3C Working Group has published the first public working draft of CSS Mobile Profile 1.0. This defines a subset of CSS2 tailored to the needs and constraints of memory, display, and bandwidth challenged devices like cell-phonnes and Palm Pilots.
The W3C has launched a new mailing list to discuss XSL Formatting Objects. To subscribe, send email to XSL-FO-request@w3.org. with the word "subscribe" in the subject.
The Apache XML Project has released Xalan-Java 2.0, an open source XSLT processor written in Java. This release supports XSLT 1.0 as well as assorted extension functions including SQL access to databases via JDBC, redirection of output, conversion of result-tree fragments to node-sets, set operations on node-sets, tokenizing strings, and more. THe major change in this release is support for TrAX, the Transformation API for XML. This API allows API-level users to code XML applications without reference to the internal details of a particular processor or XML parser.
The W3C SVG Working Group has posted the second public release of the SVG test suite. The results seem to say that the latest CVS version of Batik is the most compliant for static SVG, and that the Adobe SVG Plug-in 2.0 is most compliant for animations. Of course, all the products tested are in beta, so everyone still has a lot of work to do.
Sun's published a draft of the XML file formats for OpenOffice, a.k.a. the open source version of Star Office 6.
The W3C Core XML working group has published the last call working draft of the XML InfoSet. Last Call Ends February 23.
The XML Apache Project has released Xerces-J 1.3.0. The big new feature in this release is upgrading schema support to partial compliance with the W3C Schema Candidate Recommendation of October 24, 2000. There are a few other bug fixes and optimizations as well.
The XML Apache Project has also released
Xerces-C 1.4.0.
New features of this include
a SAX2
LexicalHandler, an optimized DOM Implementation,
and many big fixes. However Xerces-C does not support schemas yet.
IBM's alphaWorks has refreshed their XML Security Suite. The XML Security Suite provides digital signatures, element-wise encryption, and access control. mIt is written in Java, and should run on most Java compatible platforms. This release adds an improved API document for XACL, along with better KeyInfo handling of XML-Signature, a programing how-to guide, and some bug fixes.
The W3C DOM Working Group has published the first
public working draft of Document Object Model (DOM) Level 3 Core Specification Version 1.0.
The current document is quite incomplete, but eventually it will define the DOM3 versions of
the basic DOM
classes that represent the parts of an XML document
(e.g.
Element,
Attr,
Text, etc.). New features in DOM3 core
include:
DOMKeys, unique keys generated by the DOM implementation for each DOM node
The version and encoding of an external parsed entity, as provided in text declarations
The version, encoding, and standalone status of a document, as specified in the XML declarations
An
adoptNode() method to move a node from one document to another.
Several new methods in the
Node interface including:
public TreePosition compareTreePosition(in Node other) throws DOMException public boolean isSameNode(Node other) public String lookupNamespacePrefix(String namespaceURI) public String lookupNamespaceURI(String prefix) public void normalizeNS() public boolean equalsNode(Node n, boolean deep)
The W3C WCAG Working Group has published the first public working draft of the Web Content Accessibility Guidelines 2.0.
The W3C Internationalization Working Group and the IETF Internationalization Interest Group have published the last call working draft of Character Model for the World Wide Web 1.0. This document provides authors of specifications, software developers, and content developers with a common reference for consistent, interoperable text manipulation on the Web. Topics addressed include encoding identification, early uniform normalization, string identity matching, string indexing, and URI conventions. Some introductory material on characters and character encodings is also included. Last Call ends February 23, 2001.
Unicorn Enterprises SA has released the Unicorn XML Toolkit 1.00.00 for C++ and ECMAScript on Windows. This is a collection of XML libraries and utilities iincluding
The XML Apache Project has posted version 1.8.2 of the Cocoon application server. This is a bug fix release. Cocoon 1.8.2 is now available for download: Among other things, Cocoon works on Java 1.1 again, and the XInclude processor should work correctly at any stage in the pipeline. The optional connectors for XT and JNDI have been restored.
The W3C CSS working group has published the last call working draft of CSS3 module: W3C selectors. This is a major upgrade form CSS2 selectors with a lot of new functionality. It takes much more explicit account of XML support, including namespaces and case-sensitivity. Comments are due by March 1, 2001.
Amazon.com got XML in a Nutshell in stock today, and promptly ran out while filling pre-orders. It is now listed on 4-6 week availability, but they'll probably get more much sooner than that, if you want to preorder it. The following bookstores also have it in stock for shipment in 2-4 days:
In the meantime I've begin posting various material from the book for your perusal, including:
I still have to post the examples from a few of the later chapters, but most of them are available now.
Mike Olson has released 4XDebug, an interactive XSLT debugger, and 4XProf, an XSLT profiler. The debugger has all the typical debugger features: stepping through XSLT instructions, setting breakpoints, displaying arbitrary expressions against the current context, etc. The profiler breaks down performance by patterns, templates, paths, portions of path (etc. How long are my descendant-or-self axis specifiers taking?)
The XML Authoring Environment for Emacs (XAE) is a free software package that allows you to use Emacs and your system's HTML browser to create, transform, and display XML documents. The XAE includes:
SWAG, the Semantic Web Agreement Group is self-organizing with a goal of "creating a strong infrastructure for the Semantic Web, whilst working with various members of the Web community to ensure that data remains interoperable." SWAG's current focus is the compilation of the SWAG Dictionary, a database of terms for the Semantic Web, and the creation of new vocabularies. You can subscribe to the SWAG development list by sending a blank email to swag-dev-subscribe@egroups.com.
The Unicode Consortium has published the first public working draft of Unicode 3.1. The primary new feature of Unicode 3.1 are 44,946 new characters covering several historic scripts, several sets of symbols, and many additional CJK ideographs. For the first time, characters are encoded beyond the original 16-bit codespace or Basic Multilingual Plane (BMP or Plane 0) in code positions of U+10000 and higher. In particular, there are three new supplementary planes:
>P<to indicate a paragraph, you might just write
P. However, you'd use the P at U+E0070 instead of the P at 0x50. (Note: neither XML or HTML uses this. It's intended to be used for future standards.)
The creators of XML specification foresaw these developments, and the XMlm specification is fairly compliant with these new characters. However, not all parsers may be compliant yet.
Dave Beckett's posted an alpha release of the open source Rapier RDF Parser 0.9.0 written in C.
Jim Fuller's written an amusing XPath cheat sheet Flash applet.
I'm pleased to announce the imminent release of XML in a Nutshell by W. Scott Means and Elliotte Rusty Harold (i.e. me). This is a book a lot of developers have wanted for a long time now. Over a year before the contract was signed, readers were showing up at the O'Reilly booth at Internet World asking when XML in a Nutshell was going to be released. There were a few sputters and starts along the way, and like all such books multiple deadlines were missed; but I'm pleased to announce that thousands of copies of XML in a Nutshell have rolled off the printing press, been perfect bound, packed in cardboard boxes, and shipped to bookstores around the world, where they should begin arriving tomorrow. I think you'll like it.
One of my favorite comments about The XML Bible came from a reader in Norwich England who wrote, . In fact, XML in a Nutshell even weighs less than half what the XML Bible weighs, so not only will it not break your budget; it won't break your back either. (Whether I can write this concisely without the able aid of my coauthor W. Scott Means is still an open question.) I still like the XML Bible. I think it's a good book, but even I have to admit that I think twice before packing it in my carry-on luggage..
Now for the bad news: bookstores have only preordered 17,000 of these. While that sounds like a lot, more than 20,000 people a day read Cafe con Leche, which means bookstores are going to be caught at least a few thousand copies short, and probably more. Amazon, in particular, always manages to underestimate the demand for my books and sells out their initial allotment within an hour or two of me announcing one here. If you see that Amazon is listing it on "4-6 weeks availability" don't worry. O'Reilly can get them more a lot faster than that. Still, if you know you want this book, don't wait. Order it now. It will be available very soon from any bookstore that carries computer books including:
If you need to special order it, the ISBN number is 0-596-00058-8. It's $29.95, published by O'Reilly, and written by Elliotte Rusty Harold and W. Scott Means.
The W3C XML Core Working Group has promoted Canonical XML to a Proposed Recommendation. This specification describes an algorithm for generating a byte sequence from an XML document called the canonical form. The canonical form normalizes a number of insignificant details like attribute order, whether single or double quotes are used to surround white space, and so forth. Two XML documents with the same canonical form can be considered equal for all intents and purposes. This version is pretty much the same as the Candidate Recommendation. Review ends February 16.
Sun's posted a Java Specification Request (JSR) for a Java API for XML Registries 1.0 (JAXR). Acccording to the JSR abstract, "JAXR provides an API for a set of distributed Registry Services that enables business-to-business integration between business enterprises, using the protocols being defined by ebXML.org, Oasis, ISO 11179." The JSR further claims that, "JAXR may be viewed as analogous to Java Naming and Directory Interface (JNDI) but designed specifically for internet sharing of XML-related business information." Review closes on Jabuary 22, 2001. (Monday)
The W3C CSS&FP working group has published a new working draft of CSS3 introduction. This provides short descriptions of each of the planned modules of CSS3 including:
The Apache Cocoon project has released version 1.8.1 of the Cocoon application server. This is mostly a bugfix release. New features include:
IBM's alphaWorks has released version 3.1.1 of their XML Parser for Java (which is based on Xerces-J). The main changes are in performance and thread safety.
Jasc Software has posted the fourth beta of WebDraw (formerly known as Trajectory Pro), an SVG authoring program for Windows 98/NT4/2000/ME. New features in this release include:
How you phrase requests is sometimes important. I once heard a story about a woman who put up some flyers in her neighborhood advertsing, "For Adoption: eight cute puppies and one ugly one." That one ugly puppy got adopted nine times! After yesterday's claim that WML did not actually work, I finally got multiple submissions of photos of actual WML phones displaying my Hello WML example. Thanks to everyone who submitted. The best photo was probably this one from Reggie Dablo:
I'm still not convinced that WML is useful or usable, or that anyone who's not developing for it is actually using it on an even semi-regular basis, but it is at least technologically possible. What's worst is that the WAP community seems to have its head in the sand about usability issues. The Nielsen-Norman group recently did a major study pointing out the problems with WAP. The WAP Forum's response sounds to me like a desperate effort to spin the press and investors rather than a serious acknowledgement of the very real problems that exist.
There are a number of ways wireless Internet access could be fixed, though it's not clear whether WAP/WML can be. In rough order of short-term feasability they are:
A device with a small keypad, and a slightly larger, higher resolution screen; e.g. BlackBerry. This would eliminate the existing problems with typing letters on a phone keypad. Typing in URLs like can be extremely difficult on a phone. In fact, I'd say anything beyond a three-letter airport code or a four-letter stock symbol is too much to ask of users on existing phones.
A device with a much larger, higher resolution screen and pen based input; e.g. a Palm Pilot. You can get real work done on a Palm Pilot. You can't on a cell phone.
A browser that uses the one media type that's actually appropriate for cell phones: audio. All commands should be input via voice. All pages should be read to the users. This would require more CPU horsepower and memory, but that's coming.
Wearable computers with gesture input and phenomenally large heads-up displays built into glasses or contact lenses. (Eye cancer might be a bit of a problem, though.)
ZDNet is running an interesting story about future cell phone developments.
The W3C has published the first public working draft of Multi-column layout in CSS. This proposal defines three groups of new properties to support multi-column layouts in CSS3. The first group sets the number and width of the columns:
column-count
column-width
column-min-width
column-width-policy
Properties in the second group specify the amount of space and rules between columns:
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
The third group contains a single property that lets an element span multiple columns:
column-span
The IETF has published RFC 3023, XML Media Types by Makoto Murata, Simon St.Laurent, and Daniel Kohn as a This document standardizes five new MIME media types:
This document also standardizes the convention of using the suffix +xml for naming media types for specific XML applications. For instance, RDDL documents would have the type text/rddl+xml.
Meanwhile M. Baker has submitted an IETF internet draft (the pre-RFC stage) on the 'application/xhtml+xml' Media Type. This specification also introduces a new parameter called schema-location that would identify where the schema for this document can be found. For example, an HTTP server might include this Content-type header when returning an XHTML document:
Content-type: application/xhtml+xml; schema-location=""
This approach would seem to have implications beyond XHTML. It could easily be used to locate schemas for any type of XML document returned over HTTP.
AlphaXML is sponsoring a contest to write the the best Haiku on the topic of XML. The prize is a copy of Turbo XML.
Andrew Watt's launched an XSL Formatting Objects Mailing List. You can subscribe by sending email to XSL-FO-subscribe@egroups.com.
I am going to propose a falsifiable hypothesis: The Wireless Web does not exist. There are many developers but no actual users. I'm hypothesizing this because of the 20,000 people a day who read this site, not one seems to have a cell phone capable of viewing this most basic WML page. To falsify my hypothesis and prove me wrong all that's needed is to take a good picture of a real cell phone browsing that page.
After hours of trying to load this page on my own phone, and much converstion with my cell phone company's technical support, VoiceStream finally admitted that, contrary to what I was promised when I initially signed up with them, the phone they sold me did not actually support WAP and WML. Then they told me to trade it in for a new phone, but they couldn't provide me with the model that would actually do what they had promised; and after several weeks of searching, it doesn't seem that anyone else can either. Several people sent me screen shots of a cell phone simulator viewing this page, but so far not one person has actually sent in a real photograph of a real phone displaying this page. One person tells me he tried, but that the flash on his camera washed out the display! I feel like I'm in UFO-land here. Everyone believes WML exists but nobody can actually prove it.
Opera Software has released version 5.0.2 of their namesake Opera Web browser for Windows. Opera supports XML, CSS, and WML. Version 5.0.2 adds numerous minor enhancements and features. Opera 5.0 is adware/payware (your choice).
I'm still looking for a photo of this Hello World page on a cell phone. Please note: I need an actual photo of a real phone. A screen capture of an emulator is not enough. (I wonder what it says about the adoption of WML when I'm getting multiple submissions of emulator screenshots, but no pictures of actual phones? I suspect it means this technology is in even worse shape than I thought. Everyone's developing for it, but nobody's using it.)
eXist, an open source repository and search engine for XML documents, is now in public alpha release. It comes XPath and fulltext search. MySQL is used as the backend.
Fourthought, Inc. has posted version 010.1 of 4Suite, a collection of open source tools for standards-based XML, DOM, XPath, XSLT, RDF XPointer, XLink object-database, and XInclude development in Python Components include 4DOM, 4XPath and 4XSLT, 4RDF, 4ODS, 4XPointer, 4XLink and DbDOM. New features and fixes in this release include:
unparsed-entity-uri
evaluate(),
distinct(),
split(),
range(),
if(), and
find()
I'm still looking for a photo of this Hello World page on a cell phone.
James Clark has updated his TREX schema language to refine the way it handles merging included grammars. He's also written a complete implementation of XHTML modularization in TREX, something that still doesn't exist for W3C XML Schemas.
Jonathan Borden's
posted a new
draft of the Resource Description and Discovery Language (RDDL).
RDDL is a modular XHTML and XLInk based application for documents
placed at the end of namespace URIs which allows software to automatically discover and retrieve
DTDs, schemas, style sheets, and other resources for particular XML applications.
The major change in this draft at the URL that used to be the value
of
xlink:arcrole is now the value of
xlink:role,
and
xlink:arcrole can be used to provide an
additional URL further refining the role.
Furthermore, MIME types like text/css can now be used as
roles through their canonical URLs at the IETF such as.
Finally, RELAX
and TREX schemas for RDDL havve been added as one more kind
of related resource for this document.
Andrew Watt's opened which is perhaps the world's first "all SVG" web site. The Adobe SVG Browser Plug-in is required.
I have unusual request today. Would somebody with a WAP-enabled cell-phone and a digital camera please take a picture of this Hello World page on their phone and send it to me? The URL is I'd do it myself, but it seems that VoiceStream's rather clueless representatives misinformed me about which of their phones supported WAP.
This is for a new chapter about the Wireless Markup Language in the second edition of the XML Bible. The first person to send me a usable picture will get a free copy of the second edition of the XML Bible when published later this year. You'll need to sign a not-particularly onerous photo permissions agreement giving IDG non-exclusive rights to publish the picture. The agreement doesn't promise a photo credit, but I'll try and make sure you get one. Please take the picture at maximum resolution and quality, since this is intended for print rather than a web page. Thanks!
The XML Apache Project has posted Xalan-Java 2.0.D07. Xalan-Java is an XSLT processor written in Java. Along with performance enhancements and bug fixes, this release adds a compatibility layer that lets you rebuild your existing Xalan-Java 1.x applications to take advantage of the performance and conformance enhancements in Xalan-Java 2.
Version 3.1 of the Enhydra application server has been released.
This release focuses on XMLC,
adding compile time includes, updated XML and HTML parsers (Xerces
v1.2 & HTML Tidy), a Lazy DOM implementation,
the Xalan XSLT parser, and assorted bug
fixes.
The fourth beta of the XML Spy 3.5 tree-based XML editor has been released. New features in this beta inlcude:
xsi:type
xsd:list
whiteSpacefacet
In addition, a lot of bugs in the schema support have been fixed, and the schema validation has been optimized for speed and memory usage.
Enhydra's released the stand-alone version of XMLC 2.0. XMLC is a web application framework that "provides high level APIs to DOM and servlet 2.2 technologies." This is the version of XMLC that was bundled with Enhydra 3.1. It adds all of the classes necessary to run XMLC in a non-Enhydra environment. New features include:
Sebastian Rahtz has released PassiveTeX 1.4, his XSL-FO-to-TeX converter.
Zvon's published their first attempt at a W3C XML Schema Reference.
Readers in Silicon Valley may be interested in an upcoming Sun Headquarter Briefing on Java Technology + XML, Wednesday January 31, 2001 in Menlo Park. You can register online or call (800) 795-7578.
Norm Walsh has published a W3C XML schema for DocBook.
Mozilla 0.7 has been released. Version 0.7 bundles the Personal Security Manager so secure sites should work now. There are lots of other bug fixes and minor feature improvements.
IBM's alphaWorks has upgraded Data Descriptors by Example (DDbE) to support the October 24 XML Schema Candidate Recommendation. DDbE is a Java program that generates schemas and DTDs from representative sample documents.
The W3C XML Linking Working Group has pushed the XPointer specification back to working draft status. The specific issue that was uncovered during Candidate Recommendation was some confusion over how to integrate XPointers, particularly those in non-XML documents, with namespaces.
It's also come to light in this draft that Sun has claimed a patent on some of the technologies needed to implement XPointer. I think this is particularly offensive because Eve L. Maler, a Sun employee, served. The specific patent is United States Patent No. 5,659,729, Method and system for implementing hypertext scroll attributes, issued to Jakob Nielsen in 1997.. Last Call on this draft ends January 29, 2001. I recommend complete rejection of this specification until such time as Sun's patent can be dealt with more reasonably.
The W3C Math working group has promoted MathML 2.0 to Proposed Recommendation. Changes in this draft are quite minor, and mostly editorial or corrections of minor inconsistencies. Review Ends February 5, 2001
Zvon's updated their MathML reference to reflect the Proposed Recommendation.
James Clark of XSLT fame has thrown his hat into the ring for developers of XML Schema languages. According to Clark, TREX (Tree Regular Expressions for XML)".
RenderX has released version 2.0.1 of the XEP XSL Formatting Objects to PDF converter program. Changes include:
Brendan Macmillan's Java Serialization to XML, JSX (current version 0.71) generates XML documents that represent Java objects and vice versa.
The XML Apache Project has posted Xalan-Java 2.0.D06. This is a beta Developer's release of the popular open source XSLT processor. Xalan-Java 2.0.D06 supports XSLT 1.0, XPath 1.0, and the Java Transformation API for XML (TrAX). Version 2.0D6 adds some performance and error-handling enhancements along with bug fixes.
Rick Maddy's released 0.92 of XSLDoc, a JavaDoc like program for documenting XSLT style sheets. This release enables
The third beta of the XML Spy 3.5 tree-based XML editor has been released. New features in this beta inlcude:
The download is several megabytes. XML Spy is $199 payware. The beta is free, but beta testers will likely not receive the customary free copy of the release version for doing unpaid work for the software vendor.
The W3C Speech Interface Framework Working Group has published three new working drafts, including two in last call and one new one:
Adobe's posted the second beta the Adobe SVG Viewer 2.0, a plug-in for Netscape and IE on both Mac and Windows that supports much of the candidate recommendation of Scalable Vector Graphics.
Multiple competing proposals for an XML Catalog syntax are being posted on xml-dev every day. The goal is to come up with something reasonably extensible and indirect to place on the other end of namespace URIs. Sean Palmer's posted a proposal for XML Namespace Gloss, XNGloss. Most recently Jonathan Borden and Tim Bray have combined forcces for the Resource Directory Description Language (RDDL). According to.
Everybody's copying the ideas they like from everybody else, so it's hard to keep track of who's doing what. However, there does seem to be some real disagreement about both functionality and syntax, so there are some real differences between the various proposals.
Howard Katz's XML Query Engine v0.92 is a JavaBean that lets you index and search XML documents for element, attribute, and full-text content. The query language is a draft form of XQL, which is close to a subset of XPath. XML Query Engine extends XQL's syntax to provide a full-text search. Licensing remains to be worked out, but it's not open source. At least for the moment, it's free-beer.. | http://www.ibiblio.org/xml/news2001.html | CC-MAIN-2015-06 | refinedweb | 43,195 | 64.71 |
I have sometimes wondered if the 'with' statement would work in C/C++, just like in pascal. Meaning that it would in it's nearest scope automatically recognize class/struct members for the ones mentioned with a . or maybe -> operator.
Maybe something like:
TestClass* tc;
float test;
...
with tc {
test = .memberx * .membery;
}
Would that cause confusion in code or unsafe exposure of variables ... like opposite to namespace perhaps?
And another thing, why can't we specify the data size for enums? That cause problems when accessing data over different architectures or networks.
I know that C++0X will have that, but maybe this should go into the langauge. | http://www.codeproject.com/Tips/136183/Cplusplus-Syntax-Uncovered | CC-MAIN-2016-30 | refinedweb | 108 | 69.48 |
Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
5 years ago.
Why does this function crash my program?
This program function causes my program to instantly crash. A print imediately before the function call works, but the first print int the function is never reached. I believe it is a memory issue but i want to know why it crashes on the function call and not later. I am using a an Embedded Artist QSB with a LPC11u35 with 8kB ram.
int writeFrame(SPI my_spi, int Address) { pc.printf("\nWrite Frame"); char UARTDataBuffer [64]; //Creat a buffer for recived data char memoryBuffer [bufferSize]; //Create a memory buffer, to be sent to flash, bufferSize = 3840 int bufferIndex = 0; //points to the next available possition in memory while(bufferIndex<bufferSize){ waitForData(UARTDataBuffer); //Wait for data on UART and store received data in UARTDataBuffer bufferIndex=appendBuffer(UARTDataBuffer, memoryBuffer, bufferIndex); //copy UARTDataBuffer to the memoryBuffer. If I comment out this line the function runs fine. printf("\ntest"); } //Write the Buffer to flash memory mem.blockErase(my_spi, Address); mem.blockErase(my_spi, Address+0x10000); Address = mem.writeData(my_spi, memoryBuffer, Address, bufferSize); printf("\nblest"); return Address; }
1 Answer
5 years ago.
look at
Your function allocates 3840 bytes (I hope your variable buffersize is really initialized !) to the stack ....and your total memory is only 8k.
How do you implement appendbuffer ?
If you need such a buffer, I think you need a board with more memory.
Thanks for you response. What confuses me is that it crashes immediately when i call the function. As I understand it, if there is not enough memory for the buffer it should crash when Iinitialise the buffer, or when i try to modify the buffer. Here is the appendBuffer code
int appendBuffer(char UARTDataBuffer[], char memoryBuffer[], int bufferIndex) { int posIndex=0; for(int i = 0; i < 64; i++) { memoryBuffer[bufferIndex+i]=UARTDataBuffer[i]; posIndex++; } return (bufferIndex+posIndex); }
You write "As I understand it, if there is not enough memory for the buffer it should crash when I initialise the buffer"
This is how I understand the bug
: 1)the instruction "char memoryBuffer [bufferSize];" allocates a address (a pointer) for the first position in this array, during the function call. 2) Afterwards, you fill the buffer and you destroy some values . This is the famous collision stack/heap
It may not buy you enough space but you can save some memory with the following code change:
pc.printf("\nWrite Frame"); char memoryBuffer [bufferSize]; //Create a memory buffer, to be sent to flash, bufferSize = 3840 int bufferIndex = 0; //points to the next available possition in memory while(bufferIndex<bufferSize){ waitForData(memoryBuffer+bufferIndex); //Wait for data on UART and store received data in UARTDataBuffer bufferIndex+=64; printf("\ntest"); }
This writes the received data directly into the correct location and so you save the 64 bytes of the uart data buffer.posted by 05 May 2016 | https://os.mbed.com/questions/68900/Why-does-this-function-crash-my-program/ | CC-MAIN-2021-21 | refinedweb | 501 | 63.19 |
Components and supplies
Necessary tools and machines
Apps and online services
About this project
Hohoho... Santa is here!.
The idea of this project is simple: Use LEDs to show where the Santa have been and the current location of Santa on a world map. Here is what I get at the end of the project:
System Architecture
Overall the design take use of one raspberry PI and one MKR1000 to process and visualize the Santa data fetched from Google Santa Tracker API.
As you can see the data fetched from Google Santa Tracker API is first put though a Raspberry PI. The reason is that the API response JSON is around 20M which is too big to fit into MKR1000's memory (18M available after my sketch is loaded) for processing. So I'm using a Raspberry Pi 3 to first consume the data, and generate a much smaller data format which is tailer made for my application. The later data is then exposed through a REST API server hosted on Raspberry Pi. The MKR1000 board will call the REST API every 10 seconds to get the current Santa location.
Circuit Design
The MKR1000 is connected to a custom PCB which has 30 WS2812B RGB Neopixel LEDs. Each LED represents one geo location. The idea is blinking the closest LED to where the Santa's current location, and turn on all the LEDs on Santa's past locations.
The PCB is optimized for being produced by Othermill as a double sided PCB, but should be also easily produced through online PCB services like OSH Park.
I spread 30 neopixels on the PCB, forming a world map. You may not be able to see it right now, but after coating with the negative mask and diffuser it would be easier to recognize.
The main consideration here to make this home-milling-friendly is the location of vias. Since the vias are drilled on PCB plate both sides are not connected. So you will need to solder them together on both side through a wire. And because of that, the vias can not be put under a SMT component like they usually do in commercial PCBs.
There are some design considerations behind the PCB file:
- The power is delivered through a thick trunk wire and sinked into another thick ground wire. This is because 30 neopixels will draw quite a lot of current.
- The neopixeles are connected as close as possible to the trunk power wire. This is to reduce voltage drop across multiple neopixels. Different voltage will result in slight difference in brightness and color.
- A 1000 uF capacitor is connected close to the power source. This is recommended best practice to work with neopixels.
- The vias are put outside of other SMT components because they will be connected by soldering both side manually, the solder joint will not fit under another SMT components. This wouldn't be a problem on PCBs produced by commercial services, but should take into consideration when make PCM in home.
- Make sure you leave enough space between wires. It will be easily shorted after soldering because the home made PCB don't have the insulation coat. This can be done in Otherplan application by setting the trace clearance to a larger value than the default 0.006in (e.g. 0.06 in should be good enough). My first fully soldered board was found not working because of short circuit, and it's to hard to fix than just make another one.
- If you are going to work with plenty of SMT components, a hot air rework station will save you tons of time on soldering. Although it's doable, it really doesn't worth the effort to hand-solder the components one by one. And hot air will also make the components align to the the exact position automatically.
World Map Mask and Diffuser
Because the Othermill can mill directly from a SVG, I just use the world map found from wikimedia.org.
I also created another eagle file containing the drill holes. Those holes are used for mounting the mask to the circuit board.
Since I want to get highest possible milling precision, the best way to do that is using the alignment bracket. But the outline will definitely overlap with the bracket. The solution I found was first only cut the map without cutting the outline. Then remove the bracket without telling the software. Then start the milling just to drill holes and cut the outline. The software will use the same tool path to cut the outline at exactly position you want.
Assembly was pretty straightforward. I used 4 M3 Nylon long screws, 4 standoffs and 4 nuts.
Raspberry Pi Preprocessing Server
The response from Google Santa Tracker API is a huge JSON file. This may be a problem for MKR1000, but not a problem at all for Raspberry Pi 3. So I set up a HTTP server to preprocess the JSON file and produce a smaller data for the MKR1000.
The Raspberry Pi server also maps the location directly to the index of the corresponding LED to further reduce the calculation on the MKR1000. To do this, I first manually assigned a coordinate to each of the LED, and then calculate the distance between each of the location in Santa's path to the LED coordinates, find the closest LED to represent that location.
The server is written in Python, and use the Flask web framework to expose the REST endpoints to the MKR1000.
from flask import Flask import requests import json import math import sys app = Flask(__name__) # Google's Santa API. Only updates on Dec 24. # santa_api_url = '' # My Fake Santa API. santa_api_url = '' # LEDs metadata. leds = [ {'name': 'North Pole', 'location': {'lat': 90.0, 'lng': 30.0}}, {'name': 'Alaska (US)', 'location': {'lat': 64.536117, 'lng': -151.258768}}, {'name': 'Alberta (Canada)', 'location': {'lat': 48.9202307, 'lng': -93.69738}}, {'name': 'Ontario (Canada)', 'location': {'lat': 50.956252, 'lng': -87.369255}}, {'name': 'Utah (US)', 'location': {'lat': 40.7765868, 'lng': -111.9905244}}, {'name': 'Tennessee (US)', 'location': {'lat': 36.1865589, 'lng': -86.9253274}}, {'name': 'Mexico City (Mexico)', 'location': {'lat': 19.39068, 'lng': -99.2836957}}, {'name': 'Bogota (Columbia)', 'location': {'lat': 4.6482837, 'lng': -74.2478905}}, {'name': 'Brasilia (Brazil)', 'location': {'lat': -15.721751, 'lng': -48.0082759}}, {'name': 'Santiago (Chile)', 'location': {'lat': -33.4727092, 'lng': -70.7699135}}, {'name': 'Greenland', 'location': {'lat': 70.8836652, 'lng': -59.6665893}}, {'name': 'UK', 'location': {'lat': 64.6748061, 'lng': -7.9869018}}, {'name': 'Spain', 'location': {'lat': 40.4379332, 'lng': -3.749576}}, {'name': 'Mali', 'location': {'lat': 17.5237416, 'lng': -8.4791157}}, {'name': 'Finland', 'location': {'lat': 64.6479136, 'lng': 17.1440256}}, {'name': 'Greece', 'location': {'lat': 38.2540419, 'lng': 21.56707}}, {'name': 'Libya', 'location': {'lat': 21.520733, 'lng': 23.237173}}, {'name': 'Central African Republic', 'location': {'lat': 6.2540984, 'lng': -0.2809593}}, {'name': 'Botswana', 'location': {'lat': -22.327399, 'lng': 22.4437318}}, {'name': 'Saudi Arabia', 'location': {'lat': 24.0593214, 'lng': 40.6158589}}, {'name': 'Turkmenistan', 'location': {'lat': 38.9423384, 'lng': 57.3349508}}, {'name': 'Xinjiang (China)', 'location': {'lat': 42.0304225, 'lng': 77.3185349}}, {'name': 'India', 'location': {'lat': 20.8925986, 'lng': 73.7613366}}, {'name': 'Henan (China)', 'location': {'lat': 33.8541479, 'lng': 111.2634555}}, {'name': 'Cambodia', 'location': {'lat': 12.2978202, 'lng': 103.8594626}}, {'name': 'Japan', 'location': {'lat': 34.452585, 'lng': 125.382845}}, {'name': 'Australia', 'location': {'lat': -25.0340388, 'lng': 115.2378468}}, {'name': 'New Zealand', 'location': {'lat': -43.0225411, 'lng': 163.4767905}}, {'name': 'South Pole', 'location': {'lat': -90.0, 'lng': 30.0}}, ] @app.route('/santa') def santa(): santa_info = requests.get(santa_api_url).json() santa_time = santa_info['now'] response = [] for dest_json in santa_info['destinations']: if santa_time < dest_json['arrival']: break dist, led, led_index = closest_led(dest_json['location']) response.append({ 'i': led_index, 'd': int(dist), 'n': dest_json['city'], 'p': dest_json['presentsDelivered'] }) return app.response_class(json.dumps(response).replace(' ',''), content_type='application/json') def distance(loc1, loc2, unit='M'): lat1 = loc1['lat'] lng1 = loc1['lng'] lat2 = loc2['lat'] lng2 = loc2['lng'] radlat1 = math.pi * lat1 / 180 radlat2 = math.pi * lat2 / 180 theta = lng1-lng2 radtheta = math.pi * theta / 180 dist = (math.sin(radlat1) * math.sin(radlat2) + math.cos(radlat1) * math.cos(radlat2) * math.cos(radtheta)); dist = math.acos(dist) dist = dist * 180 / math.pi dist = dist * 60 * 1.1515 if unit == 'K': return dist * 1.609344 if unit == 'N': return dist * 0.8684 return dist def closest_led(loc): min_dist = sys.float_info.max min_led = None min_index = 0 for index, led in enumerate(leds): led_loc = led['location'] dist = distance(loc, led_loc) if dist < min_dist: min_dist = dist min_led = led min_index = index return min_dist, min_led, min_index if __name__ == '__main__': app.run(host='0.0.0.0', port=2412)
Since the Google Santa Tracker API only updates on one day (Dec 24) in a year, in order to test the whole system, I also wrote a fake Santa tracker API server simulates the real one. With this fake API server, I can also control the speed of travel and reset as needed. This server is also a Flask Python server, run on a different port on the Raspberry Pi 3.
from flask import Flask, request import json import time app = Flask(__name__) fake_start_time = 0 # initialized to first arrival time from json real_start_time = 0 # set to start time speed_factor = 100 # fake clock speed all_destinations = None current_info = { 'status': 'OK', 'language': 'en', 'now': None, # Will be set to fake time 'timeOffset': 120000, 'fingerprint': '3b8835bc354c6d5018344b289b833402f7079844', 'refresh': 51449, 'switchOff': False, 'clientSpecific': { 'DisableEarth': False, 'DisableTracker': False, 'DisableWikipedia': False, 'DisablePhotos': False, 'HighResolutionPhotos': False, 'EarthAltitudeMultiplier': 1 }, 'routeOffset': 0, 'destinations': None # Will only have destinations up to two towns ahead } @app.route('/info') def info(): if real_start_time != 0: advance_fake_time() return app.response_class(json.dumps(current_info), content_type='application/json') @app.route('/start') def start(): global real_start_time, speed_factor real_start_time = real_now() speed_factor = int(request.args.get('speed', '100')) print(u'fake clock stated at speed {0}'.format(speed_factor)) return 'ok' @app.route('/reset') def reset(): global real_start_time real_start_time = 0 current_info['destinations'] = all_destinations[:3] return 'ok' def index_of_current_destination(ts): for i, dest in enumerate(all_destinations): if dest['departure'] > ts: return i return 0 def current_destinations(): index = index_of_current_destination(fake_now()) + 3 return all_destinations[:index] def advance_fake_time(): current_info['now'] = fake_now() current_info['destinations'] = current_destinations() def real_now(): return int(time.time() * 100) def fake_now(): return (real_now() - real_start_time) * speed_factor + fake_start_time def arrival(d): return d['arrival'] def load_json(): with open('santa2016.json') as data_file: data = json.load(data_file) global all_destinations, fake_start_time all_destinations = sorted(data['destinations'], key=arrival) fake_start_time = all_destinations[1]['arrival'] reset() print(u'{0} destinations loaded, fake_start_time={1}'.format(len(all_destinations), fake_start_time)) if __name__ == '__main__': load_json() app.run(host='0.0.0.0', port=1224)
MKR1000 Firmware
Now the MKR1000 is ready to fetch the data from Raspberry Pi server, and turn LEDs on and off.
#include <SPI.h> #include <WiFi101.h> #include <Adafruit_NeoPixel.h> #include "JsonStreamingParser.h" #include "JsonListener.h" #define LED_PIN 6 #define LED_NUM 30 #define BRIGHTNESS 50 Adafruit_NeoPixel strip = Adafruit_NeoPixel(LED_NUM, LED_PIN, NEO_GRB + NEO_KHZ800); char ssid[] = "YOUR_SSID"; // your network SSID (name) char pass[] = "YOUR_PWRD"; // your network password int keyIndex = 0; // your network key Index number (needed only for WEP) int status = WL_IDLE_STATUS; IPAddress server(192, 168, 1, 120); // numeric IP for RPI server //char server[] = "rpi3.local"; // name address for RPI server char endpoint[] = "/santa"; int port = 2412; // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): WiFiClient client; class Led { public: String name; int distance; int presents; boolean on; }; Led leds[30]; class LedSwitcher: public JsonListener { public: void whitespace(char c) {} void startDocument() {} void key(String key) { Serial.println(key); currentKey = key; } void value(String value) { Serial.println(value); if (currentKey == "i") { ledIndex = value.toInt(); } else if (currentKey == "p") { presents = value.toInt(); } else if (currentKey == "d") { distance = value.toInt(); } else { name = value; } } void endArray() {} void endObject() { Serial.println("End of Object"); Serial.print(ledIndex); Serial.print(":"); Serial.print(name.c_str()); Serial.print(","); Serial.print(presents); Serial.print(","); Serial.print(distance); leds[ledIndex].on = true; leds[ledIndex].name = name; leds[ledIndex].presents = presents; leds[ledIndex].distance = distance; } void endDocument() {} void startArray() {} void startObject() {} int lastLed() { return ledIndex; } private: String currentKey; int ledIndex; int presents; int distance; String name; }; LedSwitcher ledSwitcher; void connectToWifi() { //(); } boolean connectToSantaServer() { Serial.println("Starting connection to server..."); return client.connect(server, port); } void ensureConnected() { if (!client.connected()) { while (!connectToSantaServer()) { Serial.println("Failed to connect to server. Retry in 5 seconds"); delay(5000); } Serial.println("connected to server"); } } void fetchSantaInfo() { ensureConnected(); // Make a HTTP request: client.print("GET "); client.print(endpoint); client.println(" HTTP/1.1"); client.print("Host: "); client.println(server); client.println("Connection: close"); client.println(); int bytes = 0; boolean isBody = false; JsonStreamingParser parser; parser.setListener(&ledSwitcher); Serial.println(); Serial.println("Received response:"); Serial.println(); while (client.connected()) { while (client.available()) { char c = client.read(); ++bytes; //Serial.write(c); if (isBody || c == '[') { isBody = true; parser.parse(c); } } } Serial.println(); Serial.println(); Serial.println("Disconnecting from server."); client.stop(); Serial.print("Received: "); Serial.print(bytes); Serial.println(" Bytes."); } void flashLastLed() { strip.setPixelColor(ledSwitcher.lastLed(), strip.Color(0, 0, 0)); strip.show(); delay(500); strip.setPixelColor(ledSwitcher.lastLed(), strip.Color(255, 0, 0)); strip.show(); delay(500); } void setup() { //Initialize serial and wait for port to open: Serial.begin(9600); strip.setBrightness(BRIGHTNESS); strip.begin(); strip.show(); // Initialize all pixels to 'off'. connectToWifi(); fetchSantaInfo(); for (int i = 0; i < 30; ++i) { if (leds[i].on) { strip.setPixelColor(i, strip.Color(255, 0, 0)); } else { strip.setPixelColor(i, strip.Color(0, 0, 0)); } } strip.show(); } void loop() { fetchSantaInfo(); delay(1000); for (int i = 0; i < 10; ++i) { flashLastLed(); } }"); }
As most of the work has been done on Raspberry Pi, the code here is straightforward. It connects to WiFi, the every 10 seconds it fetches the Santa data from Raspberry Pi, and update the neopixels accordingly.
Now let's power it on:
Conclusion
MKR1000 is very powerful board for IoT applications, but it has its own limits. With the help of more powerful SBC (Single Board Computer) like a Raspberry Pi 3 we will be able to interface with any services with more complex APIs.
Hope you like this project as a little holiday surprise.
Custom parts and enclosures
Schematics
Code
Everything for this project
Author
Bowen Feng
- 1 project
- 2 followers
Published onJanuary 23, 2017
you might like | https://create.arduino.cc/projecthub/user127218626/iot-santa-tracker-on-colorful-world-map-095fe3 | CC-MAIN-2017-13 | refinedweb | 2,351 | 52.15 |
This article was originally written in December 2002 as part of the ACCU Mentored Developers [MDevelopers] XML [XMLRec] project. It has now been revised, with considerable help from Jez Higgins, for publication in Overload.
The first exercise set for the project students by the project mentors was as follows:
Incorporate either the Xerces[Xerces] or Microsoft XML[MSXML] parsers into a C++ project and use it to:
Parse XML strings and files.
Output the element structure as an indented tree.
As most of my development experience has been on Windows I followed the MSXML route.
The MSXML parser can be downloaded from the Microsoft website. The latest version at the time of writing is version 4.0 and requires the latest Windows installer, which is incorporated into Windows XP and comes with Windows service pack 3. The installer can also be downloaded as single executable [InstMsi].
Assuming the latest Windows Installer is present on your system installing MSXML is simply a case of running the installer package. As MSXML is Component Object Model (COM) based this will register the MSXML dynamic link library (msxml4.dll). The installer also creates a directory with all necessary files needed to use the parser in a C++ project.
Although there are the usual Microsoft help files incorporated with MSXML there aren't any examples, so I used Google to try and find some and found the PerfectXML[PerfectXML] website. The website includes a number of MSXML C++ examples and one in particular, Using DOM [UsingDOM], that downloads an XML file from an Internet location, parses it, modifies it and writes it to the local hard disk. I used this example as a template for the following simple MSXML console application test program:
#include <iostream> #include <string> #include <windows.h> #include <atlbase.h> #import "msxml4.dll" int main() { std::cout << "MSXML DOM: Simple Test 1: Creating" << " of COM object and parsing of XML.\n\n"; ::CoInitialize(0); { MSXML2::IXMLDOMDocument2Ptr pXMLDoc = 0; // Create MSXML DOM object HRESULT hr = pXMLDoc.CreateInstance( "Msxml2.DOMDocument.4.0"); if (SUCCEEDED(hr)) { // Load the document synchronously pXMLDoc->async = false; _variant_t varLoadResult((bool)false); const std::string xmlFile("poem.xml"); // Load the XML document varLoadResult = pXMLDoc->load(xmlFile.c_str()); if(varLoadResult) { std::cout << "Successfully loaded XML file: " << " file: " << xmlFile << "\n"; } else { std::cout << "Failed to load XML file: " << xmlFile << "\n"; // Get parseError interface MSXML2::IXMLDOMParseErrorPtr pError = 0; if(SUCCEEDED(pXMLDoc->get_parseError( &pError))) { USES_CONVERSION; std::cout << "Error: " << W2A(pError->reason) << "\n"; } } } else { std::cout << "Failed to create MS XML COM " << "object.\n"; } } ::CoUninitialize(); return 0; }
This program takes the following XML file and parses it:
<?xml version="1.0" encoding="UTF-8"?> <poem> <line>Roses are red,</line> <line>Violets are blue.</line> <line>Sugar is sweet,</line> <line>and I love you</line> </poem>
If the parse fails an error message is written to std::cout giving the reason. Although this code snippet does the intended job, it is a bit rough and needs some work in order to achieve the objective of this exercise. Among other things it would benefit from wrapping of MSXML and some proper exception handling.
It is worth noting #import is specific to Microsoft Visual C++ and is not supported by other Win32 compilers.
I'm going to look at the exercise solution in two parts. The first part will reengineer the PerfectXML example into a more general solution with a clean interface, proper runtime handling and exception handling. The second part will look at writing the element structure to a stream.
As MSXML is COM based, the COM runtime must be started before any COM objects can be instantiated. The COM runtime is started by the CoInitializeEx API function and stopped with CoUninitialize. MSDN states that every call to CoInitializeEx must be matched by a call to CoUninitialize, even if CoInitializeEx fails.
CoUninitialize must not be called until all COM objects have been released. For instance in the example above there is an extra scope wrapping the MSXML code so that the IXMLDOMDocument2Ptr smart pointer destructor is called, destroying the DOM, before CoUninitialize is called.
The easiest way to achieve this, even in the presence of exceptions, is to take advantage of C++'s RAII (Resource Acquisition Is Initialization) and place CoInitialiseEx in the constructor of a class and CoUninitialize in the destructor and to create an instance of the class on the stack, at the beginning of the program before anything else. COMRuntimeInit, shown below, is just such a class. The copy constructor and copy-assignment operator are both private and undefined, to prevent copying. A COMRuntimeInit object has no state and therefore it does not make sense to copy it. This method of preventing copying and some more of the reasons behind it are discussed by Scott Meyers in Effective C++[ECpp].
#include <stdexcept> #include <string> #include <windows.h> class COMRuntimeInit { public: COMRuntimeInit() { HRESULT hr = ::CoInitializeEx(0, COINIT_APARTMENTTHREADED); if(FAILED(hr)) { UnInitialize(); std::string errorMsg = "Failed to start COM " "Runtime: "; switch(hr) { case E_INVALIDARG: errorMsg += "An invalid parameter was " "passed to the returning " "function."; break; case E_OUTOFMEMORY: errorMsg += "Out of memory."; break; case E_UNEXPECTED: errorMsg += "Unexpected error."; break; case S_FALSE: errorMsg += "The COM library is already " "initialized on this " "thread."; break; default: errorMsg += "Unknown."; break; } throw std::runtime_error(errorMsg); } } ~COMRuntimeInit() { UnInitialize(); } private: void UnInitialize() const { ::CoUninitialize(); } COMRuntimeInit(const COMRuntimeInit&); COMRuntimeInit& operator=(const COMRuntimeInit&); };
There are of course times when the initial call to CoInitialiseEx may fail. The cause of the failure can be ascertained from its return value. The obvious way to communicate the cause of the failure to the user is via an exception. This has the drawback that the destructor will not be called when the constructor throws and therefore CoUninitialize must be called manually. For now std::runtime_error will be thrown when CoInitializeEx fails, later on we'll look at a custom exception type.
As stated above, the COMRuntimeInit instance must be declared before any other object on the stack. The instance cannot be put at file scope as it throws an exception if it fails, so the obvious place is at the top of main's scope. A try/catch block is also needed to detect the failure.
#include <iostream> #include "comruntimeinit.h" int main() { try { COMRuntimeInit comRuntime; } catch( const std::runtime_error& e) { std::cout << e.what() << "\n"; } return 0; }
Code that uses COM, as with most Microsoft API code, is just plain ugly and really should be hidden behind an interface. Exercise 1 of the XML project states that either the Xerces parser or the MSXML parser can be used. Ideally they should be easily interchangeable and their use completely hidden from the user. Hiding the ugly code and making the parsers easily interchangeable can be achieved with the Pimpl Idiom, as discussed by Herb Sutter in Exceptional C++ [ExCpp].
The first stage in the exercise is to create the MSXML DOM parser. This is achieved with the DOM class:
// dom.h // Forward declaration so that implementation // can be completely hidden. class DOMImpl; class DOM { private: DOMImpl *impl_; public: DOM(); ~DOM(); private: DOM(const DOM&); DOM& operator=(const DOM&); };
The DOM class will form a basic wrapper for the DOMImpl class which will do all the work. DOMImpl is forward declared, so that its implementation can be completely hidden.
The DOM class implementation is shown below. It creates an instance of the DOMImplclass on the heap in the constructor and deletes it in the destructor.
// dom.cpp #include "dom.h" #include "domimpl.h" DOM::DOM() : impl_(new DOMImpl) {} DOM::~DOM() { delete impl_; }
DOMImpl creates the MSXML DOM parser in the same way as the PerfectXML example:
// domimpl.h #import "msxml4.dll" class DOMImpl { private: MSXML2::IXMLDOMDocument2Ptr xmlDoc_; public: DOMImpl() : xmlDoc_(0) { xmlDoc_.CreateInstance( "Msxml2.DOMDocument.4.0"); } private: DOMImpl(const DOMImpl&); DOMImpl& operator=(const DOMImpl&); };
Both DOM and DOMImpl have private copy constructors and copy assignment operators, again to prevent copying.
The above code does not include any error checking. It is possible for the call to CreateInstance to fail. The msxml4.dll may not be registered, for example. The success or failure of the CreateInstance call can be detected by its return value.
DOMImpl() : xmlDoc_(0) { HRESULT hr = xmlDoc_.CreateInstance( "Msxml2.DOMDocument.4.0"); if(FAILED(hr)) { std::string errorMsg = "Failed to start " "create MSXML " "DOM: "; switch(hr) { case CO_E_NOTINITIALIZED: errorMsg += "CoInitialize has not " "been called."; break; case CO_E_CLASSSTRING: errorMsg += "Invalid class string."; break; case REGDB_E_CLASSNOTREG: errorMsg += "A specified class is " "not registered." break; case CLASS_E_NOAGGREGATION: errorMsg += "This class cannot be " "created as part of an " "aggregate."; break; case E_NOINTERFACE: errorMsg += "The specified class " "does not implement the " "requested interface"; break; default: errorMsg += "Unknown error."; break; } throw std::runtime_error(errorMsg ); } }
We now have three classes which are "copy prevented", with a private copy constructor and copy assignment operator. There is a clearer way to document the fact that a class is not intended to be copied. When used by a number of different classes it also reduces the amount of code.
The NonCopyable class, show below, has a private copy constructor and assignment operator to prevent prevent copying. When another class inherits from NonCopyable, the private copy constructor and assignment operator are also inherited. This both prevents the subclass from being copied and documents the intention. The relationship between NonCopyable and its subclass is not IS-A and therefore the inheritance can be private.
As NonCopyable is intended only to provide behaviour to a derived class, rather than act as a class in its own right, its default constructor is protected, preventing a free NonCopyable object being created. Its destructor too, is protected to prevent a subclass being deleted via a pointer to NonCopyable. To further document this intention, the destructor is not virtual.
class NonCopyable { protected: NonCopyable() {} ~NonCopyable() {} private: NonCopyable(const NonCopyable&); NonCopyable& operator=(const NonCopyable&); };
The NonCopyable class was written by Dave Abrahams for the boost [boost] library. I have recreated it here so that a dependency on the boost library is avoided.
Now that the NonCopyable class is in place the copy constructors and assignment operators can be removed from COMRuntimeInit, DOM and DOMImpl. They can then be changed to privately inherit from NonCopyable.
class COMRuntimeInit : private NonCopyable { ... }; class DOM : private NonCopyable { ... }; class DOMImpl : private NonCopyable { ... };
The MSXML DOM has a method that loads and parses an XML file. While parsing the file it is checked to make sure it is well formed and if there is a DTD or Schema specified it is also validated. If the file cannot be opened, is not well formed or cannot be validated the call fails.
The method is called load and takes a single parameter which is the full path to the XML file. To load and parse an XML file, a similar method can be added to DOMImpl and a corresponding forwarding function added to DOM.
class DOMImpl : private NonCopyable { public: ... void Load(const std::string& fullPath) { xmlDoc_->load(fullPath.c_str()); } };
main can then be modified to call the new function with the path to an XML file.
try { COMRuntimeInit comRuntime; DOM dom; dom.Load("poem.xml"); } catch(const std::runtime_error& e) { std::cout << e.what() << "\n"; }
Once again there is no way of detecting failure and the return value of the MSXML DOM load method must be tested to find out if it failed. If a failure has occurred an exception should be thrown.
void Load(const std::string& fullPath) { if(!xmlDoc_->load( fullPath.c_str())) { throw std::runtime_error(ErrorMessage()); } }
The method of extracting an error message from an MSXML DOM is a little fiddly, so I have placed it in its own function, ErrorMessage.
class DOMImpl : private NonCopyable { public: ... std::string ErrorMessage() const { std::string result = "Failed to extract " "error."; MSXML2::IXMLDOMParseErrorPtr pError = xmlDoc_->parseError; if(pError->reason.length()) { result = pError->reason; } return result; } };
A parse error is extracted from an MSXML DOM as an XMLDOMParserError object. The error description is fetched from the reason property. If no description is available, the bstr_t returned by reason has a length of 0. bstr_t is a wrapper class for COM's native unsigned short* string type. It provides a conversion to const char*, and thus can be assigned to a std::string.
Our main function's body is
try { COMRuntimeInit comRuntime; DOM dom; dom.Load("poem.xml"); } catch(const std::runtime_error& e) { std::cout << e.what() << "\n"; }
Currently the example throws a std::runtime_error if the COM runtime fails to initialise or if there is an XML failure. In both cases the error message is prefixed with a description of the type of error. Exceptions thrown as a result of the COM runtime failing to initialise are probably fatal and it may be appropriate for the program to exit, while for exceptions thrown due to an XML parse fail it might be more appropriate to log the error and move on to the next file.
These different categories of error would be better communicated by the exception's actual type and it is easy to add custom exceptions. Throwing different types of exceptions helps to maintain the context in which the exception was thrown and enables the behaviour of a program to change based on the type of exception that is thrown.
Deriving from std::exception not only means that custom exception types can be caught along with other standard exception types in a single catch statement if necessary, but also provides an implementation for the custom exception object.
class BadCOMRuntime : public std::exception { public: BadCOMRuntime(const std::string& msg) : exception(msg.c_str()) {} };
std::exception's constructor takes a char*, but I know that I will be building exception messages with strings and following the model of std::runtime_error, BadCOMRuntime's constructor takes a std::string.
COMRuntimeInit's constructor must be modified for the new exception:
COMRuntimeInit() { HRESULT hr = ::CoInitialize(0); if(FAILED(hr)) { UnInitialize(); std::string errorMsg = "Unknown."; switch(hr) { case E_INVALIDARG: errorMsg = "An invalid parameter was " "passed to the returning " "function."; break; ... default: break; } throw BadCOMRuntime(errorMsg); } }
and main must be modified to catch the new exception:
try { COMRuntimeInit comRuntime; DOM dom; dom.Load("poem.xml"); } catch(const BadCOMRuntime& e) { std::cout << "COM initialisation error: " << e.what() << "\n"; } ...
The exceptions thrown by DOMImpl are a little more complicated. DOMImpl throws exceptions when two different things happen and therefore requires two different exception types, which should be in some way related. One way to solve this is to have a common exception type for DOMImpl from which two other exception types derive.
DOMImpl is the implementation of DOM and any exception thrown by DOMImpl is most likely to be caught outside DOM. Therefore, to the user of DOM, who is unaware of DOMImpl, it is more logical for DOM to be throwing exceptions of type BadDOM rather than BadDOMImpl.
#include <stdexcept> #include <string> class BadDOM : public std::exception { public: BadDOM(const std::string& msg) : exception(msg.c_str()) {} }; class CreateFailed : public BadDOM { public: CreateFailed(const std::string& msg) : BadDOM(msg) {} }; class BadParse : public BadDom { public: BadParse(const std::string& msg) : BadDOM(msg) {} };
The constructor and Load function in DOMImpl can now be modified to use the new exception types and main modified to catch a BadDOM exception. For completeness sake, we also need a third catch block. The COM smart pointers generated by #import raise a _com_error if a function call fails.
try { COMRuntimeInit comRuntime; DOM dom; dom.Load("poem.xml"); } catch(const BadCOMRuntime& e) { std::cout << "COM initialisation error: " << e.what() << "\n"; } catch(const BadDOM& e) { std::cout << "DOM error: " << e.what() << "\n"; } catch(const _com_error& e) { std::cout << "COM error: " << e.ErrorMessage() << "\n"; }
Now that the DOM is loading and validating XML the next part of the exercise is write the elements to an output stream as an indented tree.
The first step in enabling the elements to be written to an output stream is to pass one in. The obvious way to do this is to is to add a function to DOMImpl, and a forwarding function to DOM, which takes a std::ostream reference.
#include <ostream> class DOMImpl : private NonCopyable { ... public: void WriteTree(std::ostream& out) {} ... };
Modifying main to call the new function means that results can be seen straight away as the WriteTree implementation is developed.
try { COMRuntimeInit comRuntime; DOM dom; dom.Load("poem.xml"); dom.WriteTree(std::cout); } ...
In order to write the complete tree, every element must be visited. Starting with the root element, the rest of the elements can then be visited in a depth-first traversal. I wrote the following function, based on some Delphi written by Adrian Fagg, which gets a pointer to the root element and then calls the function WriteBranch which recurses the rest of the tree.
void WriteTree(std::ostream& out) { MSXML2::IXMLDOMElementPtr root = xmlDoc_->documentElement; WriteBranch(root, 0, out); }
The WriteBranch function is also based on Adrian Fagg's Delphi code. The code is self explanatory, but basically it:
Gets the tag name of the element passed to it.
Writes tag names to the supplied std::ostream at twice the specified indentation.
The supplied element is then used to get a pointer to its first child.
If the child pointer is not 0, it is used to get the node type.
If the node is of type NODE_ELEMENT the WriteBranch method is called again (recursion).
The child pointer is then used to get the next sibling.
If there are no more siblings, the method returns.
void WriteBranch( MSXML2::IXMLDOMElementPtr element, unsigned long indentation, std::ostream& out) { bstr_t cbstr element->tagName; out << std::string(2 * indentation, ' ') << cbstr << std::endl; MSXML2::IXMLDOMNodePtr child = element->firstChild; while(child != 0) { if(child->nodeType == MSXML2::NODE_ELEMENT) { WriteBranch(child, indentation + 1, out); } child = child->nextSibling; } }
The result of running the program is now that the following is written to the console:
poem line line line line
With that the exercise is complete.
The logical next step would of course be exercise 2. However, as well as completing the exercises which help the students learn about XML, one of the aims of the ACCU Mentored Developers XML Project is to write a standard interface behind which any parser, such as MSXML or Xerces can be used. Therefore, the next step is to design a common interface to the DOM.
Paul Grenyer and Jez Higgins
Thanks to all the members of the ACCU Mentored Developers XML Project, especially Adrian Fagg, Rob Hughes, Thaddaeus Frogley and Alan Griffiths for the proof reading and code suggestions.
[boost] The boost library:
[DOMRec] W3C Document Object Model (DOM):
[ECpp] Scott Meyers, Effective C++: 50 Specific Ways to improve Your Programs and Designs. Addison Wesley: ISBN 0-201-9288-9
[InstMsi] Windows Installer 2.0: ?FamilyID=4b6140f9-2d36-4977-8fa1-6f8a0f5dca8f &displaylang=en
[MDevelopers] ACCU Mentored Developers:
[MSXML] Microsoft XML parser: &displaylang=en
[PerfectXML] PerfectXML:
[UsingDOM] Using DOM:
[Xerces] Xerces XML parser:
[XMLRec] Extensible Markup Language (XML): | https://accu.org/index.php/journals/238 | CC-MAIN-2019-47 | refinedweb | 3,131 | 54.83 |
I.
Pingback from Twitter Trackbacks for Enterprise Search Web Parts are still Sealed! Unseal them! (SP2010) - Corey Roth - DotNetMafia.com - Tip of [dotnetmafia.com] on Topsy.com
Pingback from Sharepoint 2010 Search Web Parts unsealed (partially)
This post was mentioned on Twitter by jthake: #SharePoint #Link: Enterprise Search Web Parts are still Sealed! Unseal them! (SP2010) - Corey Roth - DotNetMafia.c...
Well... you do what you always do with legacy code problems like this: you create your own wrapper class that uses same public interface as class you are wrapping. Wrapper class will be unsealed and allows extending. That's all you can do going nice way.
Of course... if you are brave code terrorist and you are very sure what you do then you can always to what you ever you want to do using reflection and dynamically created code. It is way more complex thing to do and harder to debug but at least on dynamic level you can create copy of sealed class and make it unsealed. I suggest you to find better method than this.
I forgot to mention quickest way. Take Reflector and disassemble sealed class. Add it to your project withoout sealed keyword. In this case you have to be ready to modify disassembly results because code that Reflector disassembles may be problematic.
The other option is more complex. Use ILDASM to generate IL file based on sealed class. Remove sealed keyword, change namespace and/or class name and create DLL using ILASM. You can reference this DLL from your projects.
Good comments. The code terrorist way is actually the way the wildcard search web part works (via reflection).
wildcardsearch.codeplex.com
It's not pretty but it does work somewhat successfully. I've only had one real case reported where it was a real performance issue. | http://dotnetmafia.com/blogs/dotnettipoftheday/archive/2009/12/09/enterprise-search-web-parts-are-still-sealed-unseal-them-sp2010.aspx | CC-MAIN-2018-05 | refinedweb | 302 | 67.04 |
Let's create a modular Groovy application! Why?! Modularity is an enabler of scaleability. As your Groovy application increases in size, you increasingly need to manage code dependencies, structure your code in units that are larger than packages, and distribute pieces of your application to developers located in different locations and conflicting time zones. Welcome to modularity.
The NetBeans Platform already provides it (plus, OSGi is coming to the NetBeans Platform). Beyond modularity, there are specific features that the NetBeans Platform provides that will remain unique, such as a shared filesystem for intermodular communication and the concept of "context" (i.e., NetBeans Lookup), which not only applications have (as with the JDK 6 ServiceLoader class), but NetBeans Platform objects such as windows themselves. Welcome to loosely coupled modularity.
Now, let's get started.
- Start up NetBeans IDE 6.5.
- Go to this page and download the Groovy Console Template and use the Plugin Manager (in the Tools menu) to install it into the IDE.
- Now, in the New Project dialog, you should see this new project template:
- Click Next, give your new application a name (such as "HelloWorld") and a location on disk, and then click Finish. Expand a few folders and you should now see this:
Briefly, the template gives you a Groovy POJO, with this content:
package org.my.app
public class DemoPojo {
def foo
}
The template also gives you a ModuleInstall class, which handles the lifecycle of the module:
package org.my.app
import org.openide.modules.ModuleInstall as MI
public class Installer extends MI {
@Override
public void restored() {
for(int i = 0; i < 10; i++) {
DemoPojo dp = new DemoPojo()
dp.setFoo(i)
println("Number: " + dp.getFoo())
}
}
}
So, we have some standard Groovy constructs here, simply to get you started in the ecosystem of the NetBeans Platform. The module also includes a properties file for internationalization purposes and a layer.xml file, for the module's contributions to the shared filesystem.
- Run the application (i.e., without doing anything at all, no tweaking, no post processing, nothing at all, just run it). Look in the Output window of NetBeans IDE and you will see this:
So, you can see that you only have the absolute minimum set of modules to start with. Also you're using the Groovy compiler (thanks to an additional target that's added to the demo module's build.xml file). That's how to get started with modular Groovy applications. Have fun with Groovy on the NetBeans Platform!
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/how-create-modular-groovy | CC-MAIN-2016-50 | refinedweb | 428 | 55.95 |
Rejected when making POST calls.Jack Lee Jun 3, 2016 7:56 AM
Dear Qlik users.
I'm trying to integrate with our Qlik Sense service in a .NET-program.
I don't have problem running these tutorials / examples:
Creating a working ASP.NET MVC example ‒ Qlik Sense
Connecting using Microsoft Windows authentication ‒ Qlik Sense
But things seem to get more convoluted for doing POST operations.
I've been trying to copy an app with this request:
POST http://[servername]/QRS/app/0f2e9f6d-360f-475e-a446-f0a7f1da69b6/copy?name=NewPlayground&xrfkey=0123456789abcdef
This is the result:
Error 403 - Forbidden
The initial authentication request must be a GET request in order to be redirected to the authentication module.
OK, so I tried sending this GET-request prior to the POST:
GET http://[servername]/QRS/app?xrfkey=0123456789abcdef&qlikTicket=0MMtH8KE5W6swG8K
This went fine, the server returned the list of apps but this is apparently not enough to create a "session cookie" for the subsequent POST as described here:
Issuing POST commands via the proxy ‒ Qlik Sense
The word "session" is also mentioned here:
Authentication ‒ Qlik Sense
"Using the Session API, whereby an external module can transfer web sessions that identify the user and the user's attributes to Qlik Sense."
Is this somehow connected to the "session cookie" I need for making POST calls? If so, what could this "external module" be?
Someone has asked a similar question less than a week ago:
Qlik Sense Engine API Authorization | Qlik Community
...and the answer is suggesting OP to have a look at QlikAuthNet but it seems to be based on "ticket authentication". But surely, it must be enough authenticate using Windows authentication as described in the following links below?
Default authentication module ‒ Qlik Sense
Authenticating with a Windows user account ‒ Qlik Sense
I can see another person solved this by "using certificates":
Duplicate App using .NET SDK | Qlik Community
But then... what is the Windows authentication for? Only for GET-requests?
Re: Rejected when making POST calls.Gustav Gager Jun 10, 2016 9:28 AM (in response to Jack Lee)
Hi! Did you ever get this to work? Im having the exat same issue. GET request works fine but it doesnt return any cookies and there are no special headers or anything that i can use.
Re: Rejected when making POST calls.Jack Lee Jun 10, 2016 9:38 AM (in response to Gustav Gager )
Hi Gustav.
No I still haven't figured out what to do yet. But I've read the documentation again and I think I understand the concept now. Basically, in my case, Windows authentication is used as the "middle man" to retrieve a ticket from the proxy service but not for authenticating the proxy directly.
It also helps I have access to our QMC so I can see what you can configure in the administration.
I'm going to look a bit further into the "ticket" solution which seems to require a certificate. It can easily be exported from the QMC but it's not enough "just" to install it in your local repository and expect QlikAuthNet to work.
Re: Rejected when making POST calls.Gustav Gager Jun 10, 2016 9:47 AM (in response to Jack Lee)
Hi Jack.
Yes im currently working on something similar. I have created a certificate on the server and imported it on my client and now i try to authenticate using the certificate. Im not have much luck though. And i would like to skip tye certificates if i can.
The strange thing is that if i use Postman i can get a POST command working with no problem at all...
Re: Rejected when making POST calls.Jack Lee Jun 13, 2016 8:18 AM (in response to Gustav Gager )
Hi Gustav.
How did you get the POST command working? I'm using Fiddler.
Request: /GET http://[SERVERNAME:8081]/sense/app/0f2e9f6d-360f-475e-a446-f0a7f1da69b6
First response:
HTTP/1.1 302 Authenticate at this location
Location: http://[SERVERNAME:4248]/form/?targetId=8375dd73-c7e9-4ff9-b7e7-6dd9040b2d9c
Content-Length: 0
Access-Control-Allow-Origin: http://[SERVERNAME:8081]
Then the second response is a HTML page, seemingly for entering username and password. I'm wondering if the right GET-parameters would lead me to /windows_authentication.
Can you do stuff like CopyApp using POST?
I've gotten hold of the .NET SDK and I can easily do CreateApp but apparently CopyApp, ImportApp and others are only available through the REST API [1] so I'm back to square one.
/Jack
[1] Publishing an app using the .Net API - why not ... | Qlik Community
Re: Rejected when making POST calls.Gustav Gager Jun 15, 2016 3:53 AM (in response to Jack Lee)
Hi Jack!
I did not try Copy App, but i got the "start task" working using Postman (a add-in to google chrome). If i have time later, i can try copy app for you. Post man uses just standard Windows authentication, witch is exactly what i want. But as you know, we cant get it to work.
Have you tried exporting certificates from the server and use thoose with authentication?
Re: Rejected when making POST calls.Jack Lee Jun 15, 2016 11:41 AM (in response to Gustav Gager )
Hi again.
Dunno how I've managed to oversee this page but it looks like a full code sample for retrieving a ticket using server certificates
Connecting to the QPS API using certificates ‒ Qlik Sense
For the arguments to the TicketRequest method, 'user' and 'userDirectory', I had to read their definitions here:
Qlik Sense User Directory Connector API ‒ Qlik Sense
Anyway, the good thing is I can see the program is fetching the QlikClient certificate from my local store. The lesser good thing is that I'm still getting "403 Forbidden" from the QPS.
I had Fiddler running in the background at the same time and this seems to be the underlying cause:
HTTP/1.1 403 No client certificate supplied!
Cache-Control: private, must-revalidate, max-age=0
Expires: Wed, 15 Jun 2016 15:34:23 GMT
Server: QPS/2.1.1.0 Microsoft-HTTPAPI/2.0
Date: Wed, 15 Jun 2016 15:34:22 GMT
Content-Length: 0
Considering the code added the certificate to the request I don't know why I get this... Well, that's enough testing for today.
Re: Rejected when making POST calls.Jack Lee Jun 16, 2016 4:01 AM (in response to Jack Lee)
So, not sure if either Fiddler or re-exporting the certificate actually helped but..
1) I re-exported the certificate from the QMC. I didn't add a secret key nor password. Installed the client.pfx on my developer machine.
2) Ran the code again and this time it works woohoo!
Then because I wanted to see how a proper request/response flow looks like I enabled Fiddler again... This time it returned the "403 Forbidden" error message again. I suppose Fiddler is using its own certificate for https communication which is not what the server expected or something?
So I'm not sure if the code would have worked yesterday if I didn't have Fiddler enabled (i.e. didn't need to re-export the certificate) but I'm getting a proper response including the ticket. So hopefully, now comes the fun part...
Re: Rejected when making POST calls.Gustav Gager Jun 16, 2016 5:25 AM (in response to Jack Lee)
This is great news!
So you basicly just exported the Server certs from the QMC and imported them on you local machine? In my case im building a small application that will run on the local server itself and the certificates are already there so i should be ok.
But did you write your code in C#? Or what did you write it in?
Re: Rejected when making POST calls.Jack Lee Jun 16, 2016 5:30 AM (in response to Gustav Gager )
Yeah, I only imported client.pfx, not the server's. But sounds like you should be ok, assuming you're also developing on the Qlik-server too?
Yes, I'm coding in C#. Code sample can be found here:
Connecting to the QPS API using certificates ‒ Qlik Sense
Re: Rejected when making POST calls.Gustav Gager Jun 16, 2016 10:52 AM (in response to Jack Lee)
Ok. But are you connecting directly to the Engine, or are you going trough the proxy? This error only occurs becuase POSt command have some issues while going trough the proxy. And to go directly, you need the certificates.
Im not programming in C# and i have never done so. Im scripting in a language called autoit and I have only got this to work trough the proxy
Edit: Here is my working code for a standard GET request.
This uses a standard web request with username and password and i query the Proxy, and i get a response.
$key = "ABCDEFGHIJKLMNOP" $password = "password" $objHTTP = ObjCreate("Msxml2.XMLHTTP.6.0") $objHTTP.open("GET","" & $key, False,@UserName,$password) $objHTTP.setRequestHeader("X-Qlik-Xrfkey",$key) $objHTTP.send() ConsoleWrite("Sense API Output: " & $objHTTP.responseText & @CRLF)
But if i do this:
$key = "ABCDEFGHIJKLMNOP" $password = "password" $objHTTP = ObjCreate("Msxml2.XMLHTTP.6.0") $objHTTP.open("POST","" & $key, False,@UserName,$password) $objHTTP.setRequestHeader("X-Qlik-Xrfkey",$key) $objHTTP.send() ConsoleWrite("Sense API Output: " & $objHTTP.responseText & @CRLF)
I get HTML code. The code is basicly a standard page that say i need to make a GET request first.
So does that mean that I need to query the Repository directly? I tried but i just get diffrent errors.
Re: Rejected when making POST calls.Jose Cardenas Sep 30, 2016 6:53 AM (in response to Gustav Gager )
Hi Gustav
I've tried with Postman and no getting result using header config. I've got cookie and everything seems to be alright, but for some reason I've got a XSRF msg and 403 forbidden. Any Ideas?
Re: Rejected when making POST calls.praveena mundolimoole Dec 7, 2016 11:22 AM (in response to Jack Lee)
If you are using WebClient for you QRS API operations use below code to attach cookie to all your HTTP requests.
public class CookierAwareWebClient : WebClient
{
public CookieContainer QRSCookieContainer = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
request.CookieContainer = QRSCookieContainer;
request.UserAgent = "Windows";
return request;
}
} | https://community.qlik.com/thread/219476 | CC-MAIN-2017-43 | refinedweb | 1,731 | 66.33 |
Hello. I'm very new to Java, and I have just recently found a tutorial that I am using. I cut-and-pasted a bit of code -- some code that I saw the tutorial use successfully from the command line -- from the tutorial's website into Eclipse. Here is the code:
Code java:
import java.awt.Canvas; import java.awt.Graphics; import java.awt.FontMetrics; import java.awt.Rectangle; public class AdvancedWindowClass2 extends Canvas { AdvancedWindowClass2() { setSize(200,200); } public void paint(Graphics g) { Rectangle rect; rect = getBounds(); String str; str = "I'm in the center!"; FontMetrics fm = g.getFontMetrics(); int strwidth = fm.stringWidth(str); int y = rect.height / 2; int x = (rect.width / 2) - (strwidth / 2); g.drawString(str,x,y); } }
Eclipse didn't show any errors, so I ran it, and got this error:
Code java:
Exception in thread "main" java.lang.NoSuchMethodError: main
Being new to coding and Java, I have no idea what this means, although my guess would be that Eclipse is searching my code for a "main" method, and not finding it. However, the code that I pasted in didn't have a "main" method, and it worked fine in the tutorial, though that was from the command line. Does that have something to do with the error? If anyone knows the problem, I would really appreciate some help!
Thanks!
--- Update ---
Sorry. That first sentence with a bit confusing. What I meant was that I have just found a tutorial for the Java programming language, and I am using it to learn Java. | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/30675-java-eclipse-code-error-printingthethread.html | CC-MAIN-2015-48 | refinedweb | 258 | 67.65 |
Quick Links
RSS 2.0 Feeds
Lottery News
Event Calendar
Latest Forum Topics
Web Site Change Log
RSS info, more feeds
Topic closed. 5 replies. Last post 3 years ago by diamondpalace.
P3Fans:
Here's a new program we just finished testing called, P3PairPredictor. Based on the last 50 draws, the program outputs( most often) three sets of four numbers. From these numbers you build a set of pairs, at least one of which, often comes up within the next 5 draws.
Below the asterisks is the C Code for the program. For those of you who generated the executable code for the C code we supplied in previous threads, the operation is the same. Just copy and paste the code into your editor and save as P3PairPredictor.c Then run your C compiler on the file. The past draws file has to be called drawsP3.txt. It is a regular text file with the latest draw on top and the oldest on the bottom. No extra characters or spaces. One draw to a line. Play is over a five day period after which the draw file is updated.
Here's an example of 1 cycle of play for the Ky Eve P3. P3PairPredictor gave the following output using the last 50 past draws from May 31, 09 and back:
Pair Number Set -> 1-1-3-5
Pair Number Set -> 1-3-3-5
Pair Number Set -> 1-3-5-5
Pair Number Set -> 3-3-4-5
Pair Number Set -> 3-4-4-5
Pair Number Set -> 3-4-5-5
From these sets we generate the pairs: 11, 13, 33, 35, 15, 55, 33, 34, 35, 44, 45, & 55
The draw results for June 1 - June 5 were: 296, 082, 546, 945, 053. P3PairPredictor
was able to snag the pairs 35, and 45, which appeared in three of the five next draws.
Enjoy!
jayemmar
****************************************************************************
#include <math.h> #include <stdlib.h> #include <stdio.h> int main() { int i, j, temp1, temp2, temp3, temp4, a1, a2, a3, a4, a; int drawCount = 50, hit, results, bound; FILE *in; int drawArray[50], knfArray[10]; int array[360] = { 12,13,14,15,16,17,18,19,23,24,25,26, 27,28,29,34,35,36,37,38,39,45,46,47, 48,49,56,57,58,59,67,68,69,78,79,89, 112,113,114,115,116,117,118,119,122,133,144,155, 166,177,188,199,223,224,225,226,227,228,229,233, 244,255,266,277,288,299,334,335,336,337,338,339, 344,355,366,377,388,399,445,446,447,448, 1123,1124,1125,1126,1127,1128,1129,1134,1135,1136,1137,1138, 1139,1145,1146,1147,1148,1149,1156,1157,1158,1159,1167,1168, 1169,1178,1179,1189,1223,1224,1225,1226,1227,1228,1229,1233, 1244,1255,1266,1277,1288,1299,1334,1335,1336,1337,1338,1339, 1344,1355,1366,1377,1388,1399,1445,1446,1447,1448,1449,1455, 1466,1477,1488,1499,1556,1557,1558,1559,1566,1577,1588,1599, 1667,1668,1669,1677,1688,1699,1778,1779,1788,1799,1889,1899, 2234,2235,2236,2237,2238,2239,2245,2246,2247,2248,2249,2256, 2257,2258,2259,2267,2268,2269,2278,2279,2289,2334,2335,2336, 2337,2338,2339,2344,2355,2366,2377,2388,2399,2445,2446,2447, 2448,2449,2455,2466,2477,2488,2499,2556,2557,2558,2559,2566, 2577,2588,2599,2667,2668,2669,2677,2688,2699,2778,2779,2788, 2799,2889,2899,3345,3346,3347,3348,3349,3356,3357,3358,3359, 3367,3368,3369,3378,3379,3389,3445,3446,3447,3448,3449,3455, 3466,3477,3488,3499,3556,3557,3558,3559,3566,3577,3588,3599, 3667,3668,3669,3677,3688,3699,3778,3779,3788,3799,3889,3899, 4456,4457,4458,4459,4467,4468,4469,4478,4479,4489,4556,4557, 4558,4559,4566,4577,4588,4599,4667,4668,4669,4677,4688,4699, 4778,4779,4788,4799,4889,4899,5567,5568,5569,5578,5579,5589, 5667,5668,5669,5677,5688,5699,5778,5779,5788,5799,5889,5899, 6678,6679,6689,6778,6779,6788,6799,6889,6899,7789,7889,7899}; /* **Open files */ in = fopen("drawsP3.txt", "r"); if(in == NULL) { printf("error in opening drawsP3.txt\n"); getch(); exit(0); } /* ** Zero the frequency array */ for(i = 0; i < 10; i++) { knfArray[i] = 0; } /* ** Get the past 50 draws into memory and then ** loop through the first 20 draws and see if ** there's a pair number set for these draws */ for(i = 0; i < 50; i++) { fscanf(in, "%d", &a); drawArray[i] = a; } results = 0; start: for(i = 0; i < 360; i++) { hit = 0; /* ** Peel off the digits from the pair number set */ temp1 = array[i]/1000; temp2 = (array[i] - 1000*temp1)/100; temp3= (array[i] - 1000*temp1 - 100*temp2)/10; temp4 = (array[i] - 1000*temp1 - 100*temp2 - 10*temp3); for(j = 0; j < drawCount; j++) { /* ** Peel off the digits from this draw */ a = drawArray[j]; a1 = a/100; a2 = (a - 100*a1)/10; a3= (a - 100*a1 - 10*a2); /* ** Check to see if at least one digit matches one ** in the key set */ if((a1 == temp1 || a1 == temp2 || a1 == temp3 || a1 == temp4) ||(a2 == temp1 || a2 == temp2 || a2 == temp3 || a2 == temp4) ||(a3 == temp1 || a3 == temp2 || a3 == temp3 || a3 == temp4)) { /* ** Bump the match count when a match occurs */ hit++; } } /* ** If the at least one number ** in the pair number set matched ** for all draws, print out the key number set */ if(hit == drawCount) { printf("Pair Number Set -> %i-%i-%i-%i\n", temp1, temp2, temp3, temp4); /* ** Signal that a pair number set was found */ results = 1; } } /* ** If no pair number set was found, drop the last draw ** and search again */
if(results == 0) { drawCount = drawCount - 1; goto start; } printf("Enter any key to exit\n"); getch(); close(in); }
Hey JAY
Hope this is another amazing creation of yours.
hello sir.. do you also have an excel worksheet for this? because c code is gibberish to me. i think that it really looks great. :)
I'd be happy to work together with anyone who is proficient in EXCEL programming to convert P3PairPredictor into EXCEL.
I don't consider my self proficient. I am not familiar with C syntax. it appears you are using the 360 fixed numbers and comparing to numbers from last 50 games. kind of lost the intent after that. could not tell how you selected a # for output. a block diagrahm or explaination of the process would be helpful.
thanks for generating new things to try and think about
p8
I have the Pair Play available for Pick 3 and Pick 4. Perhaps if one use it with this they can make. | http://www.lotterypost.com/thread/195324/prev | crawl-003 | refinedweb | 1,112 | 76.25 |
- Write a C program to print all prime factors of a number.
- Wap in C to find all prime factors of given number.
Required Knowledge
- C printf and scanf functions
- For loop in C
- C Program to find factors of a number
- C program to check prime numbers
A Prime Factor of a number is a factor that is also a prime number.
A Prime number is a natural number greater than 1 that is only divisible by either 1 or itself. For Example: Prime factors of 15 are 3 and 5.
C program to print all prime factors of a number using for loop
#include <stdio.h> int main() { int counter, N, i, isPrime; printf("Enter a Number\n"); scanf("%d", &N); printf("List of Prime Factors of %d\n", N); /*Check for every number between 1 to N, whether it divides N */ for(counter = 2; counter <= N; counter++) { /* * If counter completely divides N, * then it is a factor of N */ if(N%counter==0) { /* Check if counter is also a prime number */ isPrime = 1; for(i = 2; i <=(counter/2); i++) { if(counter%i==0) { isPrime=0; break; } } if(isPrime==1) printf("%d ", counter); } } return 0; }
Output
Enter a Number 15 List of Prime Factors of 15 3 5
Enter a Number 50 List of Prime Factors of 50 2 5
Write while loop
| https://btechgeeks.com/c-program-to-find-prime-factors-of-a-numbers/ | CC-MAIN-2021-43 | refinedweb | 226 | 66.81 |
20883/decrypt-result-query-when-using-hyperledger-client-sdk-node
In the Hyperledger Client SDK for Node.js , how can I decrypt the results of the query that are returned in the results variable below ?
tx.on('complete', function (results) {
console.log('Results [%j]', results);
The console.log shows a message like :
Results ["7b22496e766f6963654944223a2269303031222c22436c69656e744944223a2269303031222c224e616d65223a224c656e6f766f2047726f7570204c74642e222c22416d6f756e74223a3130303030307d"]
In this case, it is just a hex-encoded string:
tx.on('complete', function (results) {
console.log('Results:[%j]', new Buffer(results,'hex').toString());
}
should work
I ran into a similar issue to ...READ MORE
Hey, @Piyusha,
Looks like the network did not ...READ MORE
You need to install testrpc globally on ...READ MORE
I am not familiar with SpringBoot, but ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
This was a bug. They've fixed it. ...READ MORE
In a Dev environment, you can first ...READ MORE
The solution to this problem is as ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/20883/decrypt-result-query-when-using-hyperledger-client-sdk-node?show=20885 | CC-MAIN-2021-49 | refinedweb | 194 | 54.39 |
On Wed, 30 Jul 1997, Steve Lamont wrote:
>
> I'm all for just adding
>
> fl_set_menu_timeout( int timeout_sec );
>
> At absolute worst, an environment variable or application resource
> could be used.
>
> Diddling with the forms.h file is (IMHO) the wrong way to go. First
> of all, it breaks the largely consistent API design. It also
> contributes to namespace pollution (again, almost *always* a Bad
> Thing). Finally, it would be hard to implement that way. If you
> include forms.h in several files (quite common) then aren't you going
> to get several instantiations and initializations of the same global?
> A lot of loader/linker programs will barf on that.
>
On reflection, perhaps your are right here SPL - having just dealt
with a nasty bit of (someone elses) code which caused the link/loader
to barf something awful wrt globals ...
I guess I was thinking of a way to hide it away so the default action
(whatever TC decides) is there and it would be hard for the casual
user to diddle with!
I withdraw the idea of stuffing the header!
R.
_________________________________________________
To unsubscribe, send the message "unsubscribe" to
xforms-request@bob.usuf2.usuhs.mil or see
Xforms Home Page:
List Archive: | http://xforms-toolkit.org/old-archive/1997/1369.html | CC-MAIN-2022-05 | refinedweb | 201 | 74.59 |
2.2.2.49 MessageClass
The MessageClass element is an optional element that specifies the message class of this e-mail message. It is defined as an element in the Email namespace.
The value of this element is a string data type, as specified in [MS-ASDTYPE] section 2.7.
The MessageClass element value provides a hint that the client SHOULD use to aid in processing the item. This protocol does not validate that the item has the correct MessageClass element value, nor does it update incorrect values.
The value of the MessageClass element SHOULD be one of the values listed in the following table or derive from one of the values listed in the following table. This protocol supports the following message classes as well as all subclasses of the same namespaces. The values are case insensitive.
In addition, certain administrative messages, such as read receipts and non-delivery reports that are generated by the server, have a message class that is derived from one of the message classes listed in the preceding table. The format of this value is a prefix of "REPORT" and a suffix that indicates the type of report. For these administrative messages, the value of the MessageClass element MUST be one of the following values. The values are case insensitive.. | https://msdn.microsoft.com/en-us/library/ee200767(v=exchg.80).aspx | CC-MAIN-2018-47 | refinedweb | 216 | 53.81 |
Philip or Troy - would you care to prepare and test the backport to ensure
we can commit this for the next 0.9 release, coming within days?
Bill
Philip Martin wrote:
> Troy Heber <troyh@debian.org> writes:
>
>> In any case, this looks like the culprit.
>
> Agreed, I've cc'd dev@a.a.o. The C implementation of apr_atomic_cas
> on the 0.9.x branch is broken on ia64, and probably any other 64 bit
> platform that uses the same code. For the full story see:
>
>
>> apr_uint32_t apr_atomic_cas(volatile apr_uint32_t *mem, long with,
>> long cmp)
>> {
>> long prev;
>> #if APR_HAS_THREADS
>> apr_thread_mutex_t *lock = hash_mutex[ATOMIC_HASH(mem)];
>> if (apr_thread_mutex_lock(lock) == APR_SUCCESS) {
>> prev = *(long*)mem;
>> if (prev == cmp) {
>> *(long*)mem = with;
>> }
>> apr_thread_mutex_unlock(lock);
>> return prev;
>>
>> On a 64-bit machine we end up with a size mismatch and a compare of
>> junk. mem is defined as a pointer to a 32-bit, then a cast to long
>> 64-bit in this case. prev ends up with junk it it and fails the
>> compare prev == cmp that passes on a 32-bit box. In any case this is a
>> bug, not positive if it's the only one.
>
> It looks like it has already been fixed in apr1.2 (as used by apache2.2):
>
> apr_uint32_t apr_atomic_cas32(volatile apr_uint32_t *mem, apr_uint32_t with,
> apr_uint32_t cmp)
> {
> apr_uint32_t prev;
> #if APR_HAS_THREADS
> apr_thread_mutex_t *lock = hash_mutex[ATOMIC_HASH(mem)];
>
> CHECK(apr_thread_mutex_lock(lock));
> prev = *mem;
> if (prev == cmp) {
> *mem = with;
> }
> CHECK(apr_thread_mutex_unlock(lock));
> #else
> prev = *mem;
> if (prev == cmp) {
> *mem = with;
> }
> #endif /* APR_HAS_THREADS */
> return prev;
> }
> | http://mail-archives.apache.org/mod_mbox/apr-dev/200609.mbox/%3C45146E24.8030109@rowe-clan.net%3E | CC-MAIN-2015-35 | refinedweb | 252 | 72.36 |
It’s Our Tree is a social genealogy website. It is the English language site of Verwandt.de, which operates multiple sites to support multiple locales.
One problem with social genealogy sites is that your data is on some server outside your control. Most sites allow you to backup the data to your own PC by exporting it to GEDCOM. It’s Our Tree already offered GEDCOM export, but has now gone one step further, by offering It’s Our Tree Home Edition.
Well, I think it’s real name is It’s Our Tree Home Edition, but the image of the CD cover they posted with their 2008 Oct 13 announcement spells the product name as "Its Our Tree Home Edition". It’s a giggle-worthy production error, That’s what it’s; it is not just a typo or editing mistake, they actually managed to get their own logo wrong. That somewhat embarrassing error is not just on the CD-cover, but in the setup wizard and the program’s About Box as well.
It’s Our Tree Home Edition (IOTHE) is a program for Windows. The CD-cover suggests that the company has produced a CD-ROM to hand out at trade shows and such, but it’s a free download. It is a small download too, less than 3 MB.
The setup wizard allows you to change the installation directory, and I
suggest that you take advantage of it by changing the rather silly "Home
Edition" into "ItsOurTree" or "ItsOurTree Home Edition", so that you’ll actually
know what program it is when you browse the directories. The same goes for the
Start Menu folder.
Other than the need to pick reasonable names, setup was blissfully uneventful and fast.
Once the setup is done, it offers to start the program. The program shows a tip on start-up, and manages to annoy by maximising its window until you size it just once. It does not try to connect to the Internet.
Verwandt.de’s international approach is immediately evident. The program offers a choice of user interface languages; Dutch, English, Spanish, French, German, Polish, Portuguese and Brazilian Portuguese. IOTHE has a menu item to bring up a character map, and it does not bring up some pathetic dialog box with just the 256 "Windows ANSI" characters like Legacy does, but it actually brings up Windows’s Character Map utility, which let’s you pick any Unicode character you like.
The program initially display a menu only, but as soon as you add at least one person, a toolbar appears. I tried creating a tree from scratch to get an initial feel for the program and found the user interface to be fairly straightforward, but way too dialog-happy. You do one thing, you get a dialog, you choose some option, you get another... sigh. It isn’t as bad as TMG or Relatives, but it is annoying.
The program does not include a help file, it includes ten help files; one for every locale it supports. That sounds fantastic, but it isn’t. All the help file contains is the erroneous logo and a link to the website. It doesn’t contain any help, and the web site does not have help pages for the program either. The German help file is the only one with real content. For the other languages, there might just as well be no help file.
Another problem is that the program let’s me edit the tree without ever asking for a filename or saving it. It doesn’t ask whether you want to save until you exit the program. That is rather odd considering that the Home Edition’s raison d’etre is to save your genealogy files locally...
Like other program that allow you to edit without saving to file, IOTHE allows you to edit just one family file at once. You cannot load two files and compare them to each other. You can start it twice, but until the vendor documents this possibility explicitly, I do not recommend taking advantage of it. It might be programming mistake, and if the two instances of the program confuse each other, it might be your data that suffers.
I decided it was time for the usual import tests, but performing these seemed unusually difficult.
I tried creating a new file by choosing File | New and thus walked smack into a serious interface blunder; File | New does not bring a File Open dialog box, it brings up the program’s New Person dialog box instead. There is an Edit | New Person... menu item, yet the File | New menu item does exactly the same; even after creating a person record (which should not be necessary), you still do not get an File Open dialog box. You need to go back to the menu and choose File | Save. When you do, the program defaults to saving in a subdirectory of the program directory...
File | New merely annoys with a New Person dialog box and does not make a new file at all. File | Save will save a file, but default to the program directory instead of a proper data directory. I sure do not expect perfection from a 1.0 program, but basic issues like this make me wonder whether anyone at Verwandt ever bothered to try and test this program before releasing it.
There is a "GEDCOM import export" menu item on the file menu, but it is greyed out. When I start creating a file by creating persons, it remains greyed out. When I try to save the file, and specify a file name, the program does not save the file, but pops up a message box cryptic error message instead: "The file format requires the specification of a creator". Only when you click OK does it present a properties dialog box for entering your own details. IOTHE wants you to specify your own details before saving the file, but instead of simply presenting the dialog box, it puts up an annoying messagebox first.
That dialog box has several options. It does not just let me specify my name and address, it also lets me specify the home person and the date format. The date format defaults to YYYY-MM-DD and that may seem right, but it is not, because the format the program export too does not support that format.
The "GEDCOM import export" menu item remains greyed out.
I don’t think there is anything you can do to enable the "GEDCOM import
export" menu item. It seems to be a dead menu item, another indicator that no
one bothered to test this program, yet that matters little.
After playing around with the program for a while, it became obvious to me that it does not have a native file format at all.
It turns out that IOTHE does not have its own file format. It was created to read and write the same GEDCOM files that the It’s Our Tree web site read and writes. You do not need to choose File | Import or File | Export, because File | Open and File | Save already support the GEDCOM format.
Having a date format option for GEDCOM files does not make sense, because GEDCOM’s date format is not configurable but fixed. Now, IOTHE actually supports a few other formats, but the date format option should not be presented for GEDCOM files.
The File | Save had not asked me to specify a character encoding. Turns out that it saved the file in UTF-8. That’s the best possible default encoding, one that will not lose any data. The only complaint here is might be that it did not offer a choice, but every other program should support UTF-8 already.
Now, there is a little thing about UTF-8 that even PAF gets wrong; GEDCOM 5.5 does not allow UTF-8. To use UTF-8, you need to use GEDCOM 5.5.1 - and IOTHE gets this right! The GEDCOM it created dos not only default to UTF-8, it also specifies the GEDCOM version as 5.5.1. There are only a few programs that get this right, and IOTHE is one of them.
IOTHE does not automatically save the files you import, so the import speed was measured by first importing the GEDCOM file (File | Open) and then saving it again (File | Save). The time need to navigate to the proper directory and picking a file name thus become part of the total import time.
For the 1 MB GEDCOM the raw import time was about 6 seconds, the save time about 15 seconds, and the total import time 30 seconds. Obviously, a better user interface would allow an import time of 21 seconds, but 30 seconds is not particularly bad.
It ain’t bad, but performance with small files does not mean much, so I moved on to importing the 100k INDI GEDCOM. During import, IOTHE displays nothing but a progress bar. While it takes its sweet time importing the data, its CPU usage keeps hovering around 50 %. The program fails to repaint its main window until the import is done.
Raw import time is 28m14s, but the import is not done until the file has been saved for future use. After file save, the total import time is 38m15s. That’s mediocre performance. It is faster than Legacy 7, even faster than Legacy 6, but slower than Family Tree Maker 16. The older FTM 16 is considerably faster than FTM 2008, but it is not a speed demon. The five year old PAF 5.2.18 is more than ten times as fast as the brand-new IOTHE version 1.0.
There is no import log file. Not in the source directory, not in the target directory, not in the program directory, there just is none.
After exploring the program for a while, I found that it does support the creation of log files, but that this feature, so essential for figuring out whether anything went wrong, has been turned into an option that is off by default. Verwandt really needs to review the default settings of this program.
Alas, turning the import log option on does not provide a real import log. It only
provides you with a dialog box after import that allows you to save a file. That
is not a real import log. A
real import log is written as event occur, so you can see how far an import got
when the program crashes. IOTHE will only offer the option to save an
import
log when it finishes importing your file, much like Family Tree Builder. Such a
post-import report is considerably less useful than a real import log.
A minor issue with changing the options is that the internationalisation
still needs a bit of work. The program shows your Import
GEDCOM options as
benutzerdefiniert. That’s
a rather befuddling word, unless you happen to know that it is German for user-defined.
An import time of some 38 minutes for the 100k INDI GEDCOM is far from the worst import time, but notice that the file save took 10 minutes - and that it take ten minutes every time you save, however small your change, because IOTHE always rewrites the entire file. That is unworkably slow; it is unreasonable to have to wait ten minutes every time you save a change.
During the import phase, memory usage seems fine. According to the Windows Task Manager, IOTHE usage climbed to138 MB, which is acceptable. During export however, the Task Manager showed IOTHE to be using more than 550 MB; IOTHE uses more than half a gigabyte to write a GEDCOM file of just 43 MB.
I was rather unpleasantly surprised to find that the save command did not save to the same file as before, but actually overwrites the file you imported from instead! I have backups and can recreate this file by exporting it from PAF again, but this is a very serious mistake indeed. I should not need the backup because I re-saved a file. It sure reinforces the impression that no one at Verwandt bothered to do even the most basic usability tests.
Overwriting the source file instead of saving the current file is a serious mistake, but it isn’t the worst yet. The worst mistake is that IOTHE bluntly starts overwriting your current file before it is done writing the new file. It deletes the old file before saving the new file. If the application or system crashes during the ten minutes it takes to save the file, a lot of data will be lost.
When the data was loaded, the program did not default to the INDI record with ID 1, but to record 329. I noticed that her last name is Aalbers, but there are other persons called Aafkens, so it is not because she comes first when all persons are sorted alphabetically..
With the data loaded, exiting the program seems to take forever. It is not
saving the file, yet exiting the program actually takes more than half an hour.
During that time, IOTHE fails to repaint its window, and Windows adds the
dreaded "(Not Responding)" to its title bar. Exiting the program is the simplest
operation of all, yet after half an hour, IOTHE was still using 50 % of CPU to
do nothing. I let it run and when I checked back several hours later, the
program had finally exited..
Killing and restarting the program is considerably faster than just exiting it.
Because IOTHE does not offer a choice of encodings on output, I wondered how well it supported different encodings on input. I particular wondered whether it supported ANSEL. I created a small ANSEL file to test it, and discovered that it does support ANSEL on input.
That makes it a bit surprising that it doesn’t support ANSEL output, but not entirely. ANSEL is pretty good character encoding, but it does not support all Unicode characters like UTF-8 does. Exporting to UTF-8 is the right thing to do, so why allow the user to shoot themselves in the foot letting them pick something else?
The only limitation of the UTF-8-only policy is that you cannot import the file into programs that do not support UTF-8, but when you think about it, That’s a good thing too. You really don’t want to import your data into programs that, some 20 years after the introduction of Unicode, 15 years after the formalisation of UTF-8 and nearly a decade since the release of GEDCOM 5.5.1, still do not support UTF-8 GEDCOMs.
IOTHE supports GEDCOM 6, also known as GEDCOM XML. That makes it the first
desktop program to do so. FamilySearch published a GEDCOM XML draft in 2002, but
did not follow that with an actual standard, and seems to have abandoned its
GEDCOM XML effort.
As far as I know, no vendor ever supported it. I noticed that Geni.com toyed with when they were about to add GEDCOM support, but Geni.com currently supports GEDCOM 5.5 as it should.
IOTHE does not just support GEDCOM XML, it also support GedML, which is a fairly straightforward XML variant of GEDCOM 5.5 by Michael Kay.
It even supports Comma Separated Value (CSV), which may come in handy if you want to import to or from a database or spreadsheet.
Export of the 100k INDI file to GedML takes 10m20s, export to GEDCOM 6 takes 14m47s. The export to GedML results in a 60 MB file, the export to GEDCOM 6 in a 75 MB file. The program defaults to same filename for both - it just uses the *.xml extension. It also offers to open the output file once it has created. If you say yes, it opens the file in Internet Explorer. Now, IE can handle XML files, but it just wasn’t designed to open XML files of 75 MB, so it’s best to say no.
The GEDCOM 6 and GedML support are half-hearted; IOTHE will export to GEDCOM 6 and GedML, but not import from it.
This first version does not have many features. There are no reporting
options, there is no HTML output. It does have one feature that far
too many other program lack; a consistency check.
I tried running it on the 100k file. Loading the file is the same as importing a GEDCOM, it takes more than 28 minutes, and waiting so long for your data to load sure is a test of patience.
The consistency check is pretty fast. It took about half a minute to check all records. It is also pretty useless. Once IOTHE is done checking, it presents a dialog box with the results. You can save the text it shows there as a file, but by itself the text is too minimal to make much sense. You can click a line in the results pane to go to the offending record, but when you do so the window disappears, and the program does not even show the message you clicked anymore. What really worries me is that this poor interface made me run the consistency checks again, and that it did not find the same number of issues the second time round. Consistency is the one thing I expect from any computer program, when it does not deliver that, I get really worried.
Nor do I like a flood of messages such as "Child 'Janna' has already different parents:". One or two such messages indicate a problems in the database, a flood of such messages indicates that the program is confused by guardians and adoptions.
You can set the home person, but even when I explicitly opted for record 1 in the options dialog, the program did not show record 1. I tried navigating to it by choosing the Edit | Go To menu item, and that turned out to be a mistake. When you choose that menu item, you do not get a dialog that let’s you enter an ID, but a progress dialog box you have to wait for while the program builds an alphabetical list. That takes about a minute and a half, after which you have to scroll through a list using a dialog box That’s way too small for the purpose.
One silly feature is the statistics menu. How much sense does it make for a program to not even produce an import log, and not have reports, yet show statistics?
Most people have a calling name based on their actual name. For example,
Jeanette is called Jenny, and Albertus is called Albert or just Ab. In Germany,
call names are registered officially, so you’d expect a German program to
have explicit support for call names. Verwandt.de is a German company, yet IOTHE
does not support call names.
There are several menu options for nicknames that strongly suggest that the author confused nicknames and calling names, and is treating these two concepts as if they are one and the same. It does import nicknames correctly.
IOTHE does not support HTML output, and I wonder whether Verwandt will ever want to add it. They are offering IOTHE as an offline editor for your data on ItsOurTree.com. They don’t want you to generate your own web pages, they want you to upload your data to their servers.
You’d expect some option to upload and download your data from within the program, but there is none. There is a File Link option in the Options menu, but that is not to upload your data, it is to associate the *.ged extension with IOTHE.
There is one menu item I don’t even want to try. The edit menu has a "Delete Group.." item. It allows deleting entire groups from your file, such as all ancestors. I have no idea why anyone thought that capability would be a Good Thing, but I am curious now. The German help file describes the option, but does not explain what you need it for. I really look forward to an updated help file that explains just how useful this feature is.
The program directory contains an empty itsourtree.ini file. When the INI file is empty it might just as well not be there, but the bigger issue is that new software should not be using INI files, it should be using the Windows Registry instead.
It’s Our Tree Home Edition appears to have been written in CodeGear Delphi, including Pierre la Riche’s FastMM Borland Edition, a memory manager That’s faster than Delphi’s own memory manager.
IOTHE does not seem to have been created using the fully Unicode-enabled Delphi 2009, but using Delphi 5 with the TNT Unicode Controls. The TNT Unicode Controls were originally offered by TNTWare, but since 2007 Mar 27 part of the TMS Unicode Component Pack. The free but unsupported older versions can still be downloaded from elsewhere on Internet.
IOTHE includes the LibTiff image manipulation library. The current version of LibTiff is 3.8.2 with 4.0 in alpha, but IOTHE uses LibTiff 3.4 Beta 037. LibTiff 3.4 betas were released in 1998.
IOTHE uses zlib by Jean-Loup Gailly and Mark Adler. The current version of zlib is version 1.2.3, released on 2005 Jul 18, but IOTHE uses 1.1.3, released on 1998 Jul 9.
It uses ALQuickSortList. This component is so old that there is hardly any reference to it on the net. It was produced by Arkadia, but the domain name it used back then has been in use by a real estate firm for years.
The setup program is Inno Setup version 5.2. That seems the be the only reasonably recent component, and it is not part of the program itself. Delphi 5 was released in 1999 and all the components used to build this program are about a decade old. That makes you wonder whether the program itself is that old. Perhaps parts of it are, but the program as a whole is not. It supports GedML (1999 Feb 16), GEDCOM 6 (2002 Jan 23) and it has an ItsOurTree.com (2007 Nov 26) logo.
This is a true Unicode program, and it writes UTF-8 GEDCOM 5.5.1 files, but
the user interface seems untested, overall performance is mediocre, and its file
save is not just unreasonably slow, it is dumb and dangerous. IOTHE’s file save function does
not just overwrite the source file but also deletes the current file before
writing a new one. If anything happens while it saving the file, data loss is a
certainty.
Exiting the program takes incredibly long too, but that hardly matters; the aforementioned issues earn it a strong discommendation already.
There is no native format. The program loads and saves to GEDCOM, and does that so slow that you wouldn’t want to use even if it was an otherwise great program. There is no import log file. The program does not support an import log. It only supports the creation of a post-import report, and that option is off by default.
IOTHE does not support ANSEL output, but it does support ANSEL input. Remarkably, it does not just support GEDCOM 5.5.1, but GEDCOM 6 and GedML too. That support is export only, IOTHE won’t import from it. Right now, the support for these formats is largely a curiosity, but to anyone interested in these formats it’s good to know that this program will write it.
The program is multilingual, and has a help file for each locale it supports,
but these files are essentially empty files. The program has few features. The
one feature I was happy to see, the consistency check, disappointed with its
poor implementation. The program will create a few lists, but does not support
proper reports, does not support HTML output, and does not provide upload to or
download from itsourtree.com either. This program should not have been released
as 1.0, but as an early beta.
Although IOTHE is a German genealogy program, it does not support call names.
Many operations brings up a progress dialog box before bringing up the dialog box you really want, and IOTHE does not seem to have been coded for speed. Practically everything about this program is slow. Its lack of performance is about as frustrating as Family Tree Maker 2008.
IOTHE’s memory usage is not as bad as FTB’s. In fact, IOTHE’s memory usage seems pretty reasonable until you decide to write a GEDCOM. Still, its overall performance is plain horrible. Its file load is slow and its file save is slower. The slow load and save are not the performance problem. IOTHE is not as dialog-crazy as TMG, but it is certainly pop-up happy. IOTHE continually annoys by popping up more boxes than necessary. happy and truly aggravates by displaying progress bars before many of its dialog boxes, often making you wait more than a minute. Exiting the program seems to take forever. The performance issues make IOTHE unsuitable for anything but tiny files, with just a few hundred, perhaps a few thousand persons it it.
IOTHE seems have undergone internal testing that is about as rigorous as that for the infamously defective Family Tree Maker 2008. The issues with this program are so basic that they could hardly have escaped notice if Verwandt.de had bothered to do some internal tests at all, but they apparently thought that testing is not necessary.
Right now, IOTHE is a database program without a database, and its performance ranges from poor to pathetic. Most of these performance problems would be solved if IOTHE were upgraded to using some native database system with indexes. That upgrade upgrade should also solve its defective file handling.
IOTHE isn’t a code-page based program like Family Tree Builder. It is a true Unicode program, but it does share basic design mistakes with MyHeritage Family Tree Builder. Its file handling logic is just as broken and just as scarily defective. Like MyHeritage Family Tree Builder, It’s Our Tree Home Edition is a danger is to your data.
It’s Our Tree Home Edition is a danger to your data. This review would have ended with that warning if I had not wondered why there was something familiar about the program, and how an ostensibly new program came to use ten year old technology. The answer, of course, is that it isn’t a new program at all, but one that has been around for a small decade already.
The About Box of It’s Our Tree Home Edition lists the author as Dirk Boettcher. Dirk Böttcher is best known as the author of Ahnenblatt, a German genealogy program. He apparently started development in 1990, and released version 1.0 in 2001.
The first international version was Ahnenblatt 2.50, released in May of this year, and that is what IOTHE seems to be based on. I downloaded Ahnenblatt 2.53, the latest version, and gave it quick whirl.
The It’s Our Tree blog post that announces Home Edition claims that
we developed a free software, but that is simply not true.
It’s Our Tree Home Edition was not developed by Verwandt.de. IOTHE 1.0 is a
re-branded release of Ahnenblatt 2.5.
Well, re-branded and stripped; the original Ahnenblatt program offers a lot more than IOTHE does. Ahnenblatt has a native database format (*.ahn), it supports HTML output, will create a few diagrams, and is available in a portable version, It will create Tiny Tafels, has options to burn to CD and will also export to Plucker, an e-book reader for Palm OS and Windows Mobile devices. Ahnenblatt does not take forever to exit, but exits promptly. It does not take half an hour to load a file, and ten minutes to save a file. After importing into native format, Ahnenblatt takes about three seconds to save the file and about ten seconds to load it again.
Its muscles have been ripped out, and it is left gasping for CPU cycles, to try and move its bones with nothing but skin and tendons.
I’d love to say that IOTHE is a Light edition of Ahnenblatt, but it is a half-destroyed Ahnenblatt. It’s Our Tree Home Edition is not Ahnenblatt Lite but Ahnenblatt Anorexic. It is Ahnenblatt without a native database format. Its muscles have been ripped out, and it is left gasping for CPU cycles, to try and move its bones with nothing but skin and tendons.
Once you know that It’s Our Tree Home Edition is really Ahnenblatt Anorexic, you also know that you should avoid it, and evaluate Ahnenblatt Original instead.
I started this review on 2008 Nov 13 with version 1.0 (1.0.0.4). The program does not check for updates, but I checked the download page, and found version 1.01 (1.0.1.1). Neither the download page, nor the versions.rtf file included with the program details what the differences are.
The It’s Our Tree blog announced the software on 2008 Oct 13. Now, two weeks later, the company issued a press release which starts off with
Users have to pay up to 84,- USD for family tree software at Amazon.com. However, today the family social network itsourtree.com has released its desktop software called “Home Edition.”.
That sounds as if It's Our Tree Home Edition is the first and only free genealogy software on the planet, which is emphatically not the case.
The press release claims that the
Home Edition offers state-of-the-art usability and technology., but the truth is that the technology it uses is ten years old, many versions behind
and no longer supported, and its user interface is far from state-of-the art, but would in fact be unremarkable on Windows 95. Apparently, the It’s Our Tree co-founders do not care much about truth in advertising.
The press release goes on to say:
Itsourtree.com co-founder Sven Schmidt states:Like Google’s strategy of turning the expensive Keyhole software [Earth Viewer] into the free Google Earth, we decided to offer a software that is usually pricy for free.
Co-founder Daniel Grözinger adds:This is athank youfor all the support we have got from our users. This also extends our internet strategy of offering top quality at no cost.
That comparison is not just grandiose - It’s Our Tree is no Google - but
wrong and dishonest too.
It is wrong because Google Earth has several editions, and only the basic edition is free. It is dishonest because the software that It’s Our Tree offers is not
usually pricey at all. It's Our Tree did not buy a company
to start giving their expensive software away, but merely arranged to create
a branded variant of an application that is freeware already. While
Google continues to improve Google Earth at is own expense, It’s Our Tree removed features from
Ahnenblatt to make their Home Edition. They did that in such a way that Home
Edition is a danger to your data - that is a far cry
from
top quality.
It’s Our Tree has changed its name to dynastree (all lower-case), perhaps in part because of the problems it had spelling its name. Consequently, It’s Our Tree Home Edition is now known as dynastree Home Edition.
FamilySearch has broken the link to the GEDCOM 6.0 draft. The broken link has been removed.
Please see the GEDCOM Alternatives article for current links to this document. | http://www.tamurajones.net/ItsOurTreeHomeEdition1.0.xhtml | CC-MAIN-2013-48 | refinedweb | 5,333 | 71.75 |
properties v/s constants
aparna chi
Greenhorn
Joined: May 19, 2004
Posts: 16
posted
Dec 28, 2004 08:44:00
0
Consider the scenario that you have some strings in your application. Whose value may change some time in future.
What would be the best possible solution for this?
Using properties file and loading them through resource bundle
or
Using a
java
class which contains public static final strings for the changing values.
Which one is better and why?
Thanks
Stephen Huey
Ranch Hand
Joined: Jul 15, 2003
Posts: 618
posted
Dec 28, 2004 09:31:00
0
I'm not sure I completely understand what's going on...however, the
String
class is immutable. You can't modify a String (if you try to, it creates an entirely new object and leaves the original unchanged). Of course, depending on what's going on, your references might be changing and pointing to different objects...
pascal betz
Ranch Hand
Joined: Jun 19, 2001
Posts: 547
posted
Dec 28, 2004 09:38:00
0
i would go for properties files and ResourceBundles. You can send these files to editors/translators, can pack different versions of it with different releases and can also provide several languages with your app.
pascal
aparna chi
Greenhorn
Joined: May 19, 2004
Posts: 16
posted
Dec 28, 2004 09:54:00
0
We have some string constants like key1 = "value" in our system. These constants are used in multiple places throughout system using the key e.g. key1 here.
There are two ways of accessing these
1) I make a properties file constants.properties in which i put the values as key1 = value. And then access them through resource bundle.
2) I make a java class like:
public class ConstantsClass
{
public static final String key1 = "value";
}
and now access them as ConstantsClass.key1 wherever i need them.
So I want to know the which is best solution 1 or 2. I am saying that 1 is better and some are saying 2 is better. Their argument is that it will be resource intensive to have a properties file. I am saying that since it is web application which will utimately deployed as an ear , if we use a constants class we will have to rebuild and redeploy the whole application even for some small change.
I basically want to know the concrete differences between two apporaches and their effect on application. And which one to use in which case. Basically what's the better way and why in such situation.
Thanks for the replies.
David Harkness
Ranch Hand
Joined: Aug 07, 2003
Posts: 1646
posted
Dec 29, 2004 00:45:00
0
The approach to take, as usual, depends on how these strings are being used by your application. Your only constraints are that it's a web application and the strings "may change some time in [the] future." The frequency of change would be first priority to me.
If you want to change them at runtime and see the results immediately (e.g. queries or display formats), you can externalize them (properties files, resource bundles, database, etc), but you'll also need methods to reload them dynamically without redploying. If redploying is okay, it's far easier.
Keep in mind that if you externalize them, you still need a compile-time constant with which to find the real value. Consider a date format string, originally as a constant.
public static final String DATE_FORMAT = "mm/dd/yyyy";
If you put it into a properties file,
date_format = mm/dd/yyyy
you will now need to put its key into a constant so you can access its value.
public static final String DATE_FORMAT_KEY = "date_format"; ... String format = props.get(DATE_FORMAT_KEY);
And of course remember the YAGNI principle. Are you so sure up front that the values will change frequently enough to warrent the extra development effort? Of course, if you hide both access methods behind a facade, you won't have to change client code when you change storage methods.
public class ValueFormats { private static final String DATE_FORMAT = "mm/dd/yyyy"; public static String getDateFormat() { return DATE_FORMAT; } }
can be replaced with the following without changing any code that calls it.
public class ValueFormats { private static final String DATE_FORMAT_KEY = "date_format"; private static Properties props = ...; public static String getDateFormat() { return (String) props.get(DATE_FORMAT_KEY); } }
I agree. Here's the link:
subject: properties v/s constants
Similar Threads
Properties file v/s Constants in Java
in the my book appears above, well Properties(); key, value , is it REQUIRED to be <String,String>?
MessageResources are not loaded for three languages, japanese, Turkish, polish
Netbeans GUI Code Doubt
JSP:: How to set a list of values using setProperty?
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/375493/java/java/properties-constants | CC-MAIN-2015-40 | refinedweb | 799 | 63.59 |
#include <c4d_raytrace.h>
Filled by VolumeData::GetSurfaceData().
The surface color at a point.
The reflection color. Note the result of the reflection ray is not part of this color.
The transparency color. Note the result of the transparent ray is not part of this color.
Obsolete.
The reflected ray.
The transmitted ray.
The bump normal.
This is the "caustic generation strength value" for the surface point.
The user can adjust this value in the material, it determines when caustic photons hit the surface point how strong caustics will be generated.
This is the "caustics receive value" for the surface point.
The diffuse component of the color.
The specular component of the color.
The luminance component of the color. | https://developers.maxon.net/docs/Cinema4DCPPSDK/html/struct_surface_data.html | CC-MAIN-2021-10 | refinedweb | 118 | 63.66 |
Diverting trains of thought, wasting precious time.
[/devel] permanent link.
[/devel] permanent link.
[/devel] permanent link.
[/devel] permanent link.
[/devel] permanent link contact....
[/devel] permanent link contact.]
[/devel] permanent link contact
When I was less experienced with C++, I would avoid creating any sort of constness in my code because it invariably led to headaches. When I'd tried, all too often I'd found myself trawling through the source code either adding or removing constness all over the place in order to make things compile. It's certainly true that constness has to be done right or not at all. Like a lot of C++, it's not resilient either to mistakes or to change.
These days I usually make a reasonable job. I've found the best way to understand constness is as follows. Every object in a C++ program exposes exactly two variants of its interface: the “full” one and the const one. The actual boundary between these, at least in the case of user-defined types, is somewhat flexible (as witnessed by mutable, and by your forgetfulness to add const to method definitions!).
Grokking the difference between a const pointer and pointer-to-const is of course a rite of passage in C and C++ programming. A more obscure subtlety about const in C++ is that const references let you pass around temporaries' lvalues, but you can't do this in a non-const fashion. It's not clear why not, except that it's something you'd rarely want to do ---unless, of course, you had omitted to add the const annotation in the signature of whatever function you wanted to pass the lvalue to. That's one reason why getting const right is something you can't really opt out of.
Today I was wrestling with an unfortunate side of const---untraceable compilation errors. I'm using the boost graph library so I can run graph algorithms over my DWARF data structure. Since all my “nodes” live in a std::map, I was specialising the graph_traits giving the map's value_type as the node type. Here's what the compiler said.
/local/scratch/srk31/opt/bin/../lib/gcc/i686-pc-linux-gnu/4.4.3/../../../../incl ude/c++/4.4.3/bits/stl_pair.h: In member function ?std::pair<const long long uns igned int, boost::shared_ptr<dwarf::encap::die> >& std::pair<const long long uns igned int, boost::shared_ptr<dwarf::encap::die> >::operator=(const std::pair<con st long long unsigned int, boost::shared_ptr<dwarf::encap::die> >&)?: /local/scratch/srk31/opt/bin/../lib/gcc/i686-pc-linux-gnu/4.4.3/../../../../incl ude/c++/4.4.3/bits/stl_pair.h:68: instantiated from ?boost::concepts::VertexLi st /local/scratch/srk31/opt/bin/../lib/gcc/i686-pc-linux-gnu/4.4.3/../../../../incl ude/c++/4.4.3/bits/stl_pair.h:68: error: non-static const member ?const long lon g unsigned int std::pair<const long long unsigned int, boost::shared_ptr<dwarf:: encap::die> >::first?, can't use default assignment operator In file included from test-6.cpp:1: /home/srk31/opt/include/boost/graph/graph_concepts.hpp: In destructor ?boost::co ncepts::VertexList /home/srk31/opt/include/boost/graph/graph_concepts.hpp:188: note: synthesized me thod ?std::pair<const long long unsigned int, boost::shared_ptr<dwarf::encap::di e> >& std::pair<const long long unsigned int, boost::shared_ptr<dwarf::encap::di e> >::operator=(const std::pair<const long long unsigned int, boost::shared_ptr< dwarf::encap::die> >&)? first required here make: *** [test-6.o] Error 1
The bottom error refers to line 188 of graph_concepts.hpp, which is doing an innocuous assignment from a vertex iterator v = *p.first;. The variable v is an instance of my map entry type. Somehow, the compiler can't synthesise a copy constructor for the pointed-to vertex. This was incredibly difficult to track down because it wasn't due to any use of const in my code directly. I scoured my code for suspicious const, but to no avail. What had escaped me is that the value_type in a std::map is as follows (from Stroustrup C++PL section 17.4.1.1).
typedef pair<const Key, T> value_type;
In other words, maps are designed so that you can't update the key of an entry once they're created. This is very sane, because to do so might violate some invariant of the containing structure (imagining the popular red-black tree implementation). I hadn't noticed this limitation before because although it's common to initialise new pair objects, it's rare to update an existing one. Even though I had purposely avoided making the whole pair const in my code, there was already a const lurking in the header.
That the compiler couldn't give me a better error message (i.e. one actually pointing to the code at fault) is certainly disappointing, and will be fixed in a better compiler. Whether all this fiddling constness is a weakness with the C++ language I'm not sure. It's certainly self-consistent and well-motivated. Other languages might not have me worrying about const, but they also might not catch certain errors. Is C++'s trade-off good value? It's also not clear whether a better definition of map might not have lifted the const into individual references to the value_type... or not. I'd like to be able to rail and propose some better language design, but part of me suspects that sometimes in programming, the devil really is inescapably in the details.
[/devel] permanent link contact
Here's some innocuous-looking template definitions in C++.
// specialize this template! template <unsigned spec_id> class Extended_By { public: typedef struct {} spec; }; // specialization for Dwarf 3 template <> class Extended_By<0U> { public: typedef empty_def spec; }; template <unsigned spec_id> class table_def : public Extended_By<spec_id>::spec { public: typedef Extended_By<spec_id>::spec Extended; // ... };
I am implementing a delegation hierarchy of tables: lookup methods on the tables delegate to their base implementation if the lookup fails. The hierarchy is rooted at a special-cased “empty” definition (not shown). Each non-root table has a similar implementation, but must be a separate class (as it may want to override certain member functions), hence my use of templates. To define a new table, we specialize the latter template with a new integer argument denoting the concrete table being defined. (In case you're wondering, tables are singletons---but they get pointed-to at runtime, hence virtual dispatch.) The Extended_By template is simply a compile-time mapping from integers (which denote tables) to the type of the underlying table (i.e. the table which that table delegates to, if its lookup fails).
Unfortunately, the code above doesn't compile.
g++ -Wall -O0 -g3 -I/home/srk31/opt/include -I/usr/include/python2.5 -I/usr/incl ude -I../../../libsrk31c++ -c -o "spec.o" "spec.cpp" In file included from spec.cpp:8: spec.hpp:242: error: type `dwarf::spec::Extended_By<spec_id>' is not derived fro m type `dwarf::spec::table_def<spec_id>'
The error message makes no sense at all. In fact, the problem is that the compiler can't tell that Extended_By<spec_id> is a type. If you insert the typename keyword into the latter template definition, as follows....
template <unsigned spec_id> class table_def : public Extended_By<spec_id>::spec { public: typedef typename Extended_By<spec_id>::spec Extended; // ... };
...then it all magically starts working. I must confess I'm not entirely sure why---surely the usual name lookup on Extended_By would work just fine?
On a similar theme, I was specializing some predicates defined by the table template, using code as follows.
template<unsigned spec_id>; }
This also fails to compile, with a very confusing message.
g++ -Wall -O0 -g3 -I/home/srk31/opt/include -I/usr/include/python2.5 -I/usr /include -I../../../libsrk31c++ -c -o "spec.o" "spec.cpp" spec.cpp:272: error: prototype for `bool dwarf::spec::table_def<0u>::attr_d escribes_location(int) const' does not match any in class `dwarf::spec::tab le_def<0u>' spec.hpp:278: error: candidate is: bool dwarf::spec::table_defThe solution is to eliminate the template parameter.
::at tr_describes_location(int) const [with unsigned int spec_id = 0u] make: *** [spec.o] Error 1
template<>; }
It's not really clear why the latter is a valid syntax for specialization while the former isn't. However, a useful rule of thumb would seem to be that you should only list template arguments up-front (after “template”) if your definition depends on them. It doesn't matter if the originating class template uses more arguments. By contrast, the argument list attached to the classname is what nails down the particular template instance you're specializing for---this argument list should correspond directly to that of the template class definition.
[/devel] permanent link contact. # assuming you quit using a Quit-Verify menu... AddToMenu Quit-Verify "Quit" SaveQuitSession
[/devel] permanent link contact
On my Lab machine, the X login system doesn't clean up stray child processes that your X session may have left behind. (I've a feeling the Debian xinit scripts do this, but I'm not sure.) This was bothering me, because I start some background jobs in my .xsession which I want to die naturally when the session ends. So I put the following towards the end of my .xsession.
echo -n "End of .xsession: detected living child pids: " 1>&2 ps --no-header f -o pid --ppid $$ | \ while read pid; do kill ; done 2>/dev/null
Unfortunately, I found that those pesky children were still alive. (Can you tell what's wrong? Yes, that's right.) Both the ps process and the while subshell are among the children which are being killed. So one way or another, the pipeline gets broken before the loop has managed to kill the children I actually wanted to kill. A version which doesn't suffer this problem is as follows.
child_pids=$( ps --no-header f -o pid --ppid $$ ) for pid in ; do kill 2>/dev/null; done
It's another instance of the familiar Heisenbergian nature of inspecting process trees from the shell: doing many basic things from the shell entails creating processes, so inspecting the shell's own process tree is likely to yield perturbed results. Usually it's just an unwanted entry in ps (as with the old ps | grep foo gotcha) but the above shows it sometimes causes subtler problems.
[/devel] permanent link contact
I just stumbled across this video of a talk by David Beazley about the implementation of Python and, in particular, threading. In a nutshell, threading in Python is implemented as a complete minimal-effort hack on top of an interpreter that is essentially single-threaded by design. Static state is again the culprit---there's a big lock, called the Global Interpreter Lock, much like Linux used to have the Big Kernel Lock. But, rather than just protecting some carefully-selected critical regions, it protects all Python computation!
So, alarmingly, the performance of Python threading is absolutely disastrous. It's ironic that Google are heavy users of Python, given that they work with some of the largest datasets on the planet and generally have to know a thing or two about optimisation and concurrency. Of course they don't use Python for their core systems, and are sponsoring an improvement effort called Unladen Swallow.
I have some research ideas that predicated heavily on the position that language implementors often don't do a great job, particularly in the case of dynamic languages. So if we have to rewrite a bunch of dynamic language implementations, that's not really a terrible thing. I'm glad to have yet more evidence of this.
[/devel] permanent link contact
I had a weird problem with my X login scripts recently on my Lab machine---I noticed that for X sessions, the LD_LIBRARY_PATH environment variable wasn't being set, even though every other variable set from my ˜/.profile was still appearing correctly. After I bit of digging, I discovered why, but that only opened up an extra can of mystery.
The basic problem was that ssh-agent is a setuid program. so at the start of loading, the Linux loader removes all dynamic linker options (including LD_PRELOAD and LD_LIBRARY_PATH) from the environment to avoid running user code with elevated privileges. (It would make more sense just to ignore them, but still to propagate them to children... but anyway.) I was still a bit puzzled though, because I wasn't knowingly running my session as a child of ssh-agent---my login scripts do start one up if it's not already running, but it's supposed to run as a sibling of my main X session script, rather than using the ssh-agent <command> mechanism to start a child session. And ps agreed with me---my session wasn't descended from an ssh-agent process... but I did have two running, where I thought my scripts went to pains to ensure there was only one.
PID TTY STAT TIME COMMAND 19233 ? Ss 0:00 /bin/bash -l /home/srk31/.xsession 19573 ? S 0:00 \_ ssh-agent 19589 ? S 0:00 \_ fvwm 19593 ? Ss 0:00 \_ <... more X clients> 19433 ? Ssl 0:00 /bin/dbus-daemon --fork --print-pid 4 --print-address 19432 ? S 0:00 /usr/bin/dbus-launch --exit-with-session /home/srk31/
The explanations for this were somewhat convoluted. Firstly, the Fedora xinit scripts (FC7) do this (in /etc/X11/xinit/xinitrc-common, sourced from /etc/X11/xinit/Xsession):
# Prefix launch of session with ssh-agent if available and not already running. SSH_AGENT= if [ -x /usr/bin/ssh-agent -a -z "" ]; then if [ "x" != "x" ]; then SSH_AGENT="/usr/bin/ssh-agent /bin/env TMPDIR=" else SSH_AGENT="/usr/bin/ssh-agent" fi fi
...and later (in /etc/X11/xinit/Xsession)...
# otherwise, take default action if [ -x "/.xsession" ]; then exec -l -c " /.xsession" elif [ -x "/.Xclients" ]; then exec -l -c " /.Xclients" elif [ -x /etc/X11/xinit/Xclients ]; then exec -l -c " /etc/X11/xinit/Xclients" else # should never get here; failsafe fallback exec -l -c "xsm" fi
In other words, they test whether an ssh-agent is running, and arrange to start one if not. But in between testing and starting one, they run a shell---which naturally starts my login scripts. These check for ssh-agent themselves and, finding none, start one. Then later, the Fedora scripts start another one. It's a classic “unrepeatable read” race condition, but without any concurrency---just interleaving of foreign code (my login scripts).
Next, why wasn't my session showing up as a child of one of the ssh-agent processes? ps's output was doubly confusing because the top of my process tree was a bash -l .xsession process, when that's the last to be launched by the sequence initiated in the Fedora scripts! Well, strace revealed that my processes were using the clone() system call to spawn new processes (which is subtly different from fork(), in that it allows shared address spaces and hence multithreaded programming). As we know, when a process clones itself in order to start a new process, one of the resulting pair replaces itself with the new process image, while the other continues on its merry way. In the case of both ssh-agent and dbus-launch, the parent process was the one which replaced itself, leaving the child to continue the work of SSH agentery or DBUS launchery or whatever. This is really confusing because it contradicts the usual expectations about causal ordering from parent to child processes---but it's perfectly allowed, and has always been possible in Unix.
What was the fix? Sadly, there isn't a good one---I don't have the permission to edit the Fedora scripts on my Lab machine, and there's no configurable flexibility for disabling the ssh-agent launching or fixing the racey logic. So I added a hack to my .xsession shell script which detects the case where SSH_AGENT_PID is already set to a child of the shell process (since the ssh-agent my scripts created is a sibling) and if so, kills that process and re-sets SSH_AGENT_PID to the one I created earlier (which, handily, I keep stored in ${HOME}/.ssh/agent-$(uname -n)). As usual, completely horrible.
[/devel] permanent link contact
I'm doing some C++ coding at the moment. It's a language well-known for “gotchas”, so although it'd be presumptuous for me to assume they'd get you as well, dear reader, I'm going to document some of the things that've caught me out.
namespace dwarf { namespace encap { typedef Dwarf_Loc expr_instr; bool operator==(const expr_instr& e1, const expr_instr& e2); bool operator!=(const expr_instr& e1, const expr_instr& e2);; // test return hipc == e.hipc && lopc == e.lopc && //e1 == e2; // test m_expr == e.m_expr; // error! } bool operator!=(const expr& e) const { return !(*this == e); } } loc_expr; } }
Here we have some code from my C++ binding of libdwarf. I'm trying to use std::vector's builtin == operator to define equality on my struct expr, which is essentially a wrapper for vectors of Dwarf_Loc objects, where Dwarf_Loc is a structure defined by libdwarf. Here's what g++ makes of the above code:
/local/scratch/srk31/opt/bin/../lib/gcc/i686-pc-linux-gnu/4.3.3/../../../../incl ude/c++/4.3.3/bits/stl_algobase.h: In static member function ?static bool std::_ _equal<_BoolType>::equal(_II1, _II1, _II2) [with _II1 = const Dwarf_Loc*, _II2 = const Dwarf_Loc*, bool _BoolType = false]?: /local/scratch/srk31/opt/bin/../lib/gcc/i686-pc-linux-gnu/4.3.3/../../../../incl ude/c++/4.3.3/bits/stl_algobase.h:824: instantiated from ?bool std::__equal_au x(_II1, _II1, _II2) [with _II1 = const Dwarf_Loc*, _II2 = const Dwarf_Loc*]? /local/scratch/srk31/opt/bin/../lib/gcc/i686-pc-linux-gnu/4.3.3/../../../../incl ude/c++/4.3.3/bits/stl_algobase.h:956: instantiated from ?bool std::equal(_II1 , _II1, _II2) [with _II1 = __gnu_cxx::__normal_iterator
> >, _II2 = __gnu_cxx::__normal_itera tor > >]? /local/scratch/srk31/opt/bin/../lib/gcc/i686-pc-linux-gnu/4.3.3/../../../../incl ude/c++/4.3.3/bits/stl_vector.h:1111: instantiated from ?bool std::operator==( const std::vector<_Tp, _Alloc>&, const std::vector<_Tp, _Alloc>&) [with _Tp = Dw arf_Loc, _Alloc = std::allocator ]? dwarfpp.hpp:341: instantiated from here /local/scratch/srk31/opt/bin/../lib/gcc/i686-pc-linux-gnu/4.3.3/../../../../incl ude/c++/4.3.3/bits/stl_algobase.h:795: error: no match for ?operator==? in ?* __ first1 == * __first2? make: *** [dwarfpp.o] Error 1
Clearly, my definition for operator== isn't being found. But if I uncomment the blamed line and replace it with some dummy code (commented above) which invokes the operator for two dummy objects, rather than vectors, it works fine. Why can I compare two Dwarf_Locs but not two vectors thereof, when vector defines a perfectly good operator== that should just invoke mine?
The answer is that vector's operator== can't see my operator== definition, because of namespaces. According to Stroustrup (C++PL, third edition, section 11.2.4):
Consider a binary operator @. If x is of type X and y is of type Y, x@y is resolved like this:
So the code in std::vector clearly can't see my definitions in dwarf::encap::. However, the reason that this isn't such a common problem is that I'm defining operators on a type, namely Dwarf_Loc, that was defined not by me but in the pre-existing C library that I'm wrapping. I lazily dumped all of libdwarf's definitions into the global namespace, so the quick fix is to define my operator in the global namespace too.
namespace dwarf { namespace encap { typedef Dwarf_Loc expr_instr; } } bool operator==(const dwarf::encap::expr_instr& e1, const dwarf::encap::expr_instr& e2); bool operator!=(const dwarf::encap::expr_instr& e1, const dwarf::encap::expr_instr& e2); namespace dwarf { namespace encap { //typedef Dwarf_Loc expr_instr;; return hipc == e.hipc && lopc == e.lopc && //e1 == e2; m_expr == e.m_expr; // okay } bool operator!=(const expr& e) const { return !(*this == e); } } loc_expr; } }
Note that if I'd done the right thing and wrapped libdwarf's definitions into some non-global namespace, say dwarf::lib, I'd still need to do something similar, because my operator definition won't be found if I put it in a different namespace like dwarf::encap, even though that's the namespace containing the code which actually needs the operator to be defined.
Well, it certainly got me... now, on with coding.
[/devel] permanent link contact
I'm sure Ruby is a nice language, but I get slightly annoyed by two things whenever I try to install a Ruby program. One is that it has its own build system, as a replacement for Make et al---there are things called Rakefiles in the source distributions. The other is that it also has its own configuration and deployment system, based on the setup.rb script. These things annoy me because they're yet more tools that I need to learn, and for no good reason. Python is guilty of the same sins too. A new language shouldn't entail a whole new build system. (I won't go into why, but hopefully you don't need me to. I would also complain that there are too many languages, but I'll save that too.)
What really annoys me about Ruby is that setup.rb is broken, because it doesn't deal with prefixes properly. If I do ruby setup.rb config --prefix=${HOME}/opt, it still tries to install most of the program under /usr. So I tried giving the --prefix option to ruby setup.rb install too, but that doesn't do the right thing either. Instead it creates me a ${HOME}/opt/usr hierarchy and puts the stuff it was putting in /usr there.
I might as well come clean and admit that the only Ruby program I routinely install is iplayer-dl. Anyway, my next attempt: configure everything using paths relative to ./, then supply the overall prefix at install time. That doesn't work either---setup.rb interprets the ./ passed with --prefix, so you get install destinations relative to your configure directory. But only for files affected by --prefix, which isn't all of them.
Next attempt: configure everything relative to the root directory, then supply the prefix at install time. This does work, but you wouldn't guess from the output of ruby setup.rb install.
$ rubyver=$( ruby --version | sed 's/ruby \([0-9]*\.[0-9]*\)\..*/\1/' ) # horrible $ rubyarch=$( uname -i )-$( uname -s | tr '[:upper:]' '[:lower:]' ) # horrible $ ruby ./setup.rb config --prefix='/' --sysconfdir=/etc \ --libruby=/lib/ruby --librubyver=/lib/ruby/ --librubyverarch=/lib/ruby// \ --siteruby=/lib/ruby/site_ruby --siterubyver=/lib/ruby/site_ruby/ --siterubyverarch=/lib/ruby/site_ruby// $ ruby $ ruby ./setup.rb install --prefix=${HOME}/opt rm -f InstalledFiles ---> bin mkdir -p /home/srk31/opt//bin install iplayer-dl //bin//iplayer-dl install iplayer-dl-gui //bin//iplayer-dl-gui <--- bin ---> lib mkdir -p /home/srk31/opt/lib/ruby/site_ruby/1.8 install iplayer.rb /lib/ruby/site_ruby/1.8/ ---> lib/iplayer mkdir -p /home/srk31/opt/lib/ruby/site_ruby/1.8/iplayer install downloader.rb /lib/ruby/site_ruby/1.8/iplayer install subtitles.rb /lib/ruby/site_ruby/1.8/iplayer install metadata.rb /lib/ruby/site_ruby/1.8/iplayer install preferences.rb /lib/ruby/site_ruby/1.8/iplayer install browser.rb /lib/ruby/site_ruby/1.8/iplayer install version.rb /lib/ruby/site_ruby/1.8/iplayer install errors.rb /lib/ruby/site_ruby/1.8/iplayer ---> lib/iplayer/gui mkdir -p /home/srk31/opt/lib/ruby/site_ruby/1.8/iplayer/gui install main_frame.rb /lib/ruby/site_ruby/1.8/iplayer/gui install app.rb /lib/ruby/site_ruby/1.8/iplayer/gui <--- lib/iplayer/gui <--- lib/iplayer <--- libSo, handily it's told me that it installed a bunch of stuff in /lib/ruby, which is exactly what I didn't want it to do. But, since I ran it without elevated permissions, I know that it can't have succeeded in doing that---yet there were suspiciously no error messages. Lo! Despite what it printed out, it has actually put the lib files in ${HOME}/opt/lib/ruby just as I wanted. Now, why was that so difficult?
To make matters worse, you of course have to set your Ruby path to get the deployed program to work, and that is also horrifying:
$ export RUBYLIB=${HOME}/opt/lib/ruby:${HOME}/opt/lib/ruby/site_ruby:${HOME}/opt/lib/ruby/site_ruby/1.8:---disgusting, especially embedding the 1.8 version number in the path which will be seen (and interpreted) by any version of Ruby at all. It's following the pattern established Python, of course, and since Python has some reasonably sane people behind it I'm tempted to suspect that this ludicrous scheme has been selected for a reason---but even if this suspicion is correct, it'll have to be a very good one, and I somehow doubt that.
[/devel]
I've been looking for an X11 session manager that actually works recently (since sadly xsm doesn't fit that bill) and was experimenting with KDE's session manager. It's peculiarly underdocumented but seemed like it should have all the functionality I needed, and should also be reasonably well-used and well-tested. So I was a bit disappointed when my basic set-up attempt at integrating it with fvwm appeared not to work. I was simply replacing the fvwm command in my .xsession with the following:
ksmserver -r -w fvwm
which should launch fvwm rather than kwin. Then in my fvwm configuration, to end the session properly when I quit the window manager, I tried the following.
AddToFunc SessionInitFunction + I Exec echo hello from SessionInitFunction AddToFunc SessionExitFunction # kill ksmserver when we exit + I Exec dcop ksmserver ksmserver logout 0 2 2 ## from #First parameter: confirm #Obey the user?s confirmation setting: -1 #Don?t confirm, shutdown without asking: 0 #Always confirm, ask even if the user turned it off: 1 #Second parameter: type #Select previous action or the default if it?s the first time: -1 #Only log out: 0 #Log out and reboot the machine: 1 #Log out and halt the machine: 2 #Third parameter: mode
(Thanks to Andrej Kazakov for the summary of logout's invocation that I pasted above, in turn extracted from the KDE source code.)
Of course, it didn't work, so I put my developer hat on and had a look. Attaching gdb revealed that the session manager was entering a (non-tight) endless loop when I requested the logout---setting a timer which fired after one second, disabled itself and then recursively re-started the process. The problem was that the session manager has an internal state machine, and in my case it was stuck in state AutoStart0, whereas it was expected to end up in Idle after a while---the only state from which it can initiate a shutdown.
To get out of AutoStart0, and subsequent start-up states, you have to manually call a bunch of other DCOP methods with names like autoStart0Done, kcmPhase1Done and so on. This is among what startkde does for KDE users, after performing various KDE-specific configuration updates. (These updates are exactly what a non-KDE user doesn't want to happen, at least in my case---since one major reason I don't use KDE is that I like to stick with the simple X11-provided ways of controlling backgrounds, cursors, input devices and so on.) We can manually invoke the DCOP methods to signal that it's time for the next state.
We successfully avoid most of the KDE interference in this way, because the relevant other processes (like kcminit) haven't been launched. However, we do get some, because the klauncher process does exist -- it's started when running any KDE app if not already running. In particular, ksmserver's signals to klauncher have the unwanted consequence of starting up a bunch of “autostart” applications, like the KDE desktop background and panel, that have shortcuts in ~/.kde/Autostart and /share/autostart/. To avoid this, we tell the launcher to bump our start-up “phase”, which is just an integer, to a high value---since autostart apps are marked with a “phase” attribute, and are only started when moving through that phase. ksmserver only covers as far as phase 2, so we can set the phase to 3 and they won't be started up. So, here's my final fvwm config for use with ksmserver.
[Update, 2009-03-02: not so fast! What I had here earlier didn't quite work, because fvwm doesn't necessarily execute each part of a compound function in sequence. So instead, it needs to all be rolled into one command. What's more, I had to hack in an arbitrary sleep because, depending on how long it takes to start up all the saved clients, the kcmPhase2Done call may come too soon (state machine not yet progressed into FinishingStartup, I think) and be ignored (causing ksmserver to get stuck in the latter state). Now, what follows does seem to work.] # signal ksmserver when we exit AddToFunc SessionExitFunction + I Exec dcop ksmserver ksmserver saveCurrentSessionAs "saved at previous logout"; \ dcop ksmserver ksmserver logout 0 0 3
I still haven't actually made the session management functionality work, which I think is going to take some more commands along “save” and “restore” lines. [Update, 2009-03-02: turns out to need just the one “save” command at exit, as shown above -- restoring happens by default, using the magic session name shown.] My ultimate goal is the ability to start multiple ksmserver processes, so that I can independently save and restore separate groups of clients within a single X login session. Fingers crossed... if it's nontrivial I'll write a follow-up post. There's also the joy of KDE 4 to think about later, which has exchanged DCOP for D-BUS and may well alter the undocumented behaviour I'm relying on.
The Important Science to take away from all this is I suppose that interface protocol specifications and timing specifications are useful! Not just for checking, which seems a long way off here, but just for understanding. It'd also be useful to have more convenient support for interposing on DCOP communication, by having client-specific message routing (or name-bindings) so that the “phase” hack could be handled a bit more elegantly by cutting off the connection to klauncher.
[/devel] permanent link contact
I just spent an age tracking down a bug in a very simple tool I'm writing using the GNU BFD. It turns out that when opening a file for reading with BFD, various API calls are not valid until bfd_check_format_matches has been called and has returned successfully. This doesn't appear to be documented in the current texinfo manual. In fact, even the need to call bfd_init is not very clearly documented---but at least that one is fairly predictable. Most libraries, particularly those which maintain a lot of state behind the scenes, have an init function. Additional initialization steps, like the one I ran afoul of, are not at all guessable and should really be clearly signposted in the documentation. It was only by careful examination of what objcopy does that I could track down the bug.
It's well-known in the research world that interfaces come with protocol constraints, and it'd be nice to check client code against these just as we already do with function signatures. Initialization constraints are by far the most common example of protocol constraint. But rather than just checking satisfaction of these constraints, why should we even have to write the code at all? Why can't our toolchain insert initialization calls in the right places automatically? In fact at least one research linkage tool (Knit) can already do this.
How far can we generalise this constraint-solving? Usually protocol specifications use a finite-state model of component state, which are clearly good for a wide range of protocols but not all (consider a stack). Of course, we want our checking/solving to be decidable, and more complex models quickly lose this property, although I'm not sure whether a pushdown automaton model would necessarily be undecidable. More practically, Knit essentially supports a single bit of state (initialized or not) for each component (or actually a tri-state, because it supports finalizers too). If we wanted to generalise this even to a general finite-state model, we'd get ambiguity: say we had to call function A one or more times before calling function B, how many calls would we insert? Maybe “the smallest string” would be a sensible policy, but that would be ambiguous in some cases, and it's not clear it's always a good choice anyway. In protocol adaptation, there is invariably some programmer-provided “specification” to answer these questions, usually by constraining the generated automaton.
The BFD example is unusual in another way, in that it requires a successful call to the init function, not just any call. So our protocol checker/solver has to understand return values (and of course arguments) as well as function names. It's about time I re-examined the research literature on protocol adaptation and worked out how much of it has actually been turned into practical tools that address these issues. In due course I'm hoping to build a practical subset (or superset) of protocol adaptation functionality into Cake. One thing at a time though... first I must master that pesky BFD.
[/devel] permanent link contact
It's about time I began sharing the hard-learnt arcane development knowledge I've managed to pick up. One of the most annoying “features” I've had to reverse-engineer is in the behaviour of Linux's dynamic linker, ld-linux. I have a lot of directories in my LD_LIBRARY_PATH environment variable.
srk31@font:~/scratch/kde$ echo /home/srk31/scratch/opt/lib:/home/srk31/scratch/kde/lib:/usr/lib/mysql:/usr/lib/opensync/:/usr/lib/o pensync/formats/:/usr/lib/opensync/plugins/:/usr/lib/qt-3.3/lib:/usr/lib/wine/:/home/srk31/opt/lib:/ lib:/usr/lib
They all get searched as you'd expect. Each directory is expanded to include searches for various architecture-specific variant subdirectories like tls, sse2, nosegneg etc.
srk31@font:~/scratch/kde$ LD_DEBUG=libs ldd bin/konsole 2>&1 | head 5666: find library=libtinfo.so.5 [0]; searching 5666: search path=/home/srk31/scratch/opt/lib/tls/i686/sse2/nosegneg:/home/srk31/scratch/ opt/lib/tls/i686/sse2:/home/srk31/scratch/opt/lib/tls/i686/nosegneg:/home/srk31/scratch/opt/lib/tls/ i686:/home/srk31/scratch/opt/lib/tls/sse2/nosegneg:/home/srk31/scratch/opt/lib/tls/sse2:/home/srk31/ scratch/opt/lib/tls/nosegneg:/home/srk31/scratch/opt/lib/tls:/home/srk31/scratch/opt/lib/i686/sse2/n
(snipped some -- view source for more)
osegneg:/home/srk31/opt/lib/i686/sse2:/home/srk31/opt/lib/i686/nosegneg:/home/srk31/opt/lib/i686:/ho me/srk31/opt/lib/sse2/nosegneg:/home/srk31/opt/lib/sse2:/home/srk31/opt/lib/nosegneg:/home/srk31/opt /lib (LD_LIBRARY_PATH) 5666: trying file=/home/srk31/scratch/opt/lib/tls/i686/sse2/nosegneg/libtinfo.so.5 5666: trying file=/home/srk31/scratch/opt/lib/tls/i686/sse2/libtinfo.so.5 5666: trying file=/home/srk31/scratch/opt/lib/tls/i686/nosegneg/libtinfo.so.5
Notice that in my LD_LIBRARY_PATH, /usr/lib and lib are right at the end. Once I tried tweaking the ordering so that some paths came after these -- they were “backup” libraries I'd compiled myself in case the machine I was using didn't have them, but I wanted to pick up any local ones in preference. Unfortunately, this doesn't work. ld-linux will ignore all directories after the first directory it encounters that is part of the “system library path”.
srk31@font:~/scratch/kde$ LD_LIBRARY_PATH=/usr/lib:${LD_LIBRARY_PATH} LD_DEBUG=libs ldd bin/konsole 2>&1 | head 5687: find library=libtinfo.so.5 [0]; searching 5687: search path=/usr/lib/tls/i686/sse2/nosegneg:/usr/lib/tls/i686/sse2:/usr/lib/tls/i68 6/nosegneg:/usr/lib/tls/i686:/usr/lib/tls/sse2/nosegneg:/usr/lib/tls/sse2:/usr/lib/tls/nosegneg:/usr /lib/tls:/usr/lib/i686/sse2/nosegneg:/usr/lib/i686/sse2:/usr/lib/i686/nosegneg:/usr/lib/i686:/usr/li b/sse2/nosegneg:/usr/lib/sse2:/usr/lib/nosegneg:/usr/lib (system search path) 5687: trying file=/usr/lib/tls/i686/sse2/nosegneg/libtinfo.so.5 5687: trying file=/usr/lib/tls/i686/sse2/libtinfo.so.5 5687: trying file=/usr/lib/tls/i686/nosegneg/libtinfo.so.5 5687: trying file=/usr/lib/tls/i686/libtinfo.so.5 5687: trying file=/usr/lib/tls/sse2/nosegneg/libtinfo.so.5 5687: trying file=/usr/lib/tls/sse2/libtinfo.so.5 5687: trying file=/usr/lib/tls/nosegneg/libtinfo.so.5 5687: trying file=/usr/lib/tls/libtinfo.so.5
I have no idea why it does this, but would guess it's intended behaviour for some reason. It's annoying though.
Oh, and another gotcha relating to LD_LIBRARY_PATH is that if you're using gdb, it seems you must set solib-search-path to match your LD_LIBRARY_PATH, because gdb seems to ignore the latter (again, probably for some reason or other). And if you ever use a frontend to gdb, like DDD, that probably has its own setting too. There is so much fun to be had with these things.
[/devel] permanent link contact | https://www.cs.kent.ac.uk/people/staff/srk21/blog/devel/ | CC-MAIN-2019-51 | refinedweb | 6,280 | 55.84 |
I recently decided to publish an NPM module. I wrote it in TypeScript and went with Rollup for bundling. It was my first time publishing a module and my first experience with Rollup, so I’d like to write a tutorial on how to do it, both as a reference for myself and for anyone who may find this useful. Let’s get started!
Why TypeScript and Rollup
I went with TypeScript for several reasons. It’s what I use at work, so I’m not only familiar with it, but it’s always good to hone my skills, especially since I’m not necessarily a TypeScript expert (yet). I’m also a fan of types for a number of reasons, and compile-time errors are invaluable. I also believe all JS libraries should be authored in TypeScript.
As for Rollup, I mostly went with it because I had never used it and have heard good things about it. Not only that, but I know that a number of open-source projects use it over Webpack. I also read this great post about the differences between the two and why Rollup is better for building libraries.
Prerequisites
I’m going to be using
yarn, but you can use
npm if you wish!
First, let’s create our
package.json inside the project directory. Fill out everything as you wish, or just hit
Enter at every step if you don’t care yet. You can always edit these later.
$ yarn init
First, let’s install TypeScript and Rollup inside the project directory, as well as a plugin to allow Rollup to compile TypeScript as part of its bundling process.
$ yarn --dev add typescript rollup rollup-plugin-typescript2
Note: The original
rollup-plugin-typescript appears to be unmaintained, which is why we’re using this one instead.
At this point, your
package.json should look something like this:
{
"name": "some-project",
"version": "1.0.0",
"main": "index.js",
"author": "John Doe <jdoe@example.com>",
"license": "MIT",
"devDependencies": {
"rollup": "^0.62.0",
"rollup-plugin-typescript2": "^0.15.1",
"typescript": "^2.9.2"
}
}
Let’s add a few extra lines to the file and replace the default for
main:
{
"name": "some-project",
"version": "1.0.0",
"main": "dist/index.js",
"module": "dist/index.es.js",
"files": ["dist"],
"types": "dist/index.d.ts",
"scripts": {
"build": "rollup -c",
"watch": "rollup -cw"
},
"author": "John Doe <jdoe@example.com>",
"license": "MIT",
"devDependencies": {
"rollup": "^0.62.0",
"rollup-plugin-typescript2": "^0.15.1",
"typescript": "^2.9.2"
}
}
Here’s what’s going on:
mainand
modulepoint to the bundled JavaScript so that the library consumer may import the module.
mainis for the CommonJS module, and
moduleis for the ES module. You don’t need to understand the details of that for now, though!
fileslets
npm/
yarnknow what to publish, or rather what gets installed inside a user’s
node_moduleswhen they install your module. For now, let’s just do
dist, which will contain our bundled JS.
typespoints to our TypeScript declaration file. This will get compiled automatically for us (more on that below).
scriptsjust has some handy Rollup scripts, which you can use during development.
yarn run buildwill bundle the module once, while
yarn run watchwill build it every time a file changes.
Now we’re ready for some configuration!
TypeScript configuration
In order to configure TypeScript, we need to create a
tsconfig.json file. There are more options than we can go over, but the following ones will be good enough for now. I encourage you to dive deeper into the options if you find yourself unsatisfied with how something is working!
Copy the following into
tsconfig.json in the root directory of your project.
{
"compilerOptions": {
"declaration": true,
"declarationDir": "./dist",
"module": "es6",
"noImplicitAny": true,
"outDir": "./dist",
"target": "es5"
},
"include": [
"src/**/*"
],
"exclude": ["node_modules"]
}
What’s going on:
"declaration": trueis there to enable automatic generating of TypeScript’s declaration files. These are helpful for TypeScript users who are using your module, since they’ll have access to all the types of your module’s methods, variables, etc.
declarationDirand
outDirspecify where the compiled code will go. I’m using
./dist, but you may choose another name such as
./lib. If you choose a different directory name, make sure to use that name in your
package.jsonas well!
"noImplicitAny": trueforces us to be a bit stricter with types. By default, TypeScript allows you to get away with not assigning types to variables whose types cannot be inferred. This option makes it so that if we want something to use the type
any, it must be done explicitly.
targetallows us to specify which version of JavaScript to compile our TypeScript to. In this case, I’m choosing ES5.
includeallows us to specify where TypeScript should look for
.ts,
.d.ts, and
.tsxfiles to compile.
excludeallows us to specify directories for TypeScript to ignore when it comes to compiling.
Rollup configuration
Next, we’ll configure Rollup.
In the root directory of your project, create a file called
rollup.config.js. Next, copy this into there:
import typescript from 'rollup-plugin-typescript2'
import pkg from './package.json'
export default {
input: 'src/index.ts',
output: [
{
file: pkg.main,
format: 'cjs',
},
{
file: pkg.module,
format: 'es',
},
],
external: [
...Object.keys(pkg.dependencies || {}),
...Object.keys(pkg.peerDependencies || {}),
],
plugins: [
typescript({
typescript: require('typescript'),
}),
],
}
The first thing to note is that we’re importing
package.json. This isn’t necessary, but it’s a handy way to make sure you aren’t duplicating certain information, such as the filename of your bundle. Here’s a breakdown of what’s going on:
inputtells Rollup where to look for code to bundle. This is similar to Webpack’s
entry.
outputis where our bundle gets stored. As stated earlier, we’re going to bundle both CommonJS (
cjs) and ES (
es) modules. Rollup’s documentation has a pretty good explanation of the differences if you’re interested.
externalis what we use to tell Rollup what modules to exclude from our bundle. Since
pkg.dependencieswill get installed by the module consumer’s
yarnor
npm, and since
pkg.peerDependenciesare expected to be installed by the consumer, we can safely exclude those from the bundle.
- The
pluginssection is a bit weird. What we’re doing there is making
rollup-plugin-typescript2use the locally-installed TypeScript. By default, it uses a version that likely isn’t up-to-date. There are a bunch of other plugins we could install, but this is fine for now!
Publishing to NPM
In order to publish the module, we first need to log into NPM. If you don’t have an account, go create one now. You’ll only need to do this once on your machine. For some reason,
yarn login didn’t work for me, so I’m going to use
npm login for this:
$ npm login
Username: yourusername
Logged in as yourusername on.
Next, let’s create a tiny module to publish. Create a
src directory, and inside there, an
index.ts file:
// src/index.ts
export const greet = () => console.log('Hello, world!')
After that, run the
build command to compile the TypeScript:
$ yarn run build
yarn run v1.3.2
$ rollup -c
src/index.ts → dist/index.js, dist/index.es.js...
created dist/index.js, dist/index.es.js in 522ms
✨ Done in 0.91s.
You’ll notice a
dist folder was created with three files in it. Feel free to check those out!
Finally, we can publish the module to NPM:
$ yarn publish
yarn publish v1.3.2
[1/4] Bumping version...
info Current version: 0.0.1
question New version:
[2/4] Logging in...
[3/4] Publishing...
success Published.
[4/4] Revoking token...
info Not revoking login token, specified via config file.
✨ Done in 1.85s.
And that’s it! You’ve successfully published a module to NPM using TypeScript and Rollup.
To verify that everything looks good, create another directory somewhere else on your computer and run
yarn init, then
yarn add your-package-name. If you navigate to
node_modules/your-package-name, you should see the
dist folder with all the compiled files in there! You can then import your module like so:
import { greet } from 'your-package-name'
Developing locally
As you can imagine, it would be pretty annoying and hacky to publish your package every time you wanted to test it out. While writing automated tests helps a lot in this regard, sometimes you’ll need to actually use your module to make sure that it works properly before publishing it.
For this, we can use
yarn link (or
npm link, of course).
First, navigate to your module’s project directory and run the following:
$ yarn link
Next, navigate to the project where you’d like to consume this module. Make sure that the module is not installed via
yarn or
npm, then run:
$ yarn link your-package-name
This will create a symbolic link to your package folder inside your project’s
node_modules directory. Essentially, you’ll be able to use the local version of your package the same way you’d be able to use it if you had it published and downloaded/installed via
yarn add or
npm install!
Thanks for reading
If you’ve made it this far, congratulations on publishing something to NPM! I hope you enjoyed this tutorial. If I made any mistakes or if anything needs clarification, please don’t hesitate to reach out. I’d like to contribute more to NPM going forward, so I’ll try to keep this tutorial as up-to-date as I can. | https://hackernoon.com/building-and-publishing-a-module-with-typescript-and-rollup-js-faa778c85396 | CC-MAIN-2019-35 | refinedweb | 1,593 | 67.65 |
This tutorial was extracted from Erich Styger blog with his agreement.
Question: What makes 8 times ‘beep’, but I cannot hear it?
Answer: My ultrasonic range finder
FRDM-KL25Z with HC-SR04
What I have added to my FRDM-KL25ZFRDM.
HC-SR04 Front Side
The backside features all the electronics to which simply usage of the sensor:
HC-SR04 Back Side
With simple I mean, it only needs 4 pins:
- Vcc (+5V DC supply)
- Trig (TTL input, to trigger a measurement)
- Echo (TTL output, pulse proportional to distance)
- GND (ground):
HC-SR04 Timing Diagram
-:
HC-SR04 Timing
After the 10 us Trigger signal, the sensor sends the burst during ’1′ and ’2′ .
For decimal system challenged engineers: instead of a divider of 58, use a divider of 148 to get the result in inch instead of centimeter.
Hardware Connection
I’m using a breadboard for easy wiring and connection.
Breadboard Wiring with Freedom Board, Sensor, LCD and Logic analyzer
To visualize the measurement, I’m using the 2×16 Character display I have used in my earlier post. Of course a LCD is optional. I used the same wiring as before:
Signals with Labels
=========================================================================:
Voltage Divider with two resistors
Voltage Divider Detail:
BitIO_LDD Component
I configure it as Output pin on PTA12:
Trigger Properties
Additionally I add the Wait component to the project:
Wait Component:
TimerUnit_LDD added:
Adding Timer Unit Channel
For this I’m selecting the TPM0_CNT as counter and configure the channel for ‘capture’:
You will understand later on why I have selected this particular counter.
Using TPM0_CNT and Capture Mode
As I have connected the Echo signal on PTD4, I need to use that pin as ‘Capture input pin’:
PTD4 as input capture pin
As hinted by the pin name (PTD4/LLWU_P14/SPI1_PCS0/UART2_RX/TPM0_CH4), this pin is available on TPM0_CH4, so I need to configure this as capture device:
selected capture device:
Interrupt Settings
That’s not enough: I need to enable interrupts for the counter too:
Enabled Interrupts for Counter:
Configuring the counter frequency
The first thing to do is to disable ‘Auto select timing’:
Disabling Auto Select timing):
Selected clock frequency
Counter Overrun
There one thing to consider: when will the counter overflow? I keep in mind that with the speed of sound, around 4 meters distance means 400*58us makes 23.5ms Echo signal pulse. So I need to make sure that for this distance, my counter does *not* overflow. I can check this in the ‘Overrun period’ settings:
Overrun period
Deselecting ‘auto select timing’ again will show the overrun period time:
Overrun period’):
Enabled TimerUnit_LDD Methods:
State Diagram
-):
Timing and State Diagram
With this in mind, the implementation is pretty straight forward. First, an enumeration for the state machine states:
1 typedef enum {
2 ECHO_IDLE, /* device not used */
3 ECHO_TRIGGERED, /* started trigger pulse */
4 ECHO_MEASURE, /* measuring echo pulse */
5 ECHO_OVERFLOW, /* measurement took too long */
6 ECHO_FINISHED /* measurement finished */
7 } US_EchoState;
Next the data structure to keep all my data:
1 typedef struct {
2 LDD_TDeviceData *trigDevice; /* device handle for the Trigger pin */
3 LDD_TDeviceData *echoDevice; /* input capture device handle (echo pin) */
4 volatile US_EchoState state; /* state */
5 TU1_TValueType capture; /* input capture value */
6 } US_DeviceType;
7
8 static US_DeviceType usDevice; /* device handle for the ultrasonic device */
And here is how it gets initialized:
1 void US_Init(void) {
2 usDevice.state = ECHO_IDLE;
3 usDevice.capture = 0;
4 usDevice.trigDevice = TRIG_Init(NULL);
5 usDevice.echoDevice = TU1_Init(&usDevice);
6 }:
01 /*
02 ** ===================================================================
03 ** Event : TU1_OnChannel0 (module Events)
04 **
05 ** Component : TU1 [TimerUnit_LDD]
06 ** Description :
07 ** Called if compare register match the counter registers or
08 ** capture register has a new content. OnChannel0 event and
09 ** Timer unit must be enabled. See and
10 ** methods. This event is available only if a
11 ** is enabled.
12 ** Parameters :
13 ** NAME - DESCRIPTION
14 ** * UserDataPtr - Pointer to the user or
15 ** RTOS specific data. The pointer passed as
16 ** the parameter of Init method.
17 ** Returns : Nothing
18 ** ===================================================================
19 */
20 void TU1_OnChannel0(LDD_TUserData *UserDataPtr)
21 {
22 US_EventEchoCapture(UserDataPtr);
23 }
24
25 /*
26 ** ===================================================================
27 ** Event : TU1_OnCounterRestart (module Events)
28 **
29 ** Component : TU1 [TimerUnit_LDD]
30 ** Description :
31 ** Called if counter overflow/underflow or counter is
32 ** reinitialized by modulo or compare register matching.
33 ** OnCounterRestart event and Timer unit must be enabled. See
34 ** and methods. This event is
35 ** available only if a is enabled.
36 ** Parameters :
37 ** NAME - DESCRIPTION
38 ** * UserDataPtr - Pointer to the user or
39 ** RTOS specific data. The pointer passed as
40 ** the parameter of Init method.
41 ** Returns : Nothing
42 ** ===================================================================
43 */
44 void TU1_OnCounterRestart(LDD_TUserData *UserDataPtr)
45 {
46 US_EventEchoOverflow(UserDataPtr);
47 }
In case of Overflow I simply set the state machine to the overflow state:
1 void US_EventEchoOverflow(LDD_TUserData *UserDataPtr) {
2 US_DeviceType *ptr = (US_DeviceType*)UserDataPtr;
3
4 ptr->state = ECHO_OVERFLOW;
5 }
While in the interrupt/event for raising or falling edge, I reset the counter value at raising edge, or read out the counter value at falling edge:
1 US_DeviceType *ptr = (US_DeviceType*)UserDataPtr;
2
3 if (ptr->state==ECHO_TRIGGERED) { /* 1st edge, this is the raising edge, start measurement */
4 TU1_ResetCounter(ptr->echoDevice);
5 ptr->state = ECHO_MEASURE;
6 } else if (ptr->state==ECHO_MEASURE) { /* 2nd edge, this is the falling edge: use measurement */
7 (void)TU1_GetCaptureValue(ptr->echoDevice, 0, &ptr->capture);
8 ptr->state = ECHO_FINISHED;
9 }:
01 uint16_t US_Measure_us(void) {
02 uint16_t us;
03
04 /* send 10us pulse on TRIG line. */
05 TRIG_SetVal(usDevice.trigDevice);
06 WAIT1_Waitus(10);
07 usDevice.state = ECHO_TRIGGERED;
08 TRIG_ClrVal(usDevice.trigDevice);
09 while(usDevice.state!=ECHO_FINISHED) {
10 /* measure echo pulse */
11 if (usDevice.state==ECHO_OVERFLOW) { /* measurement took too long? */
12 usDevice.state = ECHO_IDLE;
13 return 0; /* no echo, error case */
14 }
15 }
16 us = (usDevice.capture*1000UL)/(TU1_CNT_INP_FREQ_U_0/1000);
17 return us;
18 }:
01 static uint16_t calcAirspeed_dms(uint8_t temperatureCelsius) {
02 /* Return the airspeed depending on the temperature, in deci-meter per second */
03 unsigned int airspeed; /* decimeters per second */
04
05 airspeed = 3313 + (6 * temperatureCelsius); /* dry air, 0% humidity, see */
06 airspeed -= (airspeed/100)*15; /* factor in ~15% for a relative humidity of ~40% */
07 return airspeed;
08 }
09
10 uint16_t US_usToCentimeters(uint16_t microseconds, uint8_t temperatureCelsius) {
11 return (microseconds*100UL)/calcAirspeed_dms(temperatureCelsius)/2; /* 2 because of two way */
12 }:
01 static void Measure(void) {
02 uint16_t us, cm;
03 uint8_t buf[8];
04
05 us = US_Measure_us();
06 UTIL1_Num16uToStrFormatted(buf, sizeof(buf), us, ' ', 5);
07 LCD1_GotoXY(1,5);
08 LCD1_WriteString((char*)buf);
09
10 cm = US_usToCentimeters(us, 22);
11 UTIL1_Num16uToStrFormatted(buf, sizeof(buf), cm, ' ', 5);
12 LCD1_GotoXY(2,5);
13 LCD1_WriteString((char*)buf);
14
15 LEDR_Put(cm<10); /* red LED if object closer than 10 cm */
16 LEDB_Put(cm>=10&&cm<=100); /* blue LED if object is in 10..100 cm range */
17 LEDG_Put(cm>100); /* blue LED if object is in 10..100 cm range */
18 }
19
20 /*lint -save -e970 Disable MISRA rule (6.3) checking. */
21 int main(void)
22 /*lint -restore Enable MISRA rule (6.3) checking. */
23 {
24 /* Write your local variable definition here */
25
26 /*** Processor Expert internal initialization. DON'T REMOVE THIS CODE!!! ***/
27 PE_low_level_init();
28 /*** End of Processor Expert internal initialization. ***/
29
30 /* Write your code here */
31 US_Init();
32 LCD1_Clear();
33 LCD1_WriteLineStr(1, "us: ");
34 LCD1_WriteLineStr(2, "cm: ");
35 for(;;) {
36 Measure();
37 WAIT1_Waitms(50); /* wait at least for 50 ms until the next measurement to avoid echos */
38 }
39
40 /*** Don't write any code pass this line, or it will be deleted during code generation. ***/
41 /*** RTOS startup code. Macro PEX_RTOS_START is defined by the RTOS component. DON'T MODIFY THIS CODE!!! ***/
42 #ifdef PEX_RTOS_START
43 PEX_RTOS_START(); /* Startup of the selected RTOS. Macro is defined by the RTOS component. */
44 #endif
45 /*** End of RTOS startup code. ***/
46 /*** Processor Expert end of main routine. DON'T MODIFY THIS CODE!!! ***/
47 for(;;){}
48 /*** Processor Expert end of main routine. DON'T WRITE CODE BELOW!!! ***/
49 } /*** End of main routine. DO NOT MODIFY THIS TEXT!!! ***/
| http://www.element14.com/community/docs/DOC-51641/l/codewarrior-tutorial-for-frdm-kl25z-arduino-ultrasonic-ranging-with-the-freescale-freedom-board | CC-MAIN-2015-35 | refinedweb | 1,308 | 50.16 |
When accessing the Kubernetes API for the first time, we suggest using the
Kubernetes CLI,
kubectl.
To access a cluster, you need to know the location of the cluster and have credentials to access it. Typically, this is automatically set-up when you work through and complete documentation is found in the kubectl manual.
Kubectl handles locating and authenticating to the apiserver. If you want to directly access the REST API with an http client like curl or wget, or a browser, there are several ways to locate and authenticate:
The following command runs kubectl in a mode where it acts as a reverse proxy. It handles locating the apiserver and authenticating. Run it like this:
$ kubectl proxy --port=8080 &
See kubectl proxy for more details.
Then you can explore the API with curl, wget, or a browser, like so:
$ curl { "versions": [ "v1" ] }
It is possible to avoid using kubectl proxy by passing an authentication token directly to the apiserver, like this:
$ APISERVER=$(kubectl config view | grep server | cut -f 2- -d ":" | tr -d " ") $ TOKEN=$(kubectl config view | grep token | cut -f 2 -d ":" | tr -d " ") $ curl $APISERVER/api --header "Authorization: Bearer $TOKEN" --insecure { "versions": [ "v1" ] }
In Kubernetes version 1.3 or later,
kubectl config view no longer displays the token. Use
kubectl describe secret... to get the token for the default service account, examples use apiserver does not require authentication; it may serve on localhost, or be protected by a firewall. There is not a standard for this. Configuring Access to the API describes how a cluster admin can configure this. Such approaches may conflict with future high-availability support.
The Kubernetes project-supported Go client library is at.
To use it,
* To get the library, run the following command:
go get k8s.io/client-go/<version number>/kubernetes/1.4/pkg/api/v1" is correct.
The Go client can use the same kubeconfig file as the kubectl CLI does to locate and authenticate to the apiserver.().Pods("").List(v1.ListOptions{}) fmt.Printf("There are %d pods in the cluster\n", len(pods.Items)) ...
If the application is deployed as a Pod in the cluster, please refer to the next section.
There are client libraries for accessing the API from other languages. See documentation for other libraries for how they authenticate.
When accessing the API from a pod, locating and authenticating to the api server are somewhat different.
The recommended way to locate the apiserver within the pod is with
the
kubernetes DNS name, which resolves to a Service IP which in turn
will be routed to an apiserver.
The recommended way to authenticate to the apiserver is with a
service account credential. By kube-system, apiserver.
Finally, the default namespace to be used for namespaced API operations is placed in a file
at
/var/run/secrets/kubernetes.io/serviceaccount/namespace in each container.
From within a pod the recommended ways to connect to API are:
client.NewInCluster()factory. This handles locating and authenticating to the apiserver. See this example of using Go client library in a pod.
In each case, the credentials of the pod are used to communicate securely with the apiserver.
The previous section was about connecting the Kubernetes API server. This section is about connecting to other services running on Kubernetes cluster. In Kubernetes, the nodes, pods and services all have their own IPs. In many cases, the node IPs, pod IPs, and some service IPs on a cluster will not be routable, so they will not be reachable from a machine outside the cluster, such as your desktop machine. Kubernetes master is running at elasticsearch-logging is running at kibana-logging is running at kube-dns is running at grafana is running at heapster is running at
This shows the proxy-verb URL for accessing each service.
For example, this cluster has cluster-level logging enabled (using Elasticsearch), which can be reached
at if suitable credentials are passed,/proxy/namespaces/
namespace_name
/services/
service_name[:port_name]:
The redirect capabilities have been deprecated and removed. Please use a proxy (see below) instead.
There are several different proxies you may encounter when using Kubernetes:
LoadBalancer- use UDP/TCP only - implementation varies by cloud provider.
Kubernetes users will typically not need to worry about anything other than the first two types. The cluster admin will typically ensure that the latter types are setup correctly.
Create an Issue
Edit this Page | http://kubernetes.io/docs/user-guide/accessing-the-cluster/ | CC-MAIN-2016-50 | refinedweb | 731 | 55.24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.