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 |
|---|---|---|---|---|---|
Introduction
The Scalable Vector Graphics (SVG) specification 1.1 has been a W3C Recommendation for over three years now. Firefox 1.5 introduced a built-in SVG rendering engine, and Adobe has an SVG plug-in available for Internet Explorer. This article explains how you can use the SVG support contained in GWT Widget Library o.o.5 to render SVG elements, and how you can make your page compatible with both Firefox and Internet Explorer 6.
SVGPanel Widget
The first widget you always need to create to render SVG graphics is the SVGPanel widget. When you create this widget you need to specify the width and height or the drawing area.
SVGPanel sp = new SVGPanel(500, 300);
This panel, once created, becomes a factory for other components. This works similar to the XML DOM. In this initial release you can create circles, rectangles, ellipses, and paths.
SVGRectangle rect = p.createRectangle(x, y, width, height);
SVGCircle circle = p.createCircle(cx, cy, radius);
SVGEllipse ellipse = p.createEllipse(cx, cy, rx, ry);
SVGPath path = p.createPath(x, y);
Creating a widget this was does not add it to the drawing. You still need to add the SVGPanel via the add() method.
SVGRectangle, SVGCircle, and SVGEllipse
Once created you can set additional attributes to these objects. For all of these you may set the fill color, stroke color, fill opacity, stroke opacity, and stroke width. Each of these objects will also have attributes specific to the object type. For example, you can change the radius of a circle after it's creation, and you may extend a path by adding additional points.
Each method that sets the attribute of an object will return the object itself. This allows you to chain the setting of attributes. The only trick is that some methods belong to the super class SVGBasicShape, which will return an instance of SVGBasicShape, and not the specific subclass. So you just need to be sure to set your widget specific attributes first, followed by the attributes that belong to the super class.
Below are some concrete examples, which show off the various attributes.
p.add(p.createRectangle(0, 0, 500, 300)
.setStroke(Color.DARK_GRAY)
.setStrokeWidth(2)
.setFill(Color.LIGHT_GRAY));
p.add(p.createEllipse(250, 225, 150, 70)
.setStroke(Color.RED)
.setStrokeWidth(1)
.setFill(Color.BLUE));
p.add(p.createCircle(420, 225, 60)
.setFill(Color.BLACK)
.setStrokeWidth(15)
.setStroke(Color.WHITE));
SVGPath Widget
The path widget deserves special attention. You create a path widget by specifying the initial point on the path. From this initial point you can add additional points by drawing either straight lines or curves. You may also move the current point to include multiple lines, for example the inner and outter circles of a doughnut. You may leave the path open, or close it to create a shape. The curves may be cubic Bezier, quadratic Bezier, or elliptical arcs. Each line or curve may be specified using either absolute coordinates, or coordinates relative to the current point. I suggest reading through the path portion of the SVG specification for details on using each of the curves.
The example below draws a hexagon using relative lineTo commands, coloring the shape with red translucent fill, and an orange border.
p.add(p.createPath(150, 190)
.relLineTo(10, 0)
.relLineTo(4, 8)
.relLineTo(-4, 8)
.relLineTo(-10, 0)
.relLineTo(-4, -8)
.closePath()
.setFill(Color.RED)
.setFillOpacity(50)
.setStroke(Color.ORANGE)
.setStrokeWidth(1));
Here is another path that creates an upside-down tear-drop shape, with a translucent yellow fill.
p.add(p.createPath(250, 225)
.relMoveTo(-25, -25)
.relCurveToC(0, -25, 50, -25, 50, 0)
.relLineTo(-25, 50)
.closePath()
.setFill(Color.YELLOW)
.setFillOpacity(50)
.setStroke(Color.BLACK)
.setStrokeWidth(1));
Gradients
You may also create linear gradients that can be used to fill a widget, or in place of a stroke color. Gradients consist of one or more "stops". Each stop contains a color, and optionally an opacity . For each stop you specify the color value, and the SVG engine will transition the color/opacity between stops.
The following gradient will color a widget from red to blue. The first value of each stop is the percentage across the widget. 0% being the left-most point on the widget, to 100% being the right-most point.
SVGLinearGradient grad = p.createLinearGradient()
.addStop(0, Color.RED)
.addStop(100, Color.BLUE);
You may also change the vector of the gradient to something other then left ro right. For example, you might want to color a widget from the top to the bottom. Here is the same gradient which will color from top to bottom instead of left to right. The values are percentages of the objects width and height. Specifically this vector definition starts at 0%,0%(x,y) to 0%,100%(x.y).
SVGLinearGradient grad = p.createLinearGradient()
.addStop(0, Color.RED)
.addStop(100, Color.BLUE)
.setVector(0, 0, 0, 100);
Gradients are not widgets, so you do not add them to the SVGPanel, you just use them. Also notice that each method returns the object instance allowing you to chain method calls.
Working in the Google Hosted Browser
Good luck, it doesn't seem to work. If you are able to get this to work, I would be very interested in the solution. For development I have been compiling the Java code to JavaScript, then testing in Firefox and IE.
Setting up your HTML and Deployment
One of the trickest parts I found was trying to get the SVG content to render in both Firefox 1.5 and Internet Explorer 6. If you are using Iinternet Explorer you will need to first download and install the SVG Viewer plug-in from Adobe. I also strongly suggest reading the Inline SVG page on the SVG Wiki, it will explain in detail how to get everything working across browsers.
Below is the HTML template that I have been using.
<html xmlns=""
xmlns:
<head>
<title>SVG Component Example</title>
<meta name="'gwt:module'"
content="'org.gwtwidgets.examples.svg.Project'">
<object id="AdobeSVG"
classid="clsid:78156a80-c6a1-4bbf-8e6a-3cd390eeb4e2">
</object>
<?import namespace="svg" implementation="#AdobeSVG"?>
</head>
<body>
<script type="text/javascript" src="gwt.js">
</script>
</body>
</html>
Firefox requires that the page be either XML or XHTML, requiring the XHTML namespace definition. This is because Firefox uses a different parser for XML and HTML, and the XML parser is the one that understands SVG.
Internet Explorer requires the svg namespace declaration, as well as the
75 comments:
SCALABLE Vector Graphics, not SCALAR
Oops, thanks for the catch. Fixed.
Great article about SVG and GWT. Do you know when the API will be enhanced to also provide methods to create text using SVG?
Thanks.
Stefan
That is definately on my to-do list, but I don't have a timeframe for doing it. The biggest problem is that there is too much to do, and not enough time to do it.
I am already working with a developer who is expanding the Scriptaculous support, so perhaps someone will volunteer to round out the SVG support.
Hi Robert
Is it possible add an image in the shapes of the SVG package (SVGRectangle, SVGCircle...)?
Is it possible to use EventListener in the SVG Components??
Thanks for your help..
Adriana
Hi Robert
Is it possible add an image in the shapes of the SVG package (SVGRectangle, SVGCircle...)?
Is it possible to use EventListener in the SVG Components??
Thanks for your help..
Adriana
Adriana,
> possible add an image
Not yet.
> possible to use EventListener
Not yet.
I hope do all of those things eventually, or maybe someone will volunteer to do it. The SVG spec is huge, so it may take a while to get everything done.
If all you need is image support and (mouse?) listeners, I'll see what I can do to push them up in the priority list.
It is good to get feedback like this as it gives me an idea of what is needed the most.
Hi Rober Hanson
I want to write a program with SVG panel. when I try to use SVG component
the it makes error. for example when i create a new SVGPanel it makes Exception:
[ERROR] Unable to load module entry point class com.me.client.MyApplication
com.google.gwt.core.client.JavaScriptException: JavaScript Error exception: Unexpected call to method or property access.
at com.google.gwt.dev.shell.ie.ModuleSpaceIE6.invokeNative(ModuleSpaceIE6.java:396)
at com.google.gwt.dev.shell.ie.ModuleSpaceIE6.invokeNativeVoid(ModuleSpaceIE6.java:283)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeVoid(JavaScriptHost.java:127)
at com.google.gwt.user.client.impl.DOMImpl.appendChild(DOMImpl.java:27)
at com.google.gwt.user.client.DOM.appendChild(DOM.java:64)
at org.gwtwidgets.client.svg.SVGContainerBase.add(SVGContainerBase.java:43)
at org.gwtwidgets.client.svg.SVGPanelBase.add(SVGPanelBase.java:26)
at org.gwtwidgets.client.svg.SVGPanel.(/init)(SVGPanel.java:60)
at org.gwtwidgets.client.svg.SVGPanel.(/init)(SVGPanel.java:39)
at com.me.client.MyApplication.onModuleLoad(MyApplication.java:21)
I use eclipse IDE. please help me!
It looks like you are trying to use the hosted-mode browser. Right?
I mention that in the article, it just won't work. You need to compile the code to JavaScript, then open in your browser. The problem is that IE requires a plug-in, and this doesn't seem to work at all with the hosted-mode browser.
To Stefan, and others who were
wondering: I was wondering about
text too. But for now, perhaps it's
easier to do using PopupPanel
on top of the canvas... This is
what I came up with, and so far,
so good...
Robert,
Do you know of any way to create a simple vertical (or dotted vertical) line above a panel? I'm trying to recreate what Jack Slocum did here:
using YUI
move the column boundaries and you see a dotted vertical line floating above the table.
Since both are using javascript...there must be a way. (without using SVG)
- Bob
Bob,
If I had to do this, I think that I would probably use a div with the
height of the panel area, and a width of 2px... then use a background
image in the dix with the dotted line. The background would be about
7px high (one dash + space) and repeated top to bottom.
In GWT you could probably do this with a Popup with maybe a FlowPanel
inside, with a style on the FlowPanel to display the line.
I think that would work.
Hi Robert,
Is there anything new about the svg-events ?
I'm trying to work on that, can you give me some advice ?
> Is there anything new about the svg-events ?
SVG support is definately something that I get asked about often, but right now there are too many constraints on my time. I am hoping that things will clear up by mid-January so that I can start writing more code again.
So no, I unfortunately don't have ant tips on how to do it, but I am pretty sure that it can be done. Part of the problem is that GWT doesn't support XML namespaces, but SVG requires it. So you may have some trouble getting it to work the first time.
hi
i've found an example to give event handling to svg widget. but i can't understand why it functions with firefox, opera, and not with explorer and gwt hosted mode.
so, all you have to do is to declare a custom SVGPanel class in which you add methos for adding listeners, for example
public void addClickListener(ClickListener listener) {
if (clickListeners == null)
clickListeners = new ClickListenerCollection();
clickListeners.add(listener);
}
public void addMouseListener(MouseListener listener) {
if (mouseListeners == null)
mouseListeners = new MouseListenerCollection();
mouseListeners.add(listener);
}
and calling it
CustomSVGPanel sp = new CustomSVGPanel(800, 400);
CustomSVGCircle suca= new CustomSVGCircle(new Namespace("svg", ""),200, 225, 25);
sp.add(suca.setFill(Color.BLUE).setColor(Color.GREEN));
sp.addMouseListener(new MouseListener(){
public void onMouseDown(Widget sender, int x, int y) {
}
public void onMouseEnter(Widget sender) {}
public void onMouseLeave(Widget sender) {}
public void onMouseUp(Widget sender, int x, int y){}
public void onMouseMove(Widget sender, int x, int y){
CustomSVGPanel senderPanel = (CustomSVGPanel)sender;
((CustomSVGCircle)senderPanel.getWidget(1)).setFill(Color.RED);
}
});
if someone knows why it not functions with explorer 6 (with adobe SVG plugin istalled), please tell me!!!!
> i've found an example to give
> event handling to svg widget.
Awesome, glad to see that you got something working. The book is finishing up, so hopefully in another month or so I can get back to doing some coding.
Did you notice that the GWT roadmap included SVG support as a nice to have? It would be nice to see them get involved and throw some manpower into this.
Robert: When I load the following markup into my FireFox 1.5xx browser locally, the SVG code is rendered and the image is displayed. However, when I post it on my website and then download it into the same browser, I get a blank screen. Any suggestions as to what I am doing wrong will be greatly appreciated.
By the way, I replaced all angle brackets by entities so that I could send them via your editor.
Thanks,
Dick Baldwin
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" xml:
<head>
<meta http-
<title>Generated XHTML file</title>
</head>
<body id="body" style="position:absolute; z-index:0;border:1px solid black; left:0%; top:0%;width:90%; height:90%;">
<svg xmlns="" version="1.1" style="width:100%;height:100%;position:absolute;top:0;left:0;z-index:-1;">
<defs>
<linearGradient id="gradientA">
<stop offset="0%" style="stop-color:yellow;"/>
<stop offset="100%" style="stop-color:red;"/>
</linearGradient>
<linearGradient id="gradientB">
<stop offset="0%" style="stop-color:green;"/>
<stop offset="100%" style="stop-color:blue;"/>
</linearGradient>
</defs>
<g>
<ellipse cx="110" cy="100" rx="100" ry="40" style="fill:url(#gradientA);stroke:rgb(0,0,100);stroke-width:2"/>
<circle cx="110" cy="100" r="30" style="fill:url(#gradientB)"/>
</g>
</svg>
</body></html>
PS: I forgot to mention that the file name and extension containing the markup from my previous comment is junk.xhtml
Thanks,
Dick Baldwin
Robert,
Never mind, I found my problem - at least part of it. My real objective was to generate inline SVG code with a servlet to have it rendered on the client. It always seems to happen that as soon as I ask for help, I find the solution. In this case, the solution was to put the following statement in my servlet in place of the one that was there:
res.setContentType("image/svg+xml");
This replaced the following statement:
res.setContentType("text/html");
Thanks again.
Dick Baldwin
Glad to hear it all worked out. The whole extension/mime type issue can be problematic.
If anyone else runs into the same issue you should also check out the Inline SVG page of the SVG Wiki. Some useful tips there,.
Hi Robert
A problem that the attribute "xlink:href" cannot use a relative path of a Image. is found when I use Image tag in SVG.
Hi Robert
It looks like adobe viewer (IE 7 with adobe SVG viewer 3.0 installed) doesn't refresh plugin window if I add and remove SVG element (with Javascript produced by GWT) during runtime.
In contrary firefox mozilla 2.0.0.2 works fine (refreshes SVG ok), but doesn't allow to set attribute (example transform attribute for some SVG element) - this is reported as GWT bug ().
Does anybody experiences similar behaviour?
> In contrary firefox mozilla 2.0.0.2
> works fine (refreshes SVG ok), but
> doesn't allow to set attribute
Take a look at org.gwtwidgets.client.ext.ExtDOM. You might be able to use ExtDom.setAttributeNS(element, "prop", "value"). This is what all of the SVG widgets use internally to set the element attributes.
As for IE... well, I have this feeling that it just isn;t going to pan out. The worst part is that Adobe doesn't even support the plug-in any longer. There is talk about a cross-browser vector API that will use SVG on FF, and VML on IE. I figure it will take a while before we see that though.
Hi Robert!
The W3C has defined the SVG specification and provided some interface. Wyh do not you implement the iterface.
Yonghe, that is indeed a very good question. I believe that when I wrote the SVG code that I did notice the W3C API... and if memory serves (it was 8 months ago), I _think_ that I just didn't like their API. I would need to look at the API again to be sure, but I think that was my thinking at the time.
...And for the record, I really dislike the DOM API as well. It is too verbose for every day use. When O coded Perl I published a module XML::EasyOBJ to make using the DOOM easier, and now that I have moved to Java I tend to use the programmer-friendly JDom.
If you are a standards purist, it is likely that you won't agree with that decision.
Is there any methods to load external SVG file to SVGPanel to display it's content??
Grzegorz, no, not currently.
Hi Robert Hanson!
The SVG standard is really too verbose, but it defines all features for SVG, if you write the SVG implementation without SVG standard, you have to refer to large numbers of document about SVG standard, it is troublesome.
By the way,I am not a standards purist, I am developping an application that depends on the SVG in web and I would like to join your project. Could you accept my application?.'
Yonghe, I am hesitant to accept an application out of the blue. If you want to submit widgets/patches, then I am more than happy to accept, review, add them.
As far as sticking to the SVG spec... if you feel that is the way to go, then maybe you should start your own project and feel free to use whatever parts of my code are useful.
As far as long-term SVG support goes, there is an expectation that the GWT core API will include a generic vector graphics API that will use SVG on FF and VML on IE. I expect though that it will be some time before we see that, and because it is generic, it will likly be missing some of what SVG has to offer.
Scott, regarding...
> svgElement.animationsPaused()
The SVG support in the GWT-WL is far from complete, and I am not sure that it ever will be.
If this is possible at all, and it might not even be supported in IE (I really don't know), then you would need to use JSNI in order to do this..'
Hi Robert!
Could you give me a email that can help me to contact with you frequently.
Sure, IamRobertHanson at gmail.com.
I can't guarantee me responsiveness though. I tend to only respond to my personal email in the mornings, and not during work hours.
did work for me in the hosted browser. I use IE7.
Hi, I was wondering if support had been added for event listeners. Please let me know. Thanks.
No, there isn't support for listeners yet. I have had almost no time to work on the library for a long time due to work, the book, and now a new baby.
But... if someone has already figure out how to accomplish this, code patches are welcome.
It seems that Adobe plugin cannot show svg elements that have been added after initWidget() call.
Does somebody have idea how to overcome this ?
I got an svg file which has the following attributes:
xml:space="preserve" width="271mm" height="195mm" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd"
viewBox="0 0 271000 194640"
This means that the paths that are made have such coordinates as: 121628. But the final "image" scales ok so that I don't loose precision. Is there a way, using your API, to set this scale so that I can use the same coordinates (there are *many* of them, and since they relate to a map, I can't simply loose precision)?
Thanks and congrats for your great work.
> Is there a way, using your API,
> to set this scale
No, not currently, but it should be easy to add. All of the source is in the jar file, so I encourage you to try it out for yourself.
As far as seeing this feature in a new release... it could be some time.
<long-story>
Now that I finally have time to work on the GWT-WL again it seems that the next release (1.4) of GWT will break SVG support.
So as of GWT-WL 0.1.4 I have removed SVG support since it won't work anyway. At a later date it is expected that GWT will be able to support SVG again, which is when I will add it back to the GWT-WL.
</long-story>
So... as long as you stick with GWT 1.3 and GWT-WL 0.1.3 you can still use the SVG support as-is. But until SVG works with new versions of GWT I don't plan on extending the SVG support.
Hi Robert, looking at Google Groups it seems it is possible to use svg with gwt 1.4. I still have to give it a try, but I was wondering if you tried to adapt your library..
Cheers,
Vito.
Vito, thanks for pointing out this post. It has been awhile since I looked at the SVG code in the GWT-WL, but I expect that it could work.
I recently upgraded my code to GWT 1.4 and very happily realized that SVG widgets are indeed working with this new GWT version!! So, I was wondering:
"But until SVG works with new versions of GWT I don't plan on extending the SVG support."
Will you now think about extending the SVG widgets to support event listening? I am working on this myself but unfortunately not getting any far..
Any ideas or details on how to accomplish this would be greatly appreciated.
Thanks!
I've started working on adding support to GWT for non-HTML document types, in particular SVG. There are basically two parts to this:
* Adapting GWT bootstrap to work in XML
* Adding a "wrapper" implementation for the org.w3c.dom APIs
The GWT-DOM Google code project has been created for this purpose.
To see a demo, point Firefox 2.x at at this example.
See also this thread in the GWT-contributors forum.
Archie,
I would like to check out your library, especially the svg part. But I haven't really seen any javadoc or example code on how to start with it. Do you think you can provide the code of your demo (or any other sample code) and possibly a javadoc of your library?
Thank you very much for your help..
Sure, just check out the code, it's all there at:
I notice that for SVG to work, or at least inline SVG, I need to send my HTML page with content type "application/xhtml+xml", so that Firefox's XML parser (and SVG parser) picks it up. However, for GWT it seems to be necessary to send content type "text/html", otherwise I get a warning in hosted mode, and no rendering at all in web mode. Does this mean the GWT and (inline) SVG are incompatible? It seems like some you people get it working anyway. Why does GWT not allow for content type "application/xhtml+xml"?
Jeroen,
I have had a falling out with SVG + GWT, so I really haven't been following it, but I *think* that GWT 1.5 (when it comes out) will work ok with XHTML. Don't hold me to that though.
hi
i want to start using svg with gwt. please tell me from where will i get the package for svg support in gwt.
expecting immediate help
Tanzeem
The GWT-WL () had support in 1.3... but then it broke, but some have said that they could get it to work.
You should probably ask on the dev list () to see if anyone is actively using GWT + SVG, and ask them what they are using.
I think SVG+GWT would be quite an interesting subject to the people at the SVG world conference SVG Open. Can you or someone else make it there?
Paper abstract deadline is at the end of this month.
Hope to see you in Nuremberg
Stelt, an interesting idea, but unless they paid my way I wouldn't be able to afford to make the trip. Nuremberg is a bit of a drive from New Jersey, and with gas prices being what they are...
Do you know another good candidate?
Someone that doesn't have to drive across an ocean to get to Nuremberg maybe?
Stelt, sorry, I can't say that I do.
i have to get a vector graphics drawn in the panel and i am getting lot of errors.I also tried JSGraphics from the latest GWT-WL.No effect. Can anyone give me a complete sample program(instead of code snippets) that uses SVGPanel or JSGraphics.
Hi,
I'm using widgets-1.3 with gwt 1.4 to draw svg objects and it seems to work fine in gwt hosted mode.
I added eventlisteners to the SWGWidget object(thanks guido) and it seems to work fine in hosted mode as well.
This was really helpful. Thank you Robert !
I have your Draw Sample example running in GWT-shell if you're still interested.
I would like to see the draw sample. But i got a solution using a gwt dojo wrapper called tatami.I found it much efficient than the SVG option . Thanks
Thanks cheapwhyskey (nice nick), but I don't think that I have the time to properly maintain it. I would very much like to see someone else take up the torch.
BTW - It may be of interest that there is a new Canvas widget in GWT-WL 0.2.0. It uses the <canvas> element in non-IE browsers and VML in IE. Using <canvas> is a *lot* faster than SVG (or VML for that matter).
Hi,
I am using GWT and want to use SVG. Please guide the example code posted above on the page, how can i use it step by step.
Please guide, i need solution urgently!
/Danish
AA, this post is over two years old, and GWT has changed in significant ways.
I had been experimenting with GWT + SVG but abandoned it for several reasons. One being that there are no supported plugins for IE, and second because Canvas is a LOT faster if you use FF or Safari.
You should post your question on the dev list to see if anyone has any success stories to share.
Thanks. Actually, I want to use some simplest way to use SVG in the GWT. I hope you would be having a lots of information in this regard. I can not find much on it. Please share some links etc. I will be thankful to you!
/Danish
Search for SVG on the dev list, that is your best bet.
Hi, Its hard to read the code as I have problems with identifying colors.
I have a question:
To do this tutorial of Robert Hanson it is necessary a jar? here I did not find the jar to include thank you for help.
BOUKHARY.
Hi
I look for the jar that allows doing this tutoriel (SVG + GWT) for I do not find the link thank you.
Kazebliz
Baukhary, you can get all of the older versions of GWT-WL here.
Note that the early versions only worked with GWT 1.3 (or older). SVG support was removed in version 0.1.4, so use 0.1.3 or earlier.
Is it possible to run GWT-Widgets 0.1.3 with GWT 1.7?
I'm getting some errors when compiling althougth it finish compilation by removing some unnecessary items.
Is the svg picture displayed in hostmode debugging?
Thanks in advance... i've been battling serveral days ;)
Jlanza, nope, it won't work.
There is a project I just found out about that may be of interest,. It is JS, not GWT, but supposedly has cross-browser SVG support. Maybe it would be possible to create a quick wrapper around it so that it can be used in GWT.
Hi robert,
I will take a look at it.
BTW I have taken your code from 1.3 a modified it a little to fit the group, and other svg items. Now I'm working with the image, but I don't manage to get it displayed.
I get the rectangles,... and the image in the xml code of the page, but it is not displayed.
jlanza, glad to hear it is being used. I wish I could help with the images, but I don't have any ideas, it has been a very long time since I looked at that code.
Hi Robert! What do you think about using GWT generated javascript for manipulating not HTML DOM, but SVG DOM? I would like to animate existing HTML-embedded SVG images by javascript generated from GWT. Just something "like Flash". SVG can be manipulated by java-jar, but this is not fully supported in contrast with javascript SVG manipulation, which is widely supported. I don't know the resulting speed of this solution, but it may be depends on browser SVG DOM and javascript implemetation?
Well, IE doesn't support SVG, so that will be an issue, and the speed is generally slow.
If you were to go through with this, I suggest leveraging the work of others. You should be able to take, and wrap it in GWT classes. The SVGWeb team has been wanting to do this anyway, so maybe you could help them.
Hi,
I am trying to run the gwt-examples-draw-1.0 for the first time and after seeing some text with a broken image box, I found my way to the README.txt file.
The major issue I am having is that the domain and there for web site;
is no longer up. Does anyone have any clue where I can get the required javascript library?
TIA,
Scott (adligo.com)
Huh, too bad that site is down. I searched for Walter Zorn on Google, and didn't find a site for his stuff anywhere.
Anyway, I have a demo using JSGraphics at, which uses the source file from.
Unfortunately I don't have any of the JSGraphics docs, but they were likely archived by the Way Back Machine (). If you search for there, you should be able to find the documentation. (I would send a direct link, but archive.org is excessively slow this morning) | http://blog.mental.ninja/2006/06/coding-svg-with-gwt.html?showComment=1152154620000 | CC-MAIN-2019-18 | refinedweb | 5,207 | 74.69 |
vikramca06
10-05-2017
Hi,
I want to know how "prism:expirationDate" property works for Asset deactivation.
What is the difference between asset "offTime" and "prism:expirationDate"?
Regards,
Vikram.
MC_Stuff
Hi Vikram,
PRISM Namespace is consolidate all rights related elements within a single namespace. AFAIK oob does not use it & may be as part of meta data extraction it might exist.
Offtime just adds attribute as properties to the content & when you activate content will be available in publish. When Off time matches or greater than current time , AEM OSGI Services consider that content as dead and if you try to access using HTTP, AEM would return 404 error but content will still leave in publish instance. if you don;t want content to stay then need to deactivate.
Thanks,
sneh1
Expiry date is used for rights management purpose. If an asset reaches expiry date, only restricted action actions can be performed on it by non admin users.
Complete documentation available @... | https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager-assets/what-is-the-use-of-quot-prism-expirationdate-quot-and-how-does/qaq-p/208578 | CC-MAIN-2021-17 | refinedweb | 161 | 55.64 |
How to search contents of RTF files using Smart Search Štěpán Kozák — Jul 10, 2014 smart search As I mentioned in my Kentico 8 preview article about Smart Search quite a while ago, Kentico 8 comes with full support for indexing the content of attachment files. The list of support files is quite extensive, however there are still some common files missing. In this article I’ll add support for RTF files which is not among files supported out of the box. To be able to add support for indexing the content of RTF files, first we need to know how attachment content indexing works behind the scenes. The indexing is provided by so called “search text extractors”. The default ones are all in the CMS.Search.TextExtractors namespace. If you configure your Smart Search index to also index attachment content and rebuild the index, then the indexer goes through each attachment it finds attached to the document it’s indexing and the following occurs: The indexer looks at the extension of the file—if the extension is not among those supported it does nothing. If the extension is among the supported files, it gets the binary data of the file and passes it on to the corresponding text extractor registered in the system for this file type. The text extractor takes the file binary data, interprets it, and returns a pure text representation of the file back to the indexer. The indexer caches the extracted text to the AttachmentSearchContent column of attachment in the DB so next time the content is needed it does not have to be extracted (as this can be quite a resource-demanding process). If the attachment is updated, Kentico makes sure the cached value in AttachmentSearchContent is cleared so the search process can call the extractor again to get fresh data. Now understanding how indexing files for content works, we can change our goal from “Adding support for RTF files to Smart Search” to the more technical and more specific “Creating RTF text search extractors”. In this article you’ll learn two things: How to create a custom text extractor to Smart Search How to create a custom module recognized by Kentico just by copying its dll to bin folder. Let’s start with the extractor class itself. The development process is very easy; you just create your custom class (let’s name it RtfTextExtractor) and implement the interface IsearchTextExtractor. This forces you to implement the method ExtractContent, which turns the binary data of the given physical file to its text representation. Just one note about why this method does not return string but an XmlData object: it’s because you may want to index parts of your physical file to different fields of your smart search index document. For example, we may want to extract the metadata of the RTF file, such as author, and store it to the field “Author”, while the rest (the actual contents of the RTF file) might go to the default content field. In this example we will ignore the metadata of the RTF file and just index its contents. To implement the extraction, we’ll use the RichTextBox control as recommended on MSDN, so our extractor will look like this: The next thing we need to ensure is to let Kentico know about the extractor so it can use it for extracting content from the RTF files. My goal is to create a reusable library that I can quickly copy to any of my Kentico instances bin folder whenever I need this instance to be able to index RTF files. To do that, I will create a Kentico module library. This is done by creating a standard c# class library project, referencing required dlls from the Kentico 8 instance, and then adding a special Module class and one assembly attribute to the AssemblyInfo.cs class. The module class can have an arbitrary name. The important thing is that you inherit from a CMS.DataEngine.Module class and provide a parameter-less constructor by inheriting from the default constructor and specifying the module name. The inheritance from Module class provides you with a OnPreInit method where you can register your new extractor. This method is guaranteed to be called at application start, so that’s what we need. The AssemblyDiscoverable attribute in AssembylInfo.cs class then ensures Kentico will load this assembly on application init, look for all the modules in this assembly, and call their OnPreInit methods on application start. It all should look like this: Now we are ready with development. It’s enough to rebuild the project to get the dll and copy it to bin folder of your Kentico instance. Or if you develop in the solution of your Kentico instance, just add a reference to the RTF extractor project to your web project. This will cause an application restart and if you look in Event log application at an Application_Start event, you should see our module among the modules initialized. Henceforth, your Kentico instance supports the indexing of RTF files! Wasn't that easy? :-) You can download the complete code of this library along with compiled dlls from our Marketplace. PS: Just a quick tip at the end. If you would like to have search functionality over the contents of your media library files, there is nothing easier than creating a custom search index. This will call the extractors API to get the contents of the media files, as this API is public. So to get the text contents of a Word file you’d just call this line of Kentico API: var xmlData = new CMS.Search.TextExtractors.DocxSearchTextExtractor(...); Did you know there was such an API in Kentico 8? :-) Share this article on Twitter Facebook LinkedIn Google+ Štěpán Kozák Comments | https://devnet.kentico.com/articles/how-to-search-contents-of-rtf-files-using-smart-search | CC-MAIN-2018-13 | refinedweb | 968 | 57.61 |
The Jupyter Notebook has a feature known as widgets. If you have ever created a desktop user interface, you may already know and understand the concept of widgets. They are basically the controls that make up the user interface. In your Jupyter Notebook you can create sliders, buttons, text boxes and much more.
We will learn the basics of creating widgets in this chapter. If you would like to see some pre-made widgets, you can go to the following URL:
These widgets are Notebook extensions that can be installed in the same way that we learned about in my Jupyter extensions article. They are really interesting and well worth your time if you’d like to study how more complex widgets work by looking at their source code.
Getting Started
To create your own widgets, you will need to install the ipywidgets extension.
Installing with pip
Here is how you would install the widget extension with pip:
pip install ipywidgets jupyter nbextension enable --py widgetsnbextension
If you are using virtualenv, you may need to use the
--sys-prefix option to keep your environment isolated.
Installing with conda
Here is how you would install the widgets extension with conda:
conda install -c conda-forge ipywidgets
Note that when installing with conda, the extension will be automatically enabled.
Learning How to Interact
There are a number of methods for creating widgets in Jupyter Notebook. The first and easiest method is by using the interact function from ipywidgets.interact which will automatically generate user interface controls (or widgets) that you can then use to explore your code and interact with data.
Let's start out by creating a simple slider. Start up a new Jupyter Notebook and enter the following code into the first cell:
from ipywidgets import interact def my_function(x): return x # create a slider interact(my_function, x=20)
Here we import the interact class from ipywidgets. Then we create a simple function called my_function that accepts a single argument and then returns it. Finally we instantiate interact by passing it a function along with the value that we want interact to pass to it. Since we passed in an integer (i.e. 20), the interact class will automatically create a slider.
Try running the cell that contains the code above and you should end up with something that looks like this:
That was pretty neat! Try moving the slider around with your mouse. If you do, you will see that the slider updates interactively and the output from the function is also automatically updated.
You can also create a FloatSlider by passing in floating point numbers instead of integers. Give that a try to see how it changes the slider.
Checkboxes
Once you are done playing with the slider, let's find out what else we can do with interact. Add a new cell in the same Jupyter Notebook with the following code:
interact(my_function, x=True)
When you run this code you will discover that interact has created a checkbox for you. Since you set "x" to **True**, the checkbox is checked. This is what it looked like on my machine:
You can play around with this widget as well by just checking and un-checking the checkbox. You will see its state change and the output from the function call will also get printed on-screen.
Textboxes
Let's change things up a bit and try passing a string to our function. Create a new cell and enter the following code:
interact(my_function, x='Jupyter Notebook!')
When you run this code, you will find that interact generates a textbox with the string we passed in as its value:
Try editing the textbox's value. When I tried doing that, I saw that the output text also changed.
Comboboxes / Drop-downs
You can also create a combobox or drop-down widget by passing a list or a dictionary to your function in interact. Let's try passing in a list of tuples and see how that behaves. Go back to your Notebook and enter the following code into a new cell:
languages = [('Python', 'Rocks!'), ('C++', 'is hard!')] interact(my_function, x=languages)
When you run this code, you should see "Python" and "C++" as items in the combobox. If you select one, the Notebook will display the second element of the tuple to the screen. Here is how my mine rendered when I ran this example:
If you'd like to try out a dictionary instead of a list, here is an example:
languages = {'Python': 'Rocks!', 'C++': 'is hard!'} interact(my_function, x=languages)
The output of running this cell is very similar to the previous example.
More About Sliders
Let's back up a minute so we can talk a bit more about sliders. We can actually do a bit more with them than I had originally let on. When you first created a slider, all you needed to do was pass our function an integer. Here's the code again for a refresher:
from ipywidgets import interact def my_function(x): return x # create a slider interact(my_function, x=20)
The value, 20, here is technically an abbreviation for creating an integer-valued slider. The code:
interact(my_function, x=20)
is actually the equivalent of the following:
interact(my_function, x=widgets.IntSlider(value=20))
Technically, Bools are an abbreviation for Checkboxes, lists / dicts are abbreviations for Comboboxes, etc.
Anyway, back to sliders again. There are actually two other ways to create integer-valued sliders. You can also pass in a tuple of two or three items:
- (min, max)
- (min, max, step)
This allows us to make the slider more useful as now we get to control the min and max values of the slider as well as set the step. The step is the amount of change to the slider when we change it. If you want to set an initial value, then you need to change your code to be like this:
def my_function(x=5): return x interact(my_function, x=(0, 20, 5))
The x=5 in the function is what sets the initial value. I personally found that a little counter-intuitive as the IntSlider itself appears to be defined to work like this:
IntSlider(min, max, step, value)
The interact class does not instantiate IntSlider the same way that you would if you were creating one yourself.
Note that if you want to create a FloatSlider, all you need to do is pass in a float to any of the three arguments: min, max or step. Setting the function's argument to a float will not change the slider to a FloatSlider.
Using interact as a decorator
The interact class can also be used as a Python decorator. For this example, we will also add a second argument to our function. Go back to your running Notebook and add a new cell with the following code:
from ipywidgets import interact @interact(x=5, y='Python') def my_function(x, y): return (x, y)
You will note that in this example, we do not need to pass in the function name explicitly. In fact, if you did so, you would see an error raised. Decorators call functions implicitly. The other item of note here is that we are passing in two arguments instead of one: an integer and a string. As you might have guessed, this will create a slider and a text box respectively:
As with all the previous examples, you can interact with these widgets in the browser and see their outputs.
Fixed Arguments
There are many times where you will want to set one of the arguments to a set or fixed value rather than allowing it to be manipulated through a widget. The Jupyter Notebook ipywidgets package supports this via the fixed function. Let's take a look at how you can use it:
from ipywidgets import interact, fixed @interact(x=5, y=fixed('Python')) def my_function(x, y): return (x, y)
Here we import the fixed function from ipywidgets. Then in our interact decorator, we set the second argument as "fixed". When you run this code, you will find that it only creates a single widget: a slider. That is because we don't want or need a widget to manipulate the second argument.
In this screenshot, you can see that we have just the one slider and the output is a tuple. If you change the slider's value, you will see just the first value in the tuple change.
The interactive function
There is also a second function that is worth covering in this chapter that is called interactive. This function is useful during those times when you want to reuse widgets or access the data that is bound to said widgets. The biggest difference between interactive and interact is that with interactive, the widgets are not displayed on-screen automatically. If you want the widget to be shown, then you need to do so explicitly.
Let's take a look at a simple example. Open up a new cell in your Jupyter Notebook and enter the following code:
from ipywidgets import interactive def my_function(x): return x widget = interactive(my_function, x=5) type(widget)
When you run this code, you should see the following output:
ipywidgets.widgets.interaction.interactive
But you won't see a slider widget like you did had you used the interact function. Just to demonstrate, here is a screenshot of what I got when I ran the cell:
If you'd like the widget to be shown, you need to import the display function. Let's update the code in the cell to be the following:
from ipywidgets import interactive from IPython.display import display def my_function(x): return x widget = interactive(my_function, x=5) display(widget)
Here we import the display function from IPython.display and then we call it at the end of the code. When I ran this cell, I got the slider widget:
Why is this helpful? Why wouldn't you just use interact instead of jumping through extra hoops? Well the answer is that the interactive function gives you additional information that interact does not. You can access the widget's keyword arguments and its result. Add the following two lines to the end of the cell that you just edited:
print(widget.kwargs) print(widget.result)
Now when you run the cell, it will print out the arguments that were passed to the function and the return value (i.e. result) of calling the function.
Wrapping Up
We learned a lot about Jupyter Notebook widgets in this chapter. We covered the basics of using the `interact` function as well as the `interactive` function. However there is more that you can about these functions by checking out the documentation.
Even this is just scratching the surface of what you can do with widgets in Jupyter. In the next chapter we will dig into creating widgets by hand outside of using the interact / interactive functions we learned about this in this chapter. We will learn much more about how widgets work and how you can use them to make your Notebooks much more interesting and potentially much more powerful.
Related Reading
- Jupyter Notebook Extension Basics
- Creating Presentations with Jupyter Notebook | https://www.blog.pythonlibrary.org/2018/10/23/creating-jupyter-notebook-widgets-with-interact/ | CC-MAIN-2020-10 | refinedweb | 1,879 | 60.95 |
).
De-randomization of the data
One of the missing things on the last chapter was the frame data de-randomization. The data inside the frame (excluding the sync word) is randomized by a generator polynomial. This is done because of few things:
- Pseudo-random Symbols distribute better the energy in the spectrum
- Avoids “line-polarization” effect when sending a continuous stream of 1’s
- Better Clock Recovery due more changes in symbol polarity
CCSDS has a standard Polynomial as well, and the image below shows how to generate the pseudo-random bistream:
CCSDS Pseudo-random Bitstream Generator
The PN Generator polynomial (as shown in the LRIT spec) is x^8 + x^7 + x^5 + x^3 + 1. You can check several PN Sequence Generators on the internet, but since the repeating period of this PN is 255 bytes and we’re xor’ing with our bytestream I prefer to make a lookup table with all the 255 byte sequence and then just xor (instead generating and xor). Here is the 255 byte PN:
char pn[255] = { 0xff, 0x48, 0x0e, 0xc0, 0x9a, 0x0d, 0x70, 0xbc, 0x8e, 0x2c, 0x93, 0xad, 0xa7, 0xb7, 0x46, 0xce, 0x5a, 0x97, 0x7d, 0xcc, 0x32, 0xa2, 0xbf, 0x3e, 0x0a, 0x10, 0xf1, 0x88, 0x94, 0xcd, 0xea, 0xb1, 0xfe, 0x90, 0x1d, 0x81, 0x34, 0x1a, 0xe1, 0x79, 0x1c, 0x59, 0x27, 0x5b, 0x4f, 0x6e, 0x8d, 0x9c, 0xb5, 0x2e, 0xfb, 0x98, 0x65, 0x45, 0x7e, 0x7c, 0x14, 0x21, 0xe3, 0x11, 0x29, 0x9b, 0xd5, 0x63, 0xfd, 0x20, 0x3b, 0x02, 0x68, 0x35, 0xc2, 0xf2, 0x38, 0xb2, 0x4e, 0xb6, 0x9e, 0xdd, 0x1b, 0x39, 0x6a, 0x5d, 0xf7, 0x30, 0xca, 0x8a, 0xfc, 0xf8, 0x28, 0x43, 0xc6, 0x22, 0x53, 0x37, 0xaa, 0xc7, 0xfa, 0x40, 0x76, 0x04, 0xd0, 0x6b, 0x85, 0xe4, 0x71, 0x64, 0x9d, 0x6d, 0x3d, 0xba, 0x36, 0x72, 0xd4, 0xbb, 0xee, 0x61, 0x95, 0x15, 0xf9, 0xf0, 0x50, 0x87, 0x8c, 0x44, 0xa6, 0x6f, 0x55, 0x8f, 0xf4, 0x80, 0xec, 0x09, 0xa0, 0xd7, 0x0b, 0xc8, 0xe2, 0xc9, 0x3a, 0xda, 0x7b, 0x74, 0x6c, 0xe5, 0xa9, 0x77, 0xdc, 0xc3, 0x2a, 0x2b, 0xf3, 0xe0, 0xa1, 0x0f, 0x18, 0x89, 0x4c, 0xde, 0xab, 0x1f, 0xe9, 0x01, 0xd8, 0x13, 0x41, 0xae, 0x17, 0x91, 0xc5, 0x92, 0x75, 0xb4, 0xf6, 0xe8, 0xd9, 0xcb, 0x52, 0xef, 0xb9, 0x86, 0x54, 0x57, 0xe7, 0xc1, 0x42, 0x1e, 0x31, 0x12, 0x99, 0xbd, 0x56, 0x3f, 0xd2, 0x03, 0xb0, 0x26, 0x83, 0x5c, 0x2f, 0x23, 0x8b, 0x24, 0xeb, 0x69, 0xed, 0xd1, 0xb3, 0x96, 0xa5, 0xdf, 0x73, 0x0c, 0xa8, 0xaf, 0xcf, 0x82, 0x84, 0x3c, 0x62, 0x25, 0x33, 0x7a, 0xac, 0x7f, 0xa4, 0x07, 0x60, 0x4d, 0x06, 0xb8, 0x5e, 0x47, 0x16, 0x49, 0xd6, 0xd3, 0xdb, 0xa3, 0x67, 0x2d, 0x4b, 0xbe, 0xe6, 0x19, 0x51, 0x5f, 0x9f, 0x05, 0x08, 0x78, 0xc4, 0x4a, 0x66, 0xf5, 0x58 };
And for de-randomization just xor’it with the frame (excluding the 4 byte sync word):
for (int i=0; i<1020; i++) { decodedData[i] ^= pn[i%255]; }
Now you should have the de-randomized frame.
Reed Solomon Error Correction
Other of the things that were missing on the last part is the Data Error Correction. We already did the Foward Error Correction (FEC, the viterbi), but we also can do Reed Solomon. Notice that Reed Solomon is completely optional if you have good SNR (that is better than 9dB and viterbi less than 50 BER) since ReedSolomon doesn’t alter the data. I prefer to use RS because I don’t have a perfect signal (although my average RS corrections are 0) and I want my packet data to be consistent. The RS doesn’t usually add to much overhead, so its not big deal to use. Also the libfec provides a RS algorithm for the CCSDS standard.
I will assume you have a uint8_t buffer with a frame data of 1020 bytes (that is, the data we got in the last chapter with the sync word excluded). The CCSDS standard RS uses 255,223 as the parameters. That means that each RS Frame has 255 bytes which 223 bytes are data and 32 bytes are parity. With this specs, we can correct any 16 bytes in our 223 byte of data. In our LRIT Frame we have 4 RS Frames, but the structure are not linear. Since the Viterbi uses a Trellis diagram, the error in Trellis path can generate a sequence of bad bytes in the stream. So if we had a linear sequence of RS Frames, we could corrupt a lot of bytes from one frame and lose one of the RS Frames (that means that we lose the entire LRIT frame). So the data is interleaved by byte. The image below shows how the data is spread over the lrit frame.
For correcting the data, we need to de-interleave to generate the four RS Frames, run the RS algorithm and then interleave again to have the frame data. The [de]interleaving process are very simple. You can use these functions to do that:
#define PARITY_OFFSET 892 void deinterleaveRS(uint8_t *data, uint8_t *rsbuff, uint8_t pos, uint8_t I) { // Copy data for (int i=0; i<223; i++) { rsbuff[i] = data[i*I + pos]; } // Copy parity for (int i=0; i<32; i++) { rsbuff[i+223] = data[PARITY_OFFSET + i*I + pos]; } } void interleaveRS(uint8_t *idata, uint8_t *outbuff, uint8_t pos, uint8_t I) { // Copy data for (int i=0; i<223; i++) { outbuff[i*I + pos] = idata[i]; } // Copy parity - Not needed here, but I do. for (int i=0; i<32; i++) { outbuff[PARITY_OFFSET + i*I + pos] = idata[i+223]; } }
For using it on LRIT frame we can do:
#define RSBLOCKS 4 int derrors[4] = { 0, 0, 0, 0 }; uint8_t rsWorkBuffer[255]; uint8_t rsCorrectedData[1020]; for (int i=0; i<RSBLOCKS; i++) { deinterleaveRS(decodedData, rsWorkBuffer, i, RSBLOCKS); derrors[i] = decode_rs_ccsds(rsWorkBuffer, NULL, 0, 0); interleaveRS(rsWorkBuffer, rsCorrectedData, i, RSBLOCKS); }
In the variable derrors we will have how many bytes it was corrected for each RS Frames. In rsCorrectedData we will have the error corrected output. The value -1 in derrors it means the data is corrupted beyond correction (or the parity is corrupted beyond correction). I usually drop the entire frame if all derrors are -1, but keep in mind that the corruption can happen in the parity only (we can have corrupted bytes in parity that will lead to -1 in error correction) so it would be wise to not do like I did. After that we will have the corrected LRIT Frame that is 892 bytes wide.
Virtual Channel Demuxer
Now we will demux the Virtual Channels. I current save all virtual channel payload (the 892 bytes) to a file called channel_ID.bin then I post process with a python script to separate the channel packets. Parsing the virtual channel header has also some advantages now that we can see if for some reason we skipped a frame of the channel, and also to discard the empty frames (I will talk about it later).
VCDU Header
Fields:
- Version Number – The Version of the Frame Data
- S/C ID – Satellite ID
- VC ID – Virtual Channel ID
- Counter – Packet Counter (relative to the channel)
- Replay Flag – Is 1 if the frame is being sent again.
- Spare – Not used.
Basically we will only use 2 values from the header: VCID and Counter.
uint32_t swapEndianess(uint32_t num) { return ((num>>24)&0xff) | ((num<<8)&0xff0000) | ((num>>8)&0xff00) | ((num<<24)&0xff000000); } (...) uint8_t vcid = (*(rsCorrectedData+1)) & 0x3F; // Packet Counter from Packet uint32_t counter = *((uint32_t *) (rsCorrectedData+2)); counter = swapEndianess(counter); counter &= 0xFFFFFF00; counter = counter >> 8;
I usually save the last counter value and compare with the current one to see if I lost any frame. Just be carefull that the counter value is per channel ID (VCID). I actually never got any VCID higher than 63, so I store the counter in a 256 int32_t array.
One last thing I do in the C code is to discard any frame that has 63 as VCID. The VCID 63 only contains Fill Packets, that is used for keeping the satellite signal continuous, even when not sending anything. The payload of the frame will always contain the same sequence (that can be sequence of 0, 1 or 01).
Packet Demuxer
Having our virtual channels demuxed for files channel_ID.bin, we can do the packet demuxer. I did the packet demuxer in python because of the easy of use. I plan to rewrite in C as well, but I will explain using python code.
Channel Data
Each channel Data can contain one or more packets. If the Channel contains and packet end and another start, the First Header Pointer (the 11 bits from the header) will contain the address for the first header inside the packet zone.
First thing we need to do is read one frame from a channel_ID.bin file, that is, 892 bytes (6 bytes header + 886 bytes data). We can safely ignore the 6 bytes header from VCDU now since we won’t have any usefulness for this part of the program. The spare 5 bits in the start we can ignore, and we should get the FHP value to know if we have a packet start in the current frame. If we don’t, and there is no pending packet to append data, we just ignore this frame and go to the next one. The FHP value will be 2047 (all 1’s) when the current frame only contains data related to a previous packet (no header). If the value is different than 2047 then we have a header. So let’s handle this:
data = data[6:] # Strip channel header fhp = struct.unpack(">H", data[:2])[0] & 0x7FF data = data[2:] # Strip M_PDU Header #data is now TP_PDU if not fhp == 2047: # Frame Contains a new Packet # handle new header
So let’s talk first about handling a new packet. Here is the structure of a packet:
Packet Structure (CP_PDU)
We have a 6 byte header containing some useful info, and a user data that can vary from 1 byte to 8192 bytes. So this packet can span across several frames and we need to handle it. Also there is another tricky thing here: Even the packet header can be split across two frames (the 6 first bytes can be at two frames) so we need to handle that we might not have enough data to even check the packet header. I created a function called CreatePacket that receives a buffer parameter that can or not have enough data for creating a packet. It will return a tuple that contains the APID for the packet (or -1 if buffer doesn’t have at least 6 bytes) and a buffer that contains any unused data for the packet (for example if there was more than one packet in the buffer). We also have a function called ParseMSDU that will receive a buffer that contains at least 6 bytes and return a tuple with the MSDU (packet) header decomposed. There is also a SavePacket function that will receive the channelId (VCID) and a object to save the data to a packet file. I will talk about the SavePacket later.
import struct SEQUENCE_FLAG_MAP = { 0: "Continued Segment", 1: "First Segment", 2: "Last Segment", 3: "Single Data" } pendingpackets = {} def ParseMSDU(data): o = struct.unpack(">H", data[:2])[0] version = (o & 0xE000) >> 13 type = (o & 0x1000) >> 12 shf = (o & 0x800) >> 11 apid = (o & 0x7FF) o = struct.unpack(">H", data[2:4])[0] sequenceflag = (o & 0xC000) >> 14 packetnumber = (o & 0x3FFF) packetlength = struct.unpack(">H", data[4:6])[0] -1 data = data[6:] return version, type, shf, apid, sequenceflag, packetnumber, packetlength, data def CreatePacket(data): while True: if len(data) < 6: return -1, data version, type, shf, apid, sequenceflag, packetnumber, packetlength, data = ParseMSDU(data) pdata = data[:packetlength+2] if apid != 2047: pendingpackets[apid] = { "data": pdata, "version": version, "type": type, "apid": apid, "sequenceflag": SEQUENCE_FLAG_MAP[sequenceflag], "sequenceflag_int": sequenceflag, "packetnumber": packetnumber, "framesdropped": False, "size": packetlength } print "- Creating packet %s Size: %s - %s" % (apid, packetlength, SEQUENCE_FLAG_MAP[sequenceflag]) else: apid = -1 if not packetlength+2 == len(data) and packetlength+2 < len(data): # Multiple packets in buffer SavePacket(sys.argv[1], pendingpackets[apid]) del pendingpackets[apid] data = data[packetlength+2:] apid = -1 print " Multiple packets in same buffer. Repeating." else: break return apid, ""
With that we create a dictionary called pendingpackets that will store APID as the key, and another dictionary with the packet data, including a field called data that we will append data from other frames until we fill the whole packet. Back to our read function, we will have something like this:
... if not fhp == 2047: # Frame Contains a new Packet # Data was incomplete on last FHP and another packet starts here. # basically we have a buffer with data, but without an active packet # this can happen if the header was split between two frames if lastAPID == -1 and len(buff) > 0: print " Data was incomplete from last FHP. Parsing packet now" if fhp > 0: # If our First Header Pointer is bigger than 0, we still have # some data to add. buff += data[:fhp] lastAPID, data = CreatePacket(buff) if lastAPID == -1: buff = data else: buff = "" if not lastAPID == -1: # We are finishing another packet if fhp > 0: # Append the data to the last packet pendingpackets[lastAPID]["data"] += data[:fhp] # Since we have a FHP here, the packet has ended. SavePacket(sys.argv[1], pendingpackets[lastAPID]) del pendingpackets[lastAPID] # Erase the last packet data lastAPID = -1 # Try to create a new packet buff += data[fhp:] lastAPID, data = CreatePacket(buff) if lastAPID == -1: buff = data else: buff = ""
This should handle all frames that has a new header. But maybe the packet is so big that we got frames without any header (continuation packets). In this case the FHP will be 2047, and basically we have three things that can lead to that:
- The header was split between last frame end, and the current frame. FHP will be 2047 and after we append to our buffer we will have a full header to start a packet
- We just need to append the data to last packet.
- We lost some frame (or we just started) and we got a continuation packet. So we drop it.
... else: if len(buff) > 0 and lastAPID == -1: # Split Header print " Data was incomplete from last FHP. Parsing packet now" buff += data lastAPID, data = CreatePacket(buff) if lastAPID == -1: buff = data else: buff = "" elif len(buff)> 0: # This shouldn't happen, but I put a warn here if it does print " PROBLEM!" elif lastAPID == -1: # We don't have any pending packets, and we received # a continuation packet, so we drop. pass else: # We have a last packet, so we append the data. print " Appending %s bytes to %s" % (lastAPID, len(data)) pendingpackets[lastAPID]["data"] += data
Now let’s talk about the SavePacket function. I will describe some of the stuff here, but there will be also something described on the next chapter. Since the packet data can be compressed, we will need to check if the data is compressed, and if it is, we need to decompress. In this part we will not handle the decompression or the file assembler (that will need decompression).
Saving the Raw Packet
Now that we have the handler for the demuxing, we will implement the function SavePacket. It will receive two arguments, the channel id and a packetdict. The channel id will be used for saving the packets in the correct folder (separating them from other channel packets). We may have also a Fill Packet here, that has an APID of 2047. We should drop the data if the apid is 2047. Usually the fill packets are only used to increase the likely hood of the header of packet starts on the start of channel data. So it “fills” the channel data to get the header in the next packet. It does not happen very often though.
In the last step we assembled a packet dict with this structure:
{ "data": pdata, "version": version, "type": type, "apid": apid, "sequenceflag": SEQUENCE_FLAG_MAP[sequenceflag], "sequenceflag_int": sequenceflag, "packetnumber": packetnumber, "framesdropped": False, "size": packetlength }
The data field have the data we need to save, the type says the type of packet (and also if its compressed), the sequenceflag says if the packet is:
- 0 => Continued Segment, if this packet belongs to a file that has been already started.
- 1 => First Segment, if this packet contains the start of the file
- 2 => Last Segment, if this packet contains the end of the file
- 3 => Single Data, if this packet contains the whole file
It also contains a packetnumber that we can use to check if we skip any packet (or lose).
The size parameter is the length of data field – 2 bytes. The two last bytes is the CRC of the packet. The CCSDS only specify the polynomial for the CRC, CRC-CCITT standard. I made a very small function based on a few C functions I found over the internet:
def CalcCRC(data): lsb = 0xFF msb = 0xFF for c in data: x = ord(c) ^ msb x ^= (x >> 4) msb = (lsb ^ (x >> 3) ^ (x << 4)) & 255 lsb = (x ^ (x << 5)) & 255 return (msb << 8) + lsb def CheckCRC(data, crc): c = CalcCRC(data) if not c == crc: print " Expected: %s Found %s" %(hex(crc), hex(c)) return c == crc
On SavePacket function we should check the CRC to see if any data was corrupted or if we did any mistake. So we just check the CRC and then save the packet to a file (at least for now):
EXPORTCORRUPT = False def SavePacket(channelid, packet): global totalCRCErrors global totalSavedPackets global tsize global isCompressed global pixels global startnum global endnum try: os.mkdir("channels/%s" %channelid) except: pass if packet["apid"] == 2047: print " Fill Packet. Skipping" return datasize = len(packet["data"]) if not datasize - 2 == packet["size"]: # CRC is the latest 2 bytes of the payload print " WARNING: Packet Size does not match! Expected %s Found: %s" %(packet["size"], len(packet["data"])) if datasize - 2 > packet["size"]: datasize = packet["size"] + 2 print " WARNING: Trimming data to %s" % datasize data = packet["data"][:datasize-2] if packet["sequenceflag_int"] == 1: print "Starting packet %s_%s_%s.lrit" % (packet["apid"], packet["version"], packet["packetnumber"]) startnum = packet["packetnumber"] if packet["framesdropped"]: print " WARNING: Some frames has been droped for this packet." filename = "channels/%s/%s_%s_%s.lrit" % (channelid, packet["apid"], packet["version"], packet["packetnumber"]) print "- Saving packet to %s" %filename crc = packet["data"][datasize-2:datasize] if len(crc) == 2: crc = struct.unpack(">H", crc)[0] crc = CheckCRC(data, crc) else: crc = False if not crc: print " WARNING: CRC does not match!" totalCRCErrors += 1 if crc or (EXPORTCORRUPT and not crc): f = open(filename, "wb") f.write(data) f.close() totalSavedPackets += 1 else: print " Corrupted frame, skipping..."
With that you should be able to see a lot of files being out of your channel, each one being a packet. If you get the first packet (with the sequenceflag = 1), you will also have the Transport Layer header that contains the decompressed file size, and file number. We will handle the decompression and lrit file composition in next chapter. You can check the final code here: | https://www.teske.net.br/lucas/2016/11/goes-satellite-hunt-part-4-packet-demuxer/ | CC-MAIN-2019-18 | refinedweb | 3,158 | 62.92 |
GAVO DaCHS Tutorial¶
Contents
- GAVO DaCHS Tutorial
- Invoking DaCHS
- Building a Catalog Service
- Introduction to DaCHS Publishing
- More on Grammars
- More on Tables
- More on Services
- More on Cores
- More on Metadata
- Active Tags
- Some Words on Times
- Publishing DAL Services
- Writing Examples
- Services Over Views
- The Registry Interface
- Restricting Access
This tutorial intends to guide you through ingestion of data and setting up of services. Even if you plan to only publish images or spectra, you should work through the first part; it explains a lot about DaCHS’ central concept, the resource descriptor (RD), recommended directory layouts, the basics of metadata and services, and debugging.
Invoking DaCHS¶
Note: Before version 1.0 (planned release July 2017), dachs had to
be called as
gavo. While this will still be possible during the 1.0
series for DaCHS, we recommend using
dachs as the entry point. This
tutorial and other examples are migrating towards the new command name,
so: If you’re running DaCHS <1.0, you’ll have to write
gavo when
there’s either “gavo” or “dachs” in DaCHS documentation, newer
installations should just use
dachs.
All DaCHS functionality is invoked through a
program called
dachs. Multiple functions are integrated and selected
through the first argument; run
dachs help to see what’s available;
realistically, the functions most operators will be confronted with are
start,
import,
serve,
publish, and
test. Also make sure you at
least once skim the man page.
DaCHS has some global options (that go in front of the subcommand name). Most subcommands take options and/or arguments, which then have to be after the subcommand name.
Most of DaCHS’s global options have to do with debugging; it is sometimes useful go say:
dachs --ui stingy ...
to reduce the program’s chattiness.
For a brief overview what the individual functions are, see the man page or use the built-in help, as in:
$ dachs limits --help usage: dachs limits [-h] itemId Updates existing values min/max items in a referenced table or RD. positional arguments: itemId Cross-RD reference of a table or RD to update, as in ds/q or ds/q#mytable; only RDs in inputsDir can be updated. optional arguments: -h, --help show this help message and exit
Building a Catalog Service¶
Quick start¶
To do anything useful with DaCHS, you will have to write a resource descriptor (RD), and you’ll probably have to have some data. Both must reside within some subdirectory of DaCHS’ input directory (unless you configured otherwise, that’s /var/gavo/inputs; we assume that in the following).
Since both astronomical data and VO services tend to be complex, you can do a lot of things in an RD. However, the publication of a certain data type (e.g., catalogue, spectra or image collection) often follows a pattern. DaCHS comes with a library of such patterns, and when starting a service, you will usually do something like:
cd /var/gavo/inputs mkdir <collection-name> cd <collection-name> dachs start <data-type-tag>
To see something quickly, however, we will look at an existing data set first, a catalog called ARIHIP catalog – this is a re-reduction of the Hipparcos result catalog with particularly careful solutions for proper motion. It has a column-based input and probably a few more columns than your average catalog these days. It hence is simple in principle but let us demonstrate a few advanced concepts, too.
You can run the following under any user id, as long as
you wisely manage the permissions. For testing, however, we recommend
doing it as the data center administrative account (for the Debian
package, that’s gavoadmin, and short. The directory created here is ususally called the resource directory in DaCHS lingo.
The resource descriptor name also appears in URLs. At GAVO’s data
center, we usually call it
q.rd as that looks nicely query-ish (to
our tastes).
Next, get the raw data. We recommend keeping data in a subdirectory of
resource directory (and suggest to call that subdirectory
data). At
the GAVO DC we usually keep everything in the resource directory under
version control except for that data directory (which tends to be large,
full of binary files, and either versioned by upstream or not at all):
mkdir data cd data curl -O
At this point, we’re ready for ingestion. All commands to DaCHS go
through the
dachs program that has several sub-commands; in this
case, we need the
import sub-command. The sub-commands can be
abbreviated as long as the abbreviation is unambiguous:
cd .. dachs imp q
This should run for a while, reporting the number of ingested rows now and then, and finally say something like “Rows affected: XY”. With this, the data is in the database and is ready for querying.
Let us mention in passing that
dachs imp tries to interpret its first
argument first as a file system path. If that fails, it tries to
interpret it as an RD identifier, i.e., the inputsDir-relative path of
the RD with the extension stripped. Our example RD thus has the RD id
arihip/q, and you could have said:
dachs imp arihip/q
from anywhere in the file system.
After you have imported a table, it is a good idea to run
dachs info
with the DaCHS identifier of the freshly imported table, e.g.,:
dachs info arihip/q#main
The DaCHS identifier of the table consists of the RD id as introduced above, the hash (inspired by the URL fragment identifier), and the id of the table.
This will output several properties (min, max, avg) of numeric columns that may help spot import errors. Also note that for each column, the presence of NULLs is given. When you import data, it is a good idea to check whether these correspond to your expectations, and to consider declaring columns as required when they do not indeed contain NULLs.).
The RD sets up a form-based service you can operate from a web browser; open the URL [1] and play around a bit. Note the small links behind some query fields – DaCHS supports VizieR-like expressions in those fields.
Briefly have a look at the URL; apart from the host name and port (see
the operator’s guide on how to change those), there is the path to the
RD (without the file extension), then the id of the service element (see
below) and a “renderer name”. That essentially defines the physical
interface of the service, i.e., which protocol it is accessed through.
In this case, it’s
form for an HTML form.
Another renderer supported by this service is
scs.xml, which
implements the IVOA Simple Cone Search (SCS) protocol. A client that supports
this is TOPCAT; to try it out, in TOPCAT select VO/Cone Search and fill
out the Cone URL field in the lower part of the window to be. Enter some object name
and a sufficiently large search radius (e.g., Aldebaran and 0.5
degrees), and you’ll see the results coming in.
Incidentally, cone search does not (yet) have a usable interface to
discover additional parameters, and hence TOPCAT restricts you to those
mandatory for every SCS service. For instance, as delivered, arihip
admits an
mv parameter. DaCHS supports a special syntax for
“free” parameters of cone searches as defined by the spectral access
protocol SSAP; to say ”everything brighter than 6th magnitude”, the
parameter setting would be
/6; to use this constraint within TOPCAT,
the access URL needs to be amended like this:.
Finally, the RD opens the arihip table for the IVOA Table Access
Protocol TAP, which
The anatomy of the RD¶
Now have a look at the RD by bringing up q.rd in your favourite editor. It starts out with:
<resource schema="arihip">
RDs are normal XML files (meaning that you could, e.g., add an XML declaration if you want an encoding other than utf-8), and thus they need a root element. Hopefully unsurprisingly, this is called resource for RDs. DaCHS typically does not distinguish attributes and elements with atomic content, which means that you could also have written the fragment above as:
<resource> <schema>arihip</schema>
This notational freedom sometimes allows clearer notation, and it helps with defining active tags. Multiple specifications of the same property make up multiple values where the property is sequence-like (in the reference documentation this is indicated by phrases like “zero or more” or “list of” in the properties descriptions). For atomic properties, later specifications overwrite earlier ones.
The
schema attribute on resource gives the (database) schema that
tables for this resource will turn up in. You should, in general, use
the name of the resource directory here. If you don’t, you have to give
the subdirectory name in the resource element’s
resdir attribute –
either way, this is then used to build absolute paths within the RD,
e.g., for the sources element discussed below.
In general, you should have exactly one RD per database schema. This is not enforced, but sharing schemata between RDs will cause many undesirable behaviours. (which could, in this case, fixed by adding untrusted to B’s readRoles manually, but you get the idea).
Another hint: There’s a fairly large body of RDs at, and most of them are free for inspection and blatant stealing (if you need a license on any of this, let us know). These RDs can be seen live on. To locate examples for concrete elements, meta items, and such, have a look at our RD element reference for these."> <meta name="profile">AllSky ICRS</meta> <meta name="waveband">Optical</meta> </meta> <STREAM source="//procs#license-cc-by" what="ARIHIP"/> <meta name="_longdoc" format="rst"> The ARIHIP Catalogue is a suitable combination of the results of the HIPPARCOS astrometry satellite with ground-based data. (abridged) </meta> <meta name="source"> Veröff. Astron. Rechen-Inst. No. 40 (2001); </meta> <meta name="_intro" format="rst"> <![CDATA[ For advanced queries on this catalogue use ADQL_ possibly via TAP_ .. _ADQL: /adql .. _TAP: /tap ]]> </meta>
This metadata is cruicial for later registration of the service, and some of it turns up in service responses. If you have a look at the HTML form you opened above, you will find quite a bit of it in the sidebar.
Metadata elements have a
name attribute that gives the “kind” of
metadata contained, and sometimes also determine a specific type.
Metadata can be hierarchical, where hierarchy elements are separated by
dots, and metadata can come in various formats as determined by the
format attribute. If you give nothing here, DaCHS will apply some
whitespace normalization, and it will interpret empty lines as
paragraphs if the target format supports it. With
format="rst", the
content will be interpreted as reStructuredText. Be careful to use
consistent indenation in this case. There are some other, more obscure,
formats, too, that you do not need to worry about right now.
See More on Metadata for more information on what is what here.
A special thing in two respects is the STREAM in the above fragment.
For one, it’s an example of DaCHS metaprogramming, which we’ll later
look into. For now, suffice it to say that this element sets a number
of metadata items (actually, rights, rights.rightsURI, and copyright)
and thus puts your data under a definite license. This may seem a bit
legalistic, but see Licensing on why it’s nevertheless a good idea to
include, if you can, either license-cc-by or license-cc0 in the above
pattern. Just adapt the value of the
what attribute to a few-word
phrase making it clear what the object of the license is.
Defining Tables¶
A major part of the metadata DaCHS deals with is the table structure. It is defined in table elements, which usually are direct children of the resoource element. A resource element may contain multiple table definitions. See for what upstream documentation we had when we made the service..
Be sure to always specify
onDisk="True" unless you’re going for
special effects – without it, the table will end up only in memory.
The
adql attribute says that TAP queries should be allowed on the
table; leave it out for tables not suitable for “raw” consumption by your
clients.
For the
mixin attribute, see Indices and Mixins.. This is again a topic of its own, discussed in STC
Column definition¶
Finally, we’re at the column definitions:
ending up in the table, there is one column element
with a host of attributes. The
name attribute is
central in that it will be the column name in the database
(incidentally, it’s not
id as with tables as it is quite common for
different tables in one RD to have columns with the same name, and that
would violate the id attribute’s uniqueness constraint), the key for
the column’s value in record dictionaries that the software uses
internally, and it is usually used to reference the column from the
outside.. The DC software knows how to handle
text– a string. You could also use types with explicit length like char(7), but this is highly discouraged; it does not help postgres (or much anything else within the DC), but it hurts insofar as DaCHS cannot produce NULLs for such constructs in most VOTable serialisations.
char– a character, typically used in arrays. If using single flags, these might make sense (though you’ll usually have to manually give a null literal then). Don’t do
char(*),
varchar(*), or any mogrification with actual lengths, though. It doesn’t help postgres but might give headache later.
real– a real number.
double precision– a floating point number. You should use in.
date– a date. See timestamp.
time– a time. See timestamp
box– a rectangle.
spoint,
scircle,
sbox,
spoly– objects of spherical geometry, taken from pgSphere. Ask for documentation….
tablehead– a very short string designating the content. This string is typically used for display purposes, e.g., as table headings or labels on input fields and defaults to the capitalized column name.
description– a longer string characterizing the content. This may be in bubble help Notes. An example for a long descripton:
<column name="aperture"> <description>The aperture is the full-width-half-mean) that may have null values. (see above) can help you to choose suitable
NULL values. To help people spot them when metadata is missing, it’s
usually wise to choose “conspicuous” null values (like -1, 9999, or
similar).
Table elements may contain metadata. You do not need to repeat metadata
given for the resource, because (in most cases) the DC performs metadata
inheritance. This means that if a table is asked for a piece of
metadata it does not have, it forwards that request to the embedding
resource. For multi-table resources, you should usually give
title
and
description metas.
Scrolling a bit further down in the arihip RD, you’ll notice some LOOP constructs. These are discussed below under active tags.
At the end of the table element, there are meta elements called “note”; for those, see can have ids which can be used to indiviually.
The sources element.
Now have a look at the input file:
zless data/data.txt.gz
You’ll see that we have a plain ASCII file with aligned columns, header lines, and even a cell separator (“|”). That’s still a fairly common format for raw data, but by no means the only one. To give DaCHS the flexibility to deal with anything upstream cares to throw at you, DaCHS has the concept of a grammar.
There are many grammars defined, e.g., for getting values from FITS files, VOTables, or using column-based formats; you can also write specialized grammars in python. All grammars read “something” and emit a mapping from names to (mostly) string values; those unprocessed string-to-string mappings are called “rawdicts” in DaCHS jargon (distinguished from “rowdicts” ready for database ingestion, which sport processed and typed data).
It is often useful to inspect what a grammar emits. You can do that
using import’s
--dump flag. During development, it is frequently
convenient to just import a few rows and watch what they produce; this
would look like this:
dachs imp -M 100 --dump q.rd | less
(if you interrrupt the above command, your table should be unscathed –
check with
dachs info –; otherwise just re-run the full import).
With a source that has both a separator character and aligned columns, there are several valid choice for which grammar to use on this particular file. In the RD, it next says:
<columnGrammar topIgnoredLines="9" preFilter="zcat"> <colDefs> hipno: 3-8 srcSel: 47-49 alphaHMS: 59-73 deltaDMS: 77-91 pmra_mas: 95-103 pmde_mas: 107-115 t_ra_mod: 119-123 err_ra_mas:127-131 err_pmra_mas:135-139 t_de_mod: 143-147 err_de_mas:151-155 err_pmde_mas:159-163 parallax_mas:167-172 e_parallax_mas:176-180 kp: 184 vrad: 188-195 mv: 199-203 km: 207 kbin: 211-212 kdmu: 216 kae: 220 flags: 882-901 </colDefs>
– so we went for Element columngrammar. Those cut up every input line along character indices that are here, following the display in most editors, are counted from 1 upwards. Note that in ranges, the last column is included in the string – these are no python slices but basically a representation of the character ranges in VizieR-style “byte-by-byte”-descriptions.
The assignment of names to column ranges can happen both in a
colDefs element as shown above – one specification per line, label
mapped to a column or a range of columns.
Alternatively, have several
col elements, each of which has a
key
attribute that gives a name. This could be the
name of a target
column in the simplest case, or it can be an auxillary identifier that
is later processed in a rowmaker. These individual specifications are
interesting when combined with RD macros, and that’s where they come in
in the arihip RD (again, using LOOPs).
Grammars also have various attributes; the ones parsing from text files
support, for example,
topIgnoredLines, which allows you to skip
header lines, and
preFilter that allows running the input through
a shell command before it is processed using DaCHS (if you find yourself
doing more than just decompression in such a preFilter, you should
probably look for a different solution). make element brings together a table (in the
table
attribute) with a recipe how to fill it from the output of the grammar
(the row maker).
Incidentally, there can be multiple
make elements in a single
data element if multiple tables (using different row makers) are
generated from the same grammar output. This is particularly useful in
combination with dispatching grammars that let, in effect, the
grammar choose which make to use.
Makes can also carry scripts in SQL or python, at various points of the building process. These let you perform all kinds of higher magic. For details, see the chapter on scripting in the reference.
As explained above,). To cover these and more tasks, DaCHS has row makers, the results of which are then called rowdicts (note the subtle difference from the rawdicts coming in from the grammars: “row makers turn rawdicts into rowdicts”).
Basically a row maker consists of
- var elements – assignments of expression values names in the rawdict.
- map elements – simple mappings of (python) expressions to values in the destination rowdict
- procedure applications (see apply) – manipulations of both rawdicts and rowdicts in python code
The fragment above shows one of several ways to use both
var and
map (which work exactly the same way, except that vars end up in the
rawdict, and map in the rowdict): generating values from python
expressions, where there is the special syntax
@identifier which
expands to whatever value the rawdict has for that key (or raises a
KeyError if the key is not present in the rawdict).
The rawdict manipulations that
var does are useful if you want to
re-use whatever you compute. The
map element, on the other hand,
writes directly into the results dictionary, the keys of which directly
correspond to the column names.
When building a rowdict for ingestion into the database, a row maker first
binds var names, then applies procedures and finally performs the mappings.
In the bodies of the mappings, you can use all built-in python
functions plus a set of useful rowmaker functions documented in the
reference documentation, as well as everything from the python standard
library modules
datetime,
math,
os,
re,
sys,
time, and
urllib . TODO: link to useful documentation for them here.
For simple cases, maps will suffice; frequently, you can do without
python expressions by giving a
src attribute specifying a rawdict
key instead of element content (which is preferable if possible – as
elsewhere, less code is better in RDs, too). The rawdict string will in
this case be converted to a typed value using “sane” defaults </simplemaps> </rowmaker> in general controls both) that there is yet another shortcut for this:
<rowmaker> <idmaps>evi,av,ai</idmaps> </rowmaker>; due to the rounding errors when converting from decimal to binary floating points, you can only safely compare against relatively few floating point numbers (99.99 is not among them), so you shouldn’t do that if you can avoid it.
If you need to scale this (or if null values are chosen that they are
invalid literals to begin with), a feature that lets you null out a
value when an specific type of exception is raised comes in handy.
This is map’s
nullExcs attribute, which is just a comma separated list of
exceptions that should be caught and interpreted as “this is null”. If,
in the example above, the source would give the magnitude in millimags
to save a comma,.
We defer the discussion of
apply elements to the discussion of how
to build SIAP services.
rowmaker elements may also be direct children of
resource; this
is for when they are used in more than one
data. You would then give
the rowmaker an
id attribute and say something like
<make
rowmaker="id-of-rowmaker" table=.../> However, for the standard case
it’s best to keep everything related to a given import together in the
make element.
Indices and Mixins¶
We have so far deferred the discussion of the
mixin attribute in
arihip’s opening table element:
<table id="main" onDisk="True" adql="True" mixin="//scs#q3cindex" primary="hipno"> table containing information on all the
file-like datasets in the data center (which is called
dc.products)
is updated when the table is filled.
The content of the mixin element (or the attribute value when you give
the mixin property as an attribute) is a reference to a mixin
definition. These references typically go into some system descriptor
(though you could define your own mixins), and the double slash in a
DaCHS reference means “system descriptor” (in actual truth, it’s just an
abbreviation for
__system__/). The reference documentation contains
a chapter on DaCHS’ public mixins. For the curious: you can have a
look at the actual definitions by admin’s
dumpDF subcommand, e.g.,
like this:
dachs admin dumpDF //scs
The
//scs#q3cindex mixin referenced here arranges for spatial
indexing of tables having some sort of spherical coordinates.
To identify which columns to index, DaCHS inspects the UCDs of the
columns; what it looks for here are columns with UCDs of
pos.eq.(ra|dec);meta.main` as index columns. Contrary
to mixins for other standard protocols, it does not automatically insert
these columns (and neither the only other required column in SCS, the
main row identifier with the UCD
meta.id;meta.main).
Since in addition to spatial queries, we also expect a lot of queries
constraining the
mv column, we ask for an index on it using DaCHS’
index element, which is a child of
table:
<index columns="mv"/>
This is the simplest, but mostly sufficient, form of defining an index;
for advanced usage, please refer to the reference documentation. If
you decide to add an index to a table later on, or to initiate
re-indexing after a lot of data changed, see the
-I option of
gavo
imp.
The
pos.eq UCDs in the SCS
condDescs are hardcoded; this is
because the standard simple cone search protocol specifies that the
coordinates passed in are ICRS, and hence other systems – galactic, say
– make little sense here. Also, the web form-variants of the protocols
let users enter Simbad-resolvable identifiers rather than positions. In
sum, making these things generic for other systems would be an
unreasonable implementation effort.
If you want to allow queryies in other systems, just write the index
statement inline, e.g., for galactic coordinates in the columns
lambda,
beta:
<index name="q3c_gal" cluster="True" columns="lambda,beta" >q3c_ang2ipix(lambda,beta)</index>
A simple condDesc that searches using this index could be:
<condDesc> <inputKey original="lambda" required="True"/> <inputKey original="beta" required="True"/> <inputKey name="sr" tablehead="Search Radius"> <values default="0.001"/> </inputKey> <phraseMaker> yield q3c_radial_query(lambda, beta, %%(%s)s, " "%%(%s)s, %%(%s)s)")%( base.getSQLKey("lambda", inPars["lambda"], outPars), base.getSQLKey("beta", inPars["beta"], outPars), base.getSQLKey("sr", inPars["sr"], outPars)) </phraseMaker> </condDesc>
Cores and Services actually do the computation or database query
- renderers; these digest the data coming in from the service and (in general) format the result in some way requested by the user. There are renderers for web forms, VO protocols, imges, etc. Frequently – as in the example –, you can use the same core for both a VO protocol and a form-based service by just allowing different renderers.
- The service; it holds together the core and the renderer, can reformat core results, controls the metadata, etc.
The renderers are referenced by name in the service’s
allowed
attribute. What can be given there (concatenated by commas) is listed
in the reference documentation’s renderer chapter. As you have seen
above, the renderer is selected via the URL. If a client tries to
retrieve a URL with a renderer that is not in the service’s
allowed
list, DaCHS will respond with a 403 forbidden HTTP code (excepting
certain “unchecked” renderers like
info that typically expose
service metadata). In addition, not all cores can be combined with all
renderers even if you list them in
allowed. For example, the
ssap.xml renderer will not (usefully) work on anything but an
ssapCore.
The most common core for catalog services (and the one you’ll typically use for SCS services) is the dbCore, as used here. See cores available in the reference documentation for more predefined cores – e.g., to run ADQL queries or to upload files. For special functionality, you can even write your own core.
The dbCore generates a (single-table) query from condition descriptors
and returns a table that you describe through an output table. Cores
are defined as direct children of the resource (as with grammars, you
can also have them in
resource and then write
core="id-of-element", which makes sense when a single core is shared
by several services).
dbCores need a
queriedTable attribute, the value of which must be a
table reference. This is the table the query will run against.
The condition descriptors (or condDescs for short) define input fields
locates the “main”
positions as identified by UCDs and generates queries against them using
two input fields, one it tries to guess a position from, and another for
the search radius.
When you define a
condDesc using
buildFrom, the result is
usually one or more input field(s) constraining values in the column
named in the
buildFrom attribute. The software tries to make some
useful input definition from that column, depending on the renderer.
Renderers with a parameter style (this is given in each renderer’s
description the reference documentation) of “form”, for example, let
users query string-like columns using Vizier-like string expressions,
real and double precision columns using Vizier-like float expressions,
and so on. The
pql style allows a specification like for SSAP
(e.g., “range_min/range_max”).
The
service element must have an
id attribute that is used to
select the service run in the access URL. Furthermore, there should be
certain pieces of metadata useful in later registration., in which
case one could be “Cone search for ARI’s HIPPARCOS re-reduction” and the
other, say, “Autocorrelation on ARI’s HIPPARCOS re-reduction”.
See data_checklist.html for more information on useful generic
metadata and remember that services inherit whatever is defined within
resource when not specified within the element.
Many standard VO protocols require additional, protocol-specific metadata. In the case of arihip, we have a Simple Cone Search service, which, as laid down in the section on the scs.xml renderer in the reference documentation, requires the parameters of a test query returning a nonempty result.
Introduction to DaCHS Publishing¶
Starting from Scratch¶
When you get a new data collection in, it might be a good idea to check the GAVO data center’s service roster if there’s anything similar there and then see if starting from the corresponding RD in our RD repository.
The standard way (and that’s what we almost always do), however, is to
use
dachs start. To use it, create your resource directory, change
into it and give build a q.rd template by running
dachs start
<proto>. For instance, when you have a catalog).
After that, you have a file called q.rd in the current directory. This would be the perfect time to check it into your version control (you have one, don’t you?).
Next, bring in (a sample of) your data (recommended: in the data subdirectory).
And then the actual work begins: Filling in the global metadata, the
table structure, the ingestion rules, service metadata, and regression
tests. Where possible, the templates are written such that when you
have filled out everything
%between percent signs%, you should have a
very basic (possibly usesless) service. The envisioned workflow is
that you go through the file pattern by pattern.).
If you’ve followed the chapter on Building a catalog service above, not much of what you’ll be seeing should surprise you. If you’re wondering about a particular thing, you can always refer to the RD element reference to see how it’s used in our data center, or go to the reference documentation. Also, please give us hints if you see a way to make the material more helpful. – may commonly encountered problems
gavoand
gavo.
If you’re trying to figure out server behaviour, don’t run the server daemonized but use
dachs serve debuginstead; this won’t detach and log to stdout.
With this (or the problem is in normally-running DaCHS code in the first place), the python debugger is your friend. The
gavocommand. If you install the python-ipdb package, and write ipdb instead of pdb, you’ll get a nicer debugger commandline with tab completion and similar frills.
To see what SQL is actually sent to the database, set the GAVO_SQL_DEBUG environment variable to any value. This could look like this:
env GAVO_SQL_DEBUG=1 dachs imp q create
The first couple of requests are for internal use (like checking that some meta tables are present).
If
dachs serve startdoesn’t actually cause the server to run, something went wrong after detaching from the controlling terminal. The messages are in the logs directory, in the file
serverStderr.
do the
import pdb;pdb.set_trace() trick then. It’s a bit tricky to
communicate with the debugger in between the log messages of
gavo
serve debug, and there’s no readline support since pdb doesn’t think
it’s running within a terminal there, but it’s definitely doable.
Another challenge is that sometimes problems manifest themselves in a
running server. In that case it’s sometimes useful to open a manhole
into the server. One reasonably convenient way to do this is to but a
special RD somewhere (e.g.,
__tests/manhole.rd) and use some
RD-embedded code to introspect the server. We ususally use a datalink
service for this since it keeps things nicely self-contained – an
obvious alternative with less bending could be a custom renderer.
Here’s how something that fiddles out a column property would look like:
<resource schema="test"> <service id="look" allowed="dlget"> <datalinkCore> <descriptorGenerator> <code> return ProductDescriptor(None, None, None, 'text/plain', ) </code> </descriptorGenerator> <dataFunction> <code> descriptor.data = "debugging" </code> </dataFunction> <dataFormatter> <code> class DebugResult(Page): def renderHTTP(self, ctx): request = IRequest(ctx) request.setHeader("content-type", "text/plain") return "%s"%base.caches.getRD("maidanak/res/rawframes" ).getById("rawframes").getColumnByName("accref").displayHint return DebugResult() </code> </dataFormatter> </datalinkCore> </service> </resource>
All but the data formatter is just blind code for hiding our true
intentions from the datalink machinery. In the data formatter, you can
return arbitrary text. You can now access and see
whatever gets returned from
renderHTTP (the value of ID
obviously is arbitrary here, although you could use it to transmit
information into your debugging code; not that we think that’s a good
idea). samples., which we’ve not covered
so far). check out the indicated line, you’ll see some table markup. Now that you’re warned, you’ll probably see immediately that there’s a less-than sign there that’s not allowed in XML parsed character data, but while writing up such material, it’s easy to forget that < and & are magic to XML. CDATA is your fried for embedded formal languages.
Now for a particularly nasty syntax error that’re mixing blanks with tabs for indentation. Don’t do this in python, don’t do this in RDs.
All this means that RDs can break of XML processing tools normalize whitespace in certain elements. This is a bit unfortunate since the way RDs are written, they import Starting /home/msdemlei/gavo/inputs/arihip/data/data.txt.gz Failed /home/msdemlei/gavo/inputs/arihip/data/data.txt.gz *** Error: Row {u'pmdeLTP': None, u'srcSel': 'T2H', u'err_raHIP': [abridged] .. .... ... ...', u'ddeLTP': '- 2.37', u'pmra_mas': '- 4.85', u'raHIP': None} Field kbin: While building kbin in None: name 'parsWithNull' is not defined
The dump of the rawdict, however, is often helpful enough to warrant the
scary appearance, even at the risk of obscuring the actual message at
the very end. Note that the “while building kbin” tells you where in
the rowmaker something went wrong: At the mapping of kbin. The
in
None part may be a bit less fortunate – the “None” here is the id of
the rowmaker, which you didn’t give. If you have multiple rowmakers in
an RD, it’s a good idea to name them. So, add an
id attribute as
in:
<make table="main"> <rowmaker idmaps="*" id="make_main_row">
and to the improvement in the error message:. For DaCHS, it’s normally no problem if a key is
missing in the input 1 *** Error: Row {u'pmdeLTP': None, u'srcSel': 'T2H', u'err_raHIP': [...] u'ddeLTP': '- 2.37', u'pmra_mas': '- 4.85', u'raHIP': None} Field vrad: While building vrad in None: Key 'vrad' not found in a mapping.
When debugging stuff like this, it is sometimes useful to cut-and-paste
the rawdict dumped into a file, join all the lines, remove the
parser_ key-value pair (the content of which cannot be represented
as a string), assign it to a name and then manipulate it in the rest of
the file using python statements. You can have a similar effect by
giving
--enable-pdb as a
gavo main option; this will dump you in
a debugger at the place of the problem.
Undo all changes to the arihip RD to continue.
If you embed code yourself, the potential for challenging bugs is yet larger. To see how basic problems are reported, add:
<apply> <code> ddt </code> </apply>
somewhere within the RD. This yields:
arihip > dachs imp q [...] u'raHIP': None} Field proc98577cc: While executing proc98577cc in None: global name 'ddt' is not defined
The message coming from the bowels of python is clear enough, but the
alphabet soup giving the error is not. This name was invented by DaCHS
since no
name (sorry, not id this time) gav.
More on Grammars¶
In addition to the
columnGrammar mentioned above, there are several
other grammars you should know about; the full list of grammars
available is found in the reference documentation.
reGrammars¶
The reGrammar is another grammar suitable for parsing text files. The idea here is that you give two regular expressions to separate the file into records and the records into fields, and that you simply enumerate the names used in the mapping.
In the simplest case – whitespace separated columns in lines containing>
If things get noticeably more complex than this, an reGrammar may no longer be a terribly good solution. Indeed, we would welcome a contributed grammar that would do a somewhat more robust parsing of common SQL text dumps.
fitsProdGrammar¶
This grammar exposes FITS headers as rawdicts. Since both data structures represent essentially the same data structure – sequences of key-value pairs, you can get away with just:
<fitsProdGrammar/>
– and that would cover a lot of use cases that read FITS files. specialized.
It is fairly common for FITS keywords to contain a dash (
-). Since
rawdict keys are supposed to be python identifier (e.g., for
@-referencing), fitsProdGrammars translate these to underscores. If
further cleanup is necessary, there is the mapKeys element that lets you
write things like:
<mapKeys> <map key="properName">PROP NAM</map> </mapKeys>
The element should only be used to fix crazy names. Actual mapping of names should be performed in rowmakers.
FITS files are somewhat more complex, and fitsProdGrammars expose some
of this. If you need to parse from a header other than the primary one,
give the 0-base extension number in hdu., incientally, supported if
their file names end in “.gz”).
csvGrammar). It is currently required, though, that the first row gives the column headings. If you need the capability to name fields as in, say, the reGrammar, let us know – it’s just a few lines of code.
Source Fields¶
All grammars can have a
sourceFields element..
The purpose of sourceFields is to precompute values that depend on the source (“file”) and are constant for all rows within it. An example for where you need this is when you want to create backlinks to the file a piece of data came from:
<xygrammar> <sourceFields> <code> srcKey = utils.getRelativePath(sourceToken, base.getConfig("inputsDir")) return locals() </code> </sourceFields> </xygrammar>
You can then retrieve the path to the source file via srcKey key in rawdicts (and then, using render functions and static renderers, turn this into links).
In addition to the sourceToken, you also have access to the data that
will be fed from the grammar. This can be used to, e.g., retrieve the
resource directory (
data.dd.rd.resdir) or data descriptor properties
(
data.dd.getProperty("whatever")).
Sometimes you want to do database queries from within sourceFields. This is tricky when you access the table being written or otherwise being accessed. This is because sourceTokens run in the midst of a transaction updating the table. So, something like:
<code> <!-- will deadlock, don't do it like this --> base.SimpleQuerier().query(...) </code>
will wait for the transaction to finish. But the transaction is waiting for data that will only come when the query finishes – this is a deadlock, and dachs imp will just sit there and wait (see also Deadlocks).
To get around this, you need to query using the data’s connection. So, instead write:
<code> base.SimpleQuerier(connection=data.connection).query(...) </code>
More on Tables¶
Notes¶
Frequently, you need to say more about a column than is appropriate in the few-phrase description. In catalog exposed.
STC¶
As soon as you have coordinates, you will want to declare coordinate metadata on them, i.e., reference frames, roles played by tables (x is the derivative of y, and x1 is a galactic latitude, etc). In VO lingo, this is known as declaring “space-time coordinates” or STC for short.
DaCHS uses a language called STC-S to do this. The STC-S definition currently only exists as a note and is both a bit terse and not quite as rigorous as one would wish, but the good news is that you will get by with but a few features most of the time.
STC is defined in children of table elements, with references to table columns in quoted strings:
<table id="withcoo"> <stc> Position ICRS "ra" "dec" Error "e_ra" "e_dec" </stc> <stc> Position FK4 J1950.0 "ra_orig" "dec_orig" </stc> <column name="ra" unit=... <column name="dec" ... ... </table>
You do not need to change anything in the column definitions themselves, since the machinery will resolve your column references. If you refer to non-existing columns, RD parse errors will be thrown.
More on Services¶
Custom Templates¶
Within the data center, most pages are generated from templates; these are written in XHTML (well-formed XML is important, DaCHS itself does not care avout valid XHTML, though) with stan/nevow markup. Please bug us to provide more documentation on this.
The pages the form renderer on services displays are generated from such templates, too. To effect special effects, you may want to override them (though in general, it is a much better idea to work within the standard template since that will give your service all kind of automatic updates and would make, e.g., changes much easier if your institution undergoes the yearly reorganization).
You can retrieve the default response template as something to start from by saying:
dachs admin dumpDF templates/defaultsresponse.html
To obtain the plainest output conceivable, try:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ""> <html mlns="" xmlns: <head> <title>No title</title> </head> <body> <div class="result" n: <div class="result"> <n:invisible n: </div> </div> <n:invisible n: </body> </html>
Save this to a file within the resource directory, let’s say “res/plain.html”. Then, say:
<template key="form">res/plain.html</template>
in your service; this should do give you a minimally decorated page.
Of course, this will display a severely degraded page. To get at least the standard style sheet and the standard javascript, say:
<head n:
instead of the plain head.
Values Metadata¶
For input parameters, it’s usually a good idea to indicate to users what
the valid range for them might be. When you give
values elements in
your tables’ columns, DaCHS will have placeholders in floating point and
integer fields in web forms and appropriate VOTable values elements in
the metadata responses for DAL protocols. So, essentially:
<column ...> <values min="-1.0" max="2.0/> </column>
would be enough. However, maintaining these min and max values is a bit
of a chore. On the other hand, obtaining them from the database can be
costly, and hence it shouldn’t be done at each server start. Hence,
DaCHS has a subcommand
limits that takes an RD or table id as the
command line argument and replaces the existing min/max values in the
referenced thing with data obtained from the database. So, the
recommended way to do these things is to stereotypically add
<values
min="0" max="0"/> in columns that generate query parameters and then
run either of:
dachs limits arihip/q # update all tables present dachs limits arihip/q#main # only update the single table
after an import giving new data.
More on Cores¶
CondDescs¶
dbCores and cores derived from them take most of their power from condition descriptors or CondDescs. These combine inputKeys, which are basically column objects with some additional presentation-related information, with code generating SQL conditions.
A condDesc can contain zero or more input keys (though having zero input keys makes no sense for user-defined condDescs since they would never “fire”). Having more than one input key is useful when input quantities can only be interpreted when present as a group. An example is the standard cone search, where you need both a position and a search radius.
Automatic and manual control¶
However, most condDescs correspond to one input key, and the input key is mostly derived from a table column. This is effected by the standard idiom:
<condDesc buildFrom="somecol"/>
where somecol is a column in the table queried by the core. This construct will cause the an input key to be built from somecol. While doing this, the type will be mapped automatically. The primary rules are:
- Numeric types will get mapped to numeric vizier-like expressions
- Datetimes will get mapped to date vizier-like expressions
- text and chars will get mapped to string vizier-like expressions
- enumerated values (i.e., columns with value elements giving options) will not become vizier-like expressions but input keys that yield selection widgets.
To have more control (e.g., if you do not want to allow vizier-like expressions, give the input key yourself):
<condDesc> <inputKey original="primaryId" required="False"/> </condDesc>
(which would make a column required in the table optional in the query), or:
<condDesc> <inputKey name="specType" tablehead="Spectral Type" type="text" description="Spectral type of the target object"> </condDesc>
(which creates an input key matching everything literally), or even:
<condDesc> <inputKey name="color" type="text" required="True"> <values multiOk="True"> <option title="Red">R</option> <option title="Green">G</option> <option title="Blue">B</option> </values> </inputKey> </condDesc>
– if the input key is required, queries not giving it will be rejected. The title attribute on option gives the label of an option in the HTML input widget; if it’s missing, a string representation of the value will be used.
In all those cases, the SQL generated from the condDesc is a conjunction of the input key’s individual SQL expressions. Those, in turn, are simply comparisons for equality for plain types and more or less arbitrary expressions for vizier expression types.
Incidentally,
For complete control over what SQL is generated, condDescs may contain code called a phrase maker. vizierexprs.getSQLKey function. It takes a name, a value, and the outPars dictionary. It>
More on Metadata¶
In general, most metadata for services and resources rather closely follows what’s defined in Resource Metadata for the Virtual Observatory; see also the Reference Manual on RMI-style metadata.
Coverage¶
One tricky spot is coverage, i.e., the parts of the STC space covered by what’s in the resource. In general, you will define coverage more or less like this:
<meta name="coverage"> <meta name="profile">AllSky ICRS</meta> <meta name="waveband">Optical</meta> </meta>
The easy part is the waveband. Values here are from a fixed set of strings, viz., Radio, Millimeter, Infrared, Optical, UV, EUV, X-ray, Gamma-ray; capitalization is important, and you may give multiple elements (the software doesn’t enforce this selection, but your registry documents will become invalid if you use anything else).
The coverage.profile meta item has STC-S strings as values. See the STC-S Note as well as the STC library documentation for more information on the STC-S understood by DaCHS. In principle, you can get fancy here; for example, you could write:
<meta name="coverage.profile"> TimeInterval TT BARYCENTER 1999-10-01T20:30:00 1999-10-02T20:30:10 unit s Error 10 Resolution 1 2 Circle FK5 J1980.0 GEOCENTER 0.13 0.45 0.03 unit rad PixSize 0.0001 0.0001 SpectralInterval HELIOCENTER 2000 6000 unit Angstrom Error 1 RedshiftInterval TOPOCENTER VELOCITY RELATIVISTIC -10 10 unit km/s </meta>
However, the registries probably evaluate not very much of this information as yet, and you most certainly should try to give positions in ICRS.
(Content) Type¶
Values for
type come from a controlled vocabulary that
includes Other, Archive,
Bibliography, Catalog, Journal, Library, Simulation, Survey,
Transformation, Education, Outreach, EPOResource, Animation, Artwork,
Background, BasicData, Historical, Photographic, Press, Organisation,
Project, Registry.
Specifying the content type is optional, and you can repeat the meta element as often as you need to.
If you are unsure what these mean, see Resource Metadata for the Virtual Observatory, section 3.3.
Licensing¶
Within the astronomical community, licensing issues have traditionally played a minor role – if you referenced properly, using data from other people was not only ok, it was encouraged. We should keep it that way, even in the days of easy reproducability. Still, formal statements about how your data may be used are required if, for instance, the data or parts thereof are re-used in Free software. Such statements are called licenses.
In DaCHS, three meta items are used for licensing:
- copyright – this is free text displayed on web pages, including the service info. This can be verbose and state acknowledgements, funding information, and the like.
- rights – this is transmitted to the registry and should be a very terse phrase specifying the absolute minimum necessary to assess usage conditions (something like “Free to use”, “CC-BY”, etc). This should not contain funding info, acknowledgements, and the like.
- rightsURI – a URI of a common license; this is so machines can figure out conditions if necessary. We’ll link a list of such URIs if we find one.
In practice, you should stick to a well-known license. DaCHS comes with support of CC-0 (essentially, no restrictions) and CC-BY (state where you got the data from if re-publishing). Let us know if you want other licenses supported, and we’ll do something about it. To apply them, replay one of the streams
- //procs#license-cc0 (public domain)
- //procs#license-cc-by (attribution)
into the RD and give a
what attribute saying what is licensed
(usually, the data). For instance:
<STREAM source="//procs#license-cc-by" what="ARIHIP"/>
Sometimes you want an additional acknowleding clause. In that case, just add another copyright meta item:
<meta name="copyright""/>
In case your data providers are nervous: catalog within a planetarium software. didnwhich meridian (i.e., they should be close to UTC).
The time scales are important on the level of seconds; they include TAI (the time scale defined by a bunch of atomic clocks, UTC (TAI with leap seconds, basically our everyday time), UT, UT0, UT1, UT2 (several sorts of true times in Greenwich), and TT (Terrestial Time, a time scale linked to the TAI and used quite a bit in Astronomy). More of that on the fairly readable..
In STC-S parlance, the reference positions available include positions would be TOPOCENTER (the observatory), GEOCENTER (the center of the Earth), BARYCENTER (the barycenter of the solar system) and UNKNOWN (the default, which you should keep unless you are sure; clients can then at least employ some sane fallback rather than make wrong assumptions).
To declare those, you must include a time phrase in your STC declaration in your table. Typically, this could look like this:
<table id="foo"> <stc>TimeInterval TT "timeStart" "timeEnd" Time "dateObs"</stc> <column name="timeStart" ucd="time.start" unit="d"/> <column name="timeEnd" ucd="time.end" unit="d"/> <column name="dateObs" ucd="time.epoch;obs" unit="yr"/> ...
(descriptions and everything else left out for clarity; in particular, for times using double precision almost always is a good idea).
Publishing DAL Services¶
DAL is VO-speak for “Data Access Layer”, the standard protocols the VO uses to allow remote querying of data.
This section discusses the individual protocols in turn.
SCS¶ Building a Catalog Service is a combined SCS/form service. This section just briefly recapitulates what was discussed there. For a quick start, just follow the tutorial above.
Tables¶
In principle, SCS can expose any table that has#q3cindex mixin on the tables, like this:
<table id="forSCS" onDisk="true" mixin="//scs#q3cindex"> ...
Finally, note that to have a valid SCS service, you must make sure the
output table always contains the three required columns (as defined by
the UCDs given above. To ensure that, these columns’
verbLevel
attribute must be 10 or less (we advise to have it at 1).
Cores¶
The SCS core simply is a dbCore. You must include the SCS condDesc, like this:
<dbCore queriedTable="main"> <condDesc original="//scs#protoInput"/> </dbCore>
There is an alternative condDesc more suitable for humans. They can be used in parallel. The form renderer will then use the human-oriented one, the DAL renderer the protocol one. You’ll get this by writing:
<dbCore id="xlcore" queriedTable="main"> <condDesc original="//scs#humanInput"/> <condDesc original="//scs#protoInput"/> </dbCore>
Although not required by SCS, we recommend to also include a MAXREC argument that lets people change the match limit in the SCS service (for the web service, the database widget already provides this functionality). A usable definition for it is given in the SCS RD in a STREAM with the id coreDescs, together with the two condDescs above. So, here’s the recommended way to build a bare-bone SCS service:
<dbCore id="xlcore" queriedTable="main"> <FEED source="//scs#coreDescs"/> </dbCore>
SCS allows more query parameters; you can usually use condDesc’s buildFrom attribute to directly make one from an input column. If you want to add a larger number of them, you would use an active tag:
them, since for SCS this requires going through the registry. In TOPCAT, for example, users would have to manually edit the cone search URL.
Service¶
To expose that core through a service, just allow the scs.xml renderer on it. As the core is built, you can have a web-based form interface for free:
<service id="cone" allowed="scs.xml,form"> <meta name="title">Nice Catalog Cone Search</meta> <meta name="shortName">NC Cone</meta> <meta name="testQuery.ra">10</meta> <meta name="testQuery.dec">10</meta> <meta name="testQuery.sr">0.01</meta> <dbCore id="xlcore" queriedTable="main"> <FEED source="//scs#coreDescs"/> <LOOP listItems="ipix bmag rmag jmag pmra pmde"> <events> <condDesc buildFrom="\item"/> </events> </LOOP> </dbCore> </service>
The meta information given is used when generating registration records. In particular, you should make sure that a query with the given ra, dec, and sr actually returns some data.
SIAP¶
DaCHS’ SIAP implemention right now assumes you are publishing FITS files
with WCS headers. Other arrangements are of course possible, but you’d
have to write an equivalent of the
//siap#computePGS procDef
yourself.
Quick Start" \ | tr '<TD>' '\n' \ | grep "^http://" \ | sed -e 's/<[^>]*>//g' \ | xargs -n1 curl -sO
(no, this is not in general the way to operate SIAP services; use a proper client for real work, and we didn’t show you this)..
Tables¶
SIAP-capable tables should mix in
//siap#pgs.
This mixin provides all the columns necessary
for valid SIAP responses.
So, in the simplest case, a table that’s going to be published through SIAP would look like this:
<table id="images" onDisk="True" mixin="//siap#pgs"/>
(of course, you can add more columns if you need them, and you might need metadata and all that, but this is all it really takes).
In the case of the Lockman Hole RD, things are a bit more verbose:
<table id="main" onDisk="True"> <mixin>//siap#pgs</mixin> <mixin calibLevel="3" collectionName="'VLBA LH sources'" facilityName="'VLBA'" oUCD="'phot.flux.density;em:radio.750-1500MHz;phys.polarisation.Stokes.I'" polStates="'/I/'" targetName="object" tResolution="5000000" targetClass="'AGN'" >//obscore#publishSIAP</mixin> <column name="object" type="text" ucd="meta.id" tablehead="Object" description="Source name as in 2009MNRAS.397..281I (VizieR J/MNRAS/397/281)" verbLevel="1"/> <column name="obsra" ucd="pos.eq.ra" unit="deg" description="Antenna pointing, RA" verbLevel="18"/> <column name="obsdec" ucd="pos.eq.dec" unit="deg" description="Antenna pointing, Dec" verbLevel="18"/> <column name="weighting" type="text" ucd="meta.code" description="Natural or uniform, according to weighting method." verbLevel="18"> <values><option>natural</option><option>uniform</option></values> </column> </table>
More on the obscore mixin below. otherwise, you see that additional, non-siap columns are simply added as usual. Anything with a verbLevel lower or equal 20 will be included in standard SIAP replies.
To fill such tables, the normal
//products#define rowfilter is
necessary, and there are two procDefs from
//siap that come in
handy:
are fairly complex mosaics, there's no way we can have sensible dates; this one here "plays a special role in the calibration" (Middelberg) --> usually comes in particularly handy.
- When ingesting images, you will (at least for a while, still) almost always read from FITS images, i.e., FITS primary headers. A
fitsProdGrammardelivers the key-value-pairs from a header as a rawdict.
- The
qndattribute of the grammar is recommended. It makes some (weak) assumptions to yield significant speedups with large images, just so long as you can make do with the primary header.
- The
fitsProdGrammarwill map keys with hyphens to names with underscores, which allows for smoother action with them in rowmakers. The
mapKey`element can produce additional mappings; in this case, we abuse it a bit to let us have idmaps (rather than simplemaps) in the rowmaker. And, actually, to illustrate the feature, as this data does not need that facility, really.
- The grammar further needs a rowfilter. The products#define rowfilter lets you add keys on owners and embargo in case you want password protection for images, but most importantly it defines what table the data is destined for. This is crucial information, and if you ever get it wrong, you need to manually connect to the database and issue a command like
DELETE FROM products WHERE sourcetable='<your wrong table>'. So, always bind table. Make sure to include the quotes, this is supposed to be a valid python expression yielding a string. Also, this is where you’d define the media type for your products if they’re not FITS files.
- You then need to define a rowmaker that must apply two procs. For one, you need //siap#computePGS (if you mixed in
//siap#pgsSIAP). No bindings are required here.
- The second proc application required is //siap#setMeta . Try to give all its keys somewhat sensible values, you will make your users’ lives much easier.
- Typically, many values coming in the FITS headers will be messy and fouled up. You’ll spend some quality time fixing these values in the typical case. Here, we translate somewhat broken object names using a simple mapping file that was provided by the author. In other circumstances there’s the procs#mapValue procApp helping you.
- As is usual in procApps, you can access the embedding RD as
rd. Here, we use that to let DaCHS find the input file independently of where the program was started.
Warning: Do not use idmaps=”*” with SIAP, since the auto-generated mappings will clobber the work of the xSIAP procs.
Cores¶
There are two cores you may want for SIAP services:
-, use the //siap#humanInput condDesc as well. Both are written in a way that they’ll sense if they run under a SIAP renderer or in the
siap.xml reference.).
SIAP version 2¶
SIAP version 2 is just a a thin layer of parameters on top of obscore.
To publish with SIAP version 2, simply ingest your data as for SIAP and
add the appropriate ObsTAP mixin (
//obscore#publishSIAP, in all
likelihood).
There is a sitewide SIAPv2 service at
<root
URL>/__system__/siap2/sitewide/siap.xml which is always there. It is,
however, unpublished by default. To publish it, you should furnish some
extra metadata in your userconfig RD (see
opguide.html#userconfig-rd).
Specifically, get the
sitewidesiap2-extras stream and follow the
instructions there and update the meta items as appropriate; they are
analogous to the ones for SIAP.
Once that’s done, you can say:
dachs pub //siap2
and you’re done.
There currently is no facility for having SIAPv2 services for individual services. If you want them, talk to us.
SSAP¶
Since SSAP metadata is relatively large, in the past we have recommended to use an extra mixin where constant metadata was given in PARAMs. This was //ssap#hcd, which you still may find in use in several example datasets. Do not use that any more; we found that space savings are nowhere near proportional to the extra implementation effort. Only use the //ssap#mixc mixin in new RDs. If you have really large number of spectra (I’d say upwards of order 1e6), consider using SSAP with views.
SSAP Quick Start¶
cd `dachs config inputsDir` svn co cd zcosmos mkdir data
The checkout does not contain actual data, so let’s fetch a file:
cd data curl -O \ cd ..
This dataset needs obscore, and you should obscore-publish your spectra as well. So, make sure you have the obscore table:
dachs imp //obscore
Run the input and the regression tests:
dachs imp q dachs test q
One regression test should fail since you’ve not yet pre-generated the previews (which are optional but recommended for your datasets, too):
python’d have to go through datalink, which TOPCAT can’t yet do) to and do your queries (if you don’t know anything else, do a positional query for 149.734, 2.28216).
Please drop the dataset again when you’re done playing:
dachs drop zcosmos/q
Since the dataset is in the obscore table, it would otherwise be globally discoverable, and that’d be bad.
The remainder of this chapter discusses what’s in the RD. It is probably a good idea to have it open while reading this.
SSAP Tables¶
Tables open for SSAP querying need a certain structure. Use the //ssap#mixc mixin to have DaCHS fill it in:
<table id="data" onDisk="true"> <mixin fluxUnit=" " fluxUCD="phot.flux.density" spectralUnit="Angstrom">//ssap#mixc</mixin> <mixin>//ssap#simpleCoverage</mixin> </table>
As usual, you can define extra columns manually if necessary; the one you’ll find in the actual RD is discussed below in SSAP and Datalink. There’s also another mixin in what you checked out, which is discussed in SSAP Obscore Publication
This mixin has lots of parameters that define lots of
things. Simply use the parameter list in the reference documentation
(see the link above) as a
checklist and leave out what you don’t have. You must give a
fluxUnit,
fluxUCD and a
spectralUnit, though, as they are used in
the metadata of some of the columns. When your spectra are not flux
calibrated, use a single blank as the unit.
Note that despite their name, the timeSI, fluxSI, and spectralSI mixin parameters do not contain actual unit strings. Instead, they are intended to contain conversion factors in a custom syntax called “Osuna-Salgado convention”. We recommend to not set these fields and instead provide useful VOUnit-compliant units where appropriate.
Building SSA Tables¶
SSAP tables contain products, so you’ll (realistically) have to have a //products#define rowfilter in your grammar. Unless you’re very sure you don’t want that, also use the //ssap#setMeta and //ssap#setMixcMeta applys.
Unfortunately, there’s no real standard for spectra that is widely used. If you’re lucky, you’ll get 1-D arrays in FITS format (IRAF liked to write such spectra; declare those with a media type of image/fits, since that’s what they really are) or FITS tables with spectral/flux pairs (use a media type of application/fits for them).
Our example data set indeed comes as FITS, so we’re using an Element fitsProdGrammar. The following bindings already prepare for making and serving previews, which is discussed in more detail in Product Previews in the DaCHS reference; see there for everything mentioning “preview”:
<data id="import"> <property key="previewDir">previews</property> <sources pattern="data/1D/zCOSMOS_BRIGHT_DR2_*.fits"/> <fitsProdGrammar qnd="True"> <rowfilter procDef="//products#define"> <bind name="table">"\schema.data"</bind> <bind name="mime">"image/fits"</bind> <bind name="preview">\standardPreviewPath</bind> <bind name="preview_mime">"image/png"</bind> </rowfilter> </fitsProdGrammar>
The rowmaker uses the two applys mentioned above. Here, the spectral
axis is along a WCS-described array axis. There’s a nifty class
handling the calculations with a factory function
getWCSAxis.
Otherwise, writing the rowmaker essentially means using
the parameter lists of
the applys as checklists. Here, this works out to:
<make table="data"> <rowmaker idmaps="ssa_*"> <var name="specAx">getWCSAxis(@header_, 1)</var> <var name="specLen">int(@NAXIS1)</var> <apply procDef="//ssap#setMeta"> <bind name="dstitle">"%s %s"%(@TELESCOP, vars["ESO OBS ID"])</bind> <bind name="pubDID">\standardPubDID</bind> <bind name="targname">"ICRS %s %s"%(@RA, @DEC)</bind> <bind name="alpha">@RA</bind> <bind name="delta">@DEC</bind> <bind name="aperture">vars["ESO INS ADF SKYREG"]/3600.</bind> <bind name="cdate">@DATE</bind> <bind name="bandpass">"IR, Optical, UV"</bind> <bind name="targclass">"X"</bind> <bind name="dateObs">@DATE_OBS</bind> <bind name="timeExt">@EXPTIME</bind> <bind name="length">@specLen</bind> <bind name="specstart">@specAx.pixToPhys(1)*1e-10</bind> <bind name="specend">@specAx.pixToPhys(@specLen)*1e-10</bind> </apply> <apply procDef="//ssap#setMixcMeta"> <bind name="collection">"zcosmos"</bind> <bind name="creationType">"archival"</bind> <bind name="dataSource">"survey"</bind> <bind name="fluxCalib">"RELATIVE"</bind> <bind name="specCalib">"ABSOLUTE"</bind> <bind name="binSize">2.5e-10</bind> </apply> </rowmaker> </make>
Just make sure you do not forget the
idmaps="ssa_*" at the top
(you’ll see rather opaque “key (something) not found in a mapping”
messages if you do).
Caution: In the ssa table, the spectral axis must be a wavelength in meters. You must convert all values manually if necessary. For the spectra themselves you could use different units, but in our experience that’s more confusing than helpful.
In contrast to images where delivering FITS is likely all you need, there’s a plethora of formats spectra are delivered in. To help a bit, you should make sure one of the formats you offer are VOTables conforming to the spectral data model (see Making SDM Tables in the reference documentation and SSAP and Datalink below). If you want to deliver the “native” format as well, you’ll have to have two rows for each spectrum. The standard way to achieve that is through a rowmaker in the grammar importing the spectra, like this:
<rowfilter name="generateFormatLinks"> <code> baseAccref = os.path.splitext(row["prodtblPath"])[0] row["prodtblAccref"] = baseAccref row["prodtblMime"] = "image/fits" # this is the file as delivered from upstream yield row row["prodtblAccref"] = baseAccref+".vot" row["prodtblPath"] = \fullDLURL{sdl} row["prodtblMime"] = "application/x-votable+xml" # this is our processed SDM VOTable yield row </code> </rowfilter>
(we don’t do that here; if we did, you could have used a spectrum
immediately in TOPCAT in the quick test above). For this to work, you
will of course need a datalink service spitting out an appropriate
VOTable with an id of
sdl (the argument to the
fullDLURL macro)
in your RD – we will discuss this below.
SSAP’s FORMAT parameter lets clients select what they want. The way the default FORMAT argument works, only application/x-votable+xml records are considered compliant.
SSAP Services¶
Use the element ssapCore for SSAP services.
You must manually feed in
the condition descriptors for the SSAP parameters; the simplest way to
do that is to
FEED the //ssap#hcd_condDescs stream.
Additionally, there is a set of SSA-specific metadata that
is discussed with the ssap.xml renderer. The result for
our example is:
<service id="ssa" allowed="form,ssap.xml"> <meta name="shortName">zCosmos SSAP</meta> <meta name="title">zCosmos Bright Spectroscopic Observations DR2</meta> <meta name="ssap.dataSource">pointed</meta> <meta name="ssap.testQuery">MAXREC=1</meta> <meta name="ssap.creationType">archival</meta> <meta name="ssap.complianceLevel">query</meta> <publish render="ssap.xml" sets="ivo_managed"/> <publish render="form" sets="ivo_managed,local" service="web"/> <property name="datalink">sdl</property> <ssapCore queriedTable="data"> <FEED source="//ssap#hcd_condDescs"/> </ssapCore> </service>
The
hcd_condDescs STREAM.
If you>
Do not do this just because you don’t have position information – this would mean that you would dump your complete archive for (typical) queries with a position, and that is neither required by the spec (even if you might think so at first reading) nor desirable..
To expose SSAP cores, use the ssap.xml renderer. Using the form renderer on SSAP cores is not terribly useful, because the core returns XML directly, and there are far too many parameters no human will ever be interested in anyway. So, you’ll typically define extra browser-based services. The example RD shows a compact way to do that.
SSAP Obscore Publication¶
SSA tables are not terribly far from obscore tables, and so it’s fairly
easy to also publish the spectra through ObsTAP. Therefore, just do
it by mixing in //obscore#publishSSAPMIXC. This just needs a
calibLevel parameter, everything else is pre-set from SSAP or
optional. Thus, the
complete table definition for our example RD is:
<table id="data" onDisk="true"> <mixin fluxUnit=" " fluxUCD="phot.flux.density" spectralUnit="Angstrom">//ssap#mixc</mixin> <mixin>//ssap#simpleCoverage</mixin> </table>
SSAP and Datalink¶
Given that you’ll. In DaCHS, that’s not too hard; essentially, you have to write an embedded (or custom) grammar to parse the spectra. Other than that, it’s just a few formalities.
So, you first define the table that will later hold your spectrum. Use the //ssap#sdm-instance mixin for that (all examples are still from zcosmos/q):
<table id="spectrum"> <mixin ssaTable="data" fluxDescription="Relative Flux" spectralDescription="Wavelength" >//ssap#sdm-instance</mixin> </table>
If your spectrum has additional columns (e.g., errors, noise estimates, bin widths), just put more columns in here. The mixin, in particular, pulls in all the various params that SDM wants to see.
Note that the table does not have
onDisk="True"; these tables are
only made for the brief moment it takes to serialise them into what the
user receives.
As usual, to fill tables, you want a data element. In our example, this is:
<data id="build_sdm_data" auto="False"> <embeddedGrammar> <iterator> <setup> <code> from gavo.protocols import products from gavo.utils import pyfits </code> </setup> >
Starting with the rowmaker: it’s missing. DaCHS will then fill in the
default one, which essentially is
idmaps="*". Since you’re writing
the grammar from scratch, just use the names of the columns defined in
the instance table and be done with it. The predefined column names are
spectral and
flux, so make sure you always have keys for them in
the dictionaries you yield those from your grammars.
Then there’s a Element parmaker; this is stereotypical,
just always use the
procDef as here. It copies values from the SSA
input row to the params in the instance table.
The thing you have to vary is the code in the embedded grammar. It
must, from its input (
self.sourceToken, which here is the SSA row)
figure out where the data file is (in this case, we can get it from the
products table, which is the code with
products.RAccref. More typically,
just make a convention how to get from accref to the local file and use
that. An example for that is in feros/q (the complication
there is that the datalink products actually have accrefs themselves,
and for those the path in the product table is the datalink URL; that,
of course, wouldn’t bring the grammar any closer to finding the file.
But you can do arbitrary things here; see the califa/q3 RD for an example for how you can decode the accref to database rows.
Once you have that just build dictionaries with at least
spectral
and
flux keys; at least with the default rowmaker you need to make
sure that the values match the units you define in the instance table.
Finally, write the service; you should at least have skimmed the endless chapter on Datalink and SODA in the reference documentation to get an idea of how descriptor generators, data functions, and meta makers play together:
<service id="sdl" allowed="dlget,dlmeta"> <meta name="title">zCosmos Datalink Service</meta> > </service>
Datalink services (almost) always need to be enabled for both
dlget
and
dlmeta. The //soda#sdm_genData data function needs
a reference to the data element filling the instance table. The actual
operations you can simply pull from the soda RD; sdm_plainfluxcalib offers a
maximuum=1 calibration of the spectral values (which probably is not
terribly useful for you), sdm_cutout does cutouts, which may come handy
when you have long spectra, and sdm_format finally is the format
translation that’s frequently useful with spectra.
In particular as long as only few, if any, clients evaluate datalink blocks in DAL responses, it may be a good idea to include a custom column with a datalink URL in the SSAP table. If you’ve been following this exposition in the example RD, you will have noticed the custom column definition in the data table:
<column name="datalink" type="text" ucd="meta.ref.url;meta.data.datalink" tablehead="Datalink" description="A link to a datalink document for this spectrum." verbLevel="15" displayHint="type=url"/>
(we’re cheating a bit with the UCD; it’s actually not legal right now, but we’re trying). To compute the datalink URL, there’s again a helpful macro taking the datalink service id:
<map name="datalink">\dlMetaURI{sdl}</map>
DaCHS for now delivers XSLT with datalink (or does the XSLT translation
itself if it suspects its client is actually a web brower), so there’s
no harm (but potentially quite a bit benefit) to feed this URL to tables
displayed by web browsers, as we do here in the
web service.
SSAP with Views¶
In a typical SSA table, most data will be constant. We don’t consider this a large problem, as most collections are rather small, and so the memory overhead is negligible. However, in particular considering I/O bandwidth (Postgres is not a column store), you may still want to keep constant things out of the rows as your collections grow larger. We no longer support the old //ssap#hcd mixin that did something pretty much like this (albeit somewhat unflexibly). Instead, we recommend going through (non-materialised, or there’d be no benefit) views.
This works by importing your metadata into a custom table and then have the mixin-ed table be a view. The tricky part is to figure out how to write the view given that the columns are implict. Here’s how to get around this. You can see the result in context in k2c9vst/q.
Warning: This introduces a fairly complex dependency scheme, and
when dropping, DaCHS doesn’t take into account dependencies yet. Thus,
dropping the tables belonging to a service discribed here essentially
needs to happen manually (
dachs purge on the tables). We intend to
fix this; complaints will make us do that quicker.
First, write a table definition and a null data item:
<table id="timeseries" onDisk="True"> <mixin fluxUnit="adu" spectralUCD=" " spectralUnit=" " >//ssap#mixc</mixin> </table> <data id="make_ts"> <make table="timeseries"/> </data>
Do a metadata import of this – you need to import the table, or DaCHS
will not find its metadata, and you should only import the metadata, or
DaCHS will now create a table and later try to drop a view, which will
give you an error (that you can fix by running
dachs purge
<tablename>):
$ dachs imp -m k2c9vst/q make_ts
Now make sure the server is running and open the metadata inspection
page for your RD. In this case, the URL would be (it’s always
browse and the
RD id). You’ll see a link to the table, and you can see the columns.
Then, in the table, write a view statement. Always follow this pattern:
<table id="timeseries" onDisk="True"> <mixin fluxUnit="adu" spectralUCD=" " spectralUnit=" " >//ssap#mixc</mixin> <viewStatement> CREATE VIEW \curtable AS ( SELECT \colNames FROM ( SELECT ''||dataid as accref, 'application/x-votable+xml'::text as mime, ... ) AS q ) </viewStatement> </table>
This makes sure you’re actually creating the view DaCHS is expecting
(the
\curtable macro), and the view has the structure declared in
the RD (the
\colNames macro). In the innermost select, you can then
simply fill the columns one by one, in any order convenient to you as
long as you get the names right.
Unless one of the joined tables mixes in
products#table, you’ll have
to directly give complete URLs here rather than DaCHS accrefs (which
always are resolved through the products table).
Note that you must give all types of literals explicitly in the view
definition, either using
CAST or the shortcut notation
:: (when
writing the view by hand, it doesn’t really matter which one you use):
... 'LensingEv'::text as ssa_targclass, CAST (NULL as real) as ssa_redshift, ...
If you want the result to be ADQL-searchable, tables used in the view
must be accessible to an unprivileged database user. To do that, use
adql="hidden" in the respective tables:
<table id="mymeta" onDisk="True" adql="hidden"> ... your columns ... </table>
Typcially, you’ll still be importing source tables from somewhere. When
you do this, the view will be torn down. You should make sure that
DaCHS recreates the view when one of the tables making up the view is
re-made. Simply declare the view-making data item in the importing data
item as
recreateAfter:
<data id="import" recreateAfter="make_ts"> (normal, custom importing rules) </data>
ObsTAP¶
Note: Before you can do anything with obscore, you have to run:
dachs imp //obscore
This will also declare support for the obscore DM in your TAP service’s registry record.
Obscore Derived from Typed Service Tables¶
ObsTAP is basically a single table, ivoa.ObsCore. In DaCHS, this is a view generated from input tables. To include the products within a table, you must use one of the mixins from the //obscore RD and fill out some of the mixin’s parameters. There is some documentation on what to put where in the mixin documentation, but frankly, as a publisher, you should have at least passing knowledge of the obscore data model as laid down in Tody et al (2011).
In the simplest case, a SIAP table, you could get by simply adding:
mixin="//obscore#publishSIAP"
to the table definition’s start tag. You do not have to re-import a table to
publish it to obscore after the fact –
dachs imp -m <rd id> && dachs imp
//obscore create will include an existing table to the obscore view.
Even for SIAP, you will usually want to add metadata not contained in DaCHS’ SIAP meta. To do this, add a mixin element to the table definition’s body:
<mixin sResolution="0.5" calibLevel="2" >//obscore#publishSIAP</mixin>
To find out what parameters the mixin takes, see //obscore#publishSIAP in the reference documentation.
On a table import, the obscore table will automatically be recreated to include the data. If you retrofit ObsCore support to large tables, you can avoid having to re-import everything by adding the mixin clause and then updating the metadata. In that case, you must manually remake the obscore table:
dachs imp -m path/to/my/rd dachs imp //obscore create
For SSAP tables, there is an
//obscore#publishSSAPMIXC mixin that works
like its SIAP cousin (see the reference documentation of details).
Pure Obscore Tables¶
You can also have “pure” Obscore tables which do not build on protocol mixins. A live example is the cubes table in the califa/q3 RD within the GAVO data center. Here’s a brief explanation of how this works.
For the non-constant parts of your data, re-use the metadata given in
the global obscore table – to make that convenient, tell DaCHS to
resolve
original references in there:
<table id="cubes" onDisk="True" namePath="//obscore#ObsCore">
adql="True" is absent here as the obscore mixin set it. It wouldn’t
hurt, though.
You will almost always want to have DaCHS manage your products. This works even when all your files are external (i.e., you’re entering http URLs in accessURL), so it’s a good idea to always mix in products:
<mixin>//products#table</mixin>
Then, you mix in
//obscore#publish, which is like the
protocol-specific mixins except it doesn’t pre-set parameters based on
what’s already in protocol-specific tables:
<mixin accessURL="dlurl" size="10" mime="'application/x-votable+xml;content=datalink'" calibLevel="3" collectionName="'CALIFA'" coverage="s_region" dec="s_dec" emMax="7e-7" emMin="3.7e-7" emResPower="4000/red_disp_mean" expTime="t_exptime" facilityName="'Calar Alto'" fov="0.01" instrumentName="'PMAS/PPAK at 3.5m Calar Alto'" oUCD="'phot.flux;em.opt'" productType="'cube'" ra="s_ra" sResolution="0.0002778" title="obs_title" tMax="t_min" tMin="t_max" targetClass="'Galaxy'" targetName="target_name" >//obscore#publish</mixin>
Essentially, what’s constant is given in literals, what’s variable is given as a column reference. It is a bit unfortunate that you have to enter quite a few identity mappings in here, so we might provide a mixin presetting those if this turns out to be a common use case. Tell us if you’re annoyed.
You can then add your custom columns (which might be useful if people directly query your table). The central part is copying over obscore columns that are not constant for your data collection. For califa, this looks like this:
<LOOP listItems="obs_id obs_title obs_publisher_did target_name t_exptime t_min t_max s_region t_exptime"> <events> <column original="\item"/> </events> </LOOP>
– you’ll obviously have to adapt the
listItems. To see what column
names are available, see the obscore table description.
That’s about it for defining the table. To fill the table, just have a
normal rowmaker; since the table contains products, don’t forget the
//products#define rowfilter in the grammar.
Datalink¶
Datalink isn’t a discovery protocol like the others discussed so far; rather, it is a file format and a simple access protocol for representing relationships between parts of complex datasets. Essentially, datalink is for you if you have parts of a dataset’s provenance, refined products like source lists and cutouts, masks, or whatever else.
Datalink is particularly attractive when you have large datasets and you don’t want to push out the whole thing in one go by default. Insteadt, clients retrieve the datalink document. That then says how to retrieve cutouts (and also gives a link to the full dataset for those that want it and are aware they might be pulling a large chunk of data).
Since Datalink is very flexible, defining datalink services is a bit involved. The reference documentation has a large section on it. Here, we discuss some standard cases.
Datalinks in columns¶
The simplest way to let people discover datalink documents is by including links in normal tables (as for DAL tables) and keep the normal access URL in the accref column. To do that, define a column like this:
<column name="datalink" type="text" ucd="meta.ref.url" tablehead="DL" description="URL of a datalink document for this dataset" verbLevel="1" displayHint="type=url"/>
and then fill it in the corresponding rowmaker. For the normal case where a product corresponds to a disk file, there is a macro to help you:
<map key="datalink">\dlMetaURI{dl}</map>
Here, the “dl” in the macro argument must be the id of the datalink service as discussed below.
In such situations, it is still usually advisable to use the datalink URL rather than the naked accref in the obscore table – for instance, when you are using a SIAP cutout on large image (obscore cannot do cutouts) or to allow format conversions. To do that, you need to advise the obscore to use the datalink response; besides changing the access URL, you will also need to adjust the access_format (so clients know they will have to deal with a datalink) and the access_estsize (because they will not have to download the entire dataset in one go). For the latter, it is hard to predict how large the datalink stream will end up being. Guessing “about 10 kB” should be good enough, though.
In total, the obscore mixin would have to look like this:
<mixin mime="'application/x-votable;content=datalink'" accessURL="datalink" size="10" ... >//obscore#publish(WHATEVER)</mixin>
(in case you’re wondering: the
datalink given here for accessURL is
just the column name as given above).
Datalinks as accrefs¶
In particular for large datasets, it is probably a good idea to keep people from blindly pulling the data without first having been made aware that what they’re accessing is not just a little CCD frame. Having the datalink document as the primary document retrieved is a fairly good way to do that; of course, without a datalink-enabled client people might be locked out from the dataset entirely. On the other hand, DaCHS comes with a stylesheet that enables datalink operation from a common web brower, so that’s perhaps not too bad.> [...] </rowfilter> [...] </fitsProdGrammar>
When you do this, you must use a datalink-aware descriptor generator.
When you use the recommended setup, where the accref is the
inputsDir-relative path to the main file, and you’re dealing with FITS,
you can use the
DLFITSProductDescriptor class (in other cases, its
implementation (in gavo.protocols.datalink) will show you how to handle
these cases).>
Also note that DaCHS will not produce automatic previews in this situation. You will have to generate precomputed previews as discussed in Product Previews.
Simple FITS Datalink Services¶
A fairly typical case for a datalink service is a file that has a few related datasets and perhaps a cutout. To define such a thing, write something like (cf. lswscans/res/positions.rd):
> <code> yield descriptor.makeLink( makeProductLink(descriptor.accref+"?scale=4"), contentType="image/fits", description="FITS, scaled by 1/4", semantics="#science", contentLength=descriptor.estimateSize()/16.) </code> </metaMaker> </datalinkCore> </service>
TODO: Explain what’s going on here.>
In the service that has the siap.xml renderer, declare datalink support by setting the corresponding property to the id of the datalink service (here assumed to be
dl):
<service id="ssa" core="siacore" allowed="siap.xml"> <property name="datalink">dl</property>
If you have a form-based publication, hide the
pub_didcolumn and rather make datalinks:
> </outputField>>).
You should, however, take particular care that there’s a useful description of the table, usually as a direct meta on the table. Keep in mind that people will stumble across the table in some sort of registry and need to be able to figure out whether the table contains useful data by that description and the column metadata alone.
The TAP endpoint only exposes rather limited metadata. At least when there is no published service on the table, you may want to just publish the data to the registry, too. This leads to a much richer set of metadata, increasing people’s chances to able to locate the data.
To publish a nonservice (usually a table definition, but you can
register data descriptors containing multiple tables, too), use
the register Element . For a simple
table, just wringing
<register/> is enough, since the set name
defaults to
ivo_managed and ADQL-accessible tables are automatically
related to the TAP services.
When
register is the child of a data item, you need to manually
declare that child tables are TAP-accessible, like this:
<data id="collection" auto="false"> <register services="__system__/tap#run"/> <make table="part1"/> <make table="part3"/> </data>
When publishing “non-obvious” tables to TAP, it’s a good idea to add one or more TAP examples for it. See Writing Examples
Publishing existing tables via TAP¶
If you already have a database table and now want to use DaCHS to publish it via TAP, just write an RD as described above, except that the data element is trivial.="import"> <make table="values"/> </data> </resource>
Within the data element you need one make each for each table you want
in ADQL; it would cause the tables to be created on a plain
gavo
imp, in the present context, it just says something like “put the
table metadata into DaCHS’ internal catalogs”.
After that, say
dachs imp -m <rd-id>; make sure you don’t forget the
-m, because without it,
dachs imp will drop the existing tables
if it can, i.e., if gavoadmin has write access to the schema in
question, and it should have that for reasons explained in the next
paragraph.
This adds the metadata you’ve given to all kinds of administrative tables DaCHS keeps but does not touch the data. should declare them in either the allRoles or readRoles attributes to the table definiton. Maybe even adapting the profiles in GAVOROOT/etc to match your existing infrastructure could make sense.
Also do not forget that people should have some way to locate your data
collection (i.e., the table(s) that you are exposing). If you have
sufficient metadata defined – basically as for services –, you can
register your data collection. To do this, just add an empty
<register/> element to either a table definition or, more
convenient in multi-table setups, a data element for your data
collection. The defaults for register are publication to the VO and,
for ADQL-exposed tables, serviced by the TAP service, which is about
what you want in this situation.
Here’s an example for the case of a multi-table publication:
<data id="collection" auto="false"> <register services="__system__/tap#run"/> <make table="part1"/> <make table="part3"/> </data>
Don’t forget that you need to execute:
dachs pub the/rdid
to make DaCHS actually publish the table..
There are two basic ingestion options:
- local files; you let DaCHS find the sources, parse them, and infer metadata from this; DaCHS will then serve them. That’s what’s shown in the quick start example below.
- ingest from pre-destilled metadata; this is when you don’t have the files locally or at least DaCHS should not serve them. Instead, you’ll get the metadata from dumps from other databases, metadata stores, or whatever. The titan/q.rd RD shows an example for Start-TAP is just a set of columns, some mandatory, some
optional. The mandatory ones are pulled into a table by using the
//epntap2#table-2_0 mixin, which needs the
spatial_frame_type
parameter (see reference for what’s supported there) since that
determines the metadata on the spatial columns.
This treatment distinguishes the two cases mentioned above: Files served by someone else first, files served by DaCHS next.
Externally Served Products¶
The mixin will already open the table for ADQL querying, and to make that work, it is also declared onDisk. What’s not declared is the table name, although it’s fixed at epn_core. Hence, the minimal definition of an EPN-TAP table is:
<table id="epn_core"> <mixin spatial_frame_type="body" >//epntap2#table-2_0</mixin> </table>
If you want to use optional columns from the EPN-TAP specification,
give them in
optional_columns. In the typcial case that you publish
data products, you’ll at least want the access columns, which would
translate into this:
<table id="epn_core"> <mixin optional_columns="access_url access_format access_estsize" spatial_frame_type="body" >//epntap2#table-2_0</mixin> </table>
You can of course add further custom columns as necessary using the normal Element column.
Filling the table from what comes from the grammar happens through
idmaps="*" on the rowmaker (which you want as the
apply
doesn’t actually map
anything into the results and there’s too many columns to make
enumerating fun) and an application of //epntap2#populate-2_0 . The
mixin’s documentation is intended as a checklist; go through the
parameters one by one and see which ones correspond to something in your
input and then say:
<par key="param-name">@source-key</par>,
possibly using python functions and expressions to adapt your inputs to what should end up in the database.
You may need to refer to the EPN-TAP proposed specification now and then while filling things out. Note again that these are python expressions, and so you have to use quotes when specifying literal strings.
More complex operations should probably go to
var declarations
rather than the
bind bodies; again, see the examples to see how.
The real work is populating the table. Let’s first assume you data products and use DaCHS to publish them. You will then use a grammar, and as EPN-TAP then deals with data products, the grammar must use the rowfilter products#define rowfilter as discussed above in SIAP; the lutetia example shows how this can be done while also providing for DaCHS-generated previews.
Externally Served Products¶
When you can store the data products you describe locally and have DaCHS hand them out, that’s usually preferable. It also lets you do things like enforcing embargoes, make previews, etc.
To be able to manage the products, you need to add the
//epntap2#localfile-2_0 mixin, as well as the optional columns
starting with
access_ in the table definition, so minimally:
<table id="epn_core"> <mixin spatial_frame_type="celestial" optional_columns="access_url access_format access_estsize" >//epntap2#table-2_0</mixin> <mixin>//epntap2#localfile-2_0</mixin> </table>
To let DaCHS manage the files, you need the //products#define rowfilter in your grammar. You will minimally have to tell it the table you’re writing to (this is so DaCHS can remove the entries when you drop the table); since it by default assumes you’re serving FITS files, which in planetary sciences is probably untrue, you should also give the media type explicitly, for instance:
<sources pattern="data/*.pds" recurse="True"/> <pdsGrammar> <rowfilter procDef="//products#define"> <bind name="table">"\schema.epn_core"</bind> <bind name="mime">"image/x-pds"</bind> </rowfilter> </pdsGrammar>
(the
\schema will just put in the current schema name defined at the
top of your RD). This is also where you’d configure previews, embargos,
etc.
Finally, in the rowmaker you need to make sure that the new columns are filled. That’s done using a paramterless apply:
<rowmaker> ... <apply procDef="//epntap2#populate-localfile-2_0"/> </rowmaker>
About
s_region¶
The
s_region parameter (see //epntap2#populate-2_0) is essentially
a footprint describing the area covered by 2D spatially extended data products.
It uses pgshpere types such as
spoly,
scircle,
sbox or
spoint
(We advise against the use of
spoint as a
s_region type: only spatially
extended types should be used). The default type is
spoly, the others
must be specified using the
regiontype mixin parameter (Please refer to
//epntap2#table-2_0).
Please note that the
spoly type has some limitations that can trigger
unclear errors when not respected: the segments can not be crossed and, more
important, the maximum dimension of a polygon must be less than 180°.
Here are some example that shows how to implement it with a
sbox:
First the
regiontype:
<table id ="epn_core"> ... <mixin ...//epntap2#table-2_0</mixin> </table>
Then the
s_region parameter, defined in the rowmaker (see Mapping
data):
<rowmaker idmaps="*"> <map key = "s_region"> pgsphere.SBox( pgsphere.SPoint.fromDegrees(float(@c1_min),float(@c2_min)), pgsphere.SPoint.fromDegrees(float(@c1_max),float(@c2_max))) </map> </rowmaker>
If you want an “aperture” (point and radius), you’d write something like:
<table id ="epn_core"> ... <mixin ...//epntap2#table-2_0</mixin> </table> <rowmaker idmaps="*"> <map key = "s_region"> pgsphere.SCircle( pgsphere.SPoint.fromDegrees(float(@c1_min),float(@c2_min)), float(@aperture)*DEG) </map> </rowmaker>
The radius of the circle must be given in radians here; if it’s in degrees, just multiply with DaCHS’ internal DEG symbol (which is pi/180).
Writing Examples¶
In the VO, there is a (as of this writing, fledgling) standard for giving examples for service usage; the idea is to produce HTML that’s useful for human consumption with additional, RDFa-based, markup to let clients figure out how to fill their interface forms.
DaCHS lets you write such examples in ReStructuredText with some extra markup that is turned into the machine-readable semantics.
TAP examples¶
The most prominent kind of examples are the one for TAP/ADQL. These reside in userconfig – please read opguide.html#userconfig-rd before writing examples.
TAP examples are taken from a STREAM
with id
tapexamples. One such example is already given in the
userconfig.rd of the distribution which you can take as a template for
your own examples.
In the stream, there are
_example meta elements with a mandatory
title attribute and ReStructuredText contents.>
You must give a query in a block marked
..tapquery::. A typical
client would fill this into whatever its UI provides to write queries..
As is described in the operator’s guide, DaCHS does not pick up changes
to
userconfig automatically. Hence, after adding or changing
examples, you have to run:
dachs serve exp % //tap
as the gavo user on the server.
To see your shiny new example(s), point your browser to
<server
url>/tap/examples.
Datalink examples¶
DaCHS also contains provisional support for examples associated with datalink services. Since client support for it is not in the pipeline and it’s not planned for the standard either, it’s of questionable utility so far, but hopefully that’s going to change.
To add an example to a datalink service, add an
_example meta with a
title attribute directly.
No manual reloading is necessary here, changes will be picked up
automatically.>
Note that such examples best sit in the service rather than top-level in the RD; if the are direct children of the RD, they would appear in all services defined in the RD.
DaCHS does not yet have support for the capability and continuation properties defined by DALI. Ask if you need them.
Services Over Views¶
Sometimes a service should execute queries spanning several tables. One way to go about this would be to use a fancyQueryCore.
However, since metadata generation is much more straightforward if a service sits on top of something that’s actually pretty much a table, the better way usually is to define a view executing the query. There are some subtleties with this, though, so here’s a few words on how we recommend you go about that.
First, you’ll obviously define the tables involved:
<table onDisk="True" id="master" mixin="//scs#q3cindex" primary="catno" adql="True"> <column name="catno" type="integer" required="True" ucd="meta.id;meta.main" tablehead="id#" description="Identification number in the ARIGFH master catalog" verbLevel="1"/> <column name="raj2000" type="double precision" ... <table onDisk="True" id="identified" adql="True"> <column name="dist" type="double precision" ucd="pos.angDistance" unit="deg" tablehead="Offset" description="Offset between master catalog position at catalog epoch and equinox and the catalog position" verbLevel="1" displayHint="displayUnit=mas,sf=1"/> <column name="masterNo" type="integer" required="True" ...
A good approach might be to stuff the columns that will later show up in
the view into a STREAM and then replay that stream in both the table
definitions and the view definition, but since the RD we’re using as an
example
here worked with
original, this we use in this introduction; with
STREAMs, sharing the columns looks differently, the rest remains the
same.
To save typing and make things a bit clearer, we use LOOPs for copying the source columns. The view definition then looks somewhat like this:
<table onDisk="true" id="id" adql="True"> <meta name="description"> The stars from the gfh table having counterparts in the master catalog, together with those counterparts. </meta> <column original="master.catno" name="masterNo"/> <column original="master.component" name="compMaster"/> <column original="master.raj2000"/> <column original="master.dej2000"/> <column original="master.pmra" name="pmraMaster"/> <column original="master.pmde" name="pmdeMaster"/> <column original="master.mv" name="mvMaster"/> <column original="master.mb" name="mbMaster"/> <LOOP listItems="catid catan dist iq"> <events> <column original="identified.\item"/> </events> </LOOP> <LOOP> <codeItems> for col in context.getById("gfh"): yield {'item': col.name} </codeItems> <events> <column original="gfh.\item"/> </events> </LOOP> >
As you can see, you can rename columns, and the second loop actually gets column names from some table obtained via its id programmatically (only do that if you’re sure you actually want to follow changes in source table structure; the reason this is no one of the joined tables in the view has to do with the specific dataset).
The viewStatement essentially is more or less arbitrary SQL. For robustness against changes of table structure or schema or table name changes, however, you should probably always start with:
CREATE VIEW \curtable AS ( SELECT \colNames FROM
–
\\curtable will automatically adjust to whatever schema and table
name is given in the RD, and
\\colNames gives all the names of the
columns; using it, you’ll ... <make table="identified"... .
The Registry Interface¶
Conceptually, the VO’s Registry is a set of resource records (i.e., descriptions of services, data, or other entities) to let users locate resources relevant to them (e.g., look for a service giving surface temperatures for OB stars). Whatever as a resource record is called VO resource in the following to keep them apart from whatever DaCHS resource descriptors describe; DaCHS RDs may descibe zero, one, or multiple VO resources. We apologize for the confused nomenclature.
Physically, there are several services that keep and update this set and let people query them (a “full registry”), e.g., the ESAVO registry or the DaCHS network of RegTAP services [#rr], with a web interface at.
Adding Publish Elements¶
With that done, you add
<publish> elements to the services you want
to publish to the registry. These were introduced under Cores and
Services; in the most typical case, you want at least one protocol
interface and one browser interface per data sets, but there are many
exceptions.
Here’s “best practice” recommendations:
for SCS services, you can simply use the generated web interface as the browser interace. This leads to the pattern shown in Cores and Services . This will also create an auxiliary TAP publication if the queried table is adql-accessible. In plain English: the table will also be discoverable if people look for TAP services.
as discussed above, you’ll usually have a separate browser service for SSAP services. When you register these, you don’t want separate registry records for the SSAP and the web service. Instead, you just register the SSAP service and tell DaCHS to put the browser service down as a separate capability of that resource. For this, use the
serviceattribute of
publish; this example is again taken from feros/q:
<publish render=”ssap.xml” sets=”ivo_managed”/> <publish render=”form” sets=”ivo_managed” service=”web”/>
for SIAP services, that might work, too; usually, however, you’ll want to trim the interface and in particular the response a bit (using outputTable). If you do, you’ll have to use the
service=trick as in SSAP.
your TAP service you only need to register once:
dachs pub //tap. this will register any obscore table you may have. Similarly, if you want to register your SIAv2 service, you’ll just say
dachs pub //siap2.
For compound services like TAP, Obscore and SIAv2, which typically provide access to many different data collections, each of these should be registered as a data collection record. In the TAP case, that’s easy. Simply write:
<publish/>
into the body of the table and be done with it. If your “resource” consists of several tables, do not individually publish them. Instead, publish the data item that creates them, as in this example taken from rr/q:
<data id="create" auto="false"> <publish sets="ivo_managed" services="//tap#run"/> <make table="resource" role="resource"> [...] <LOOP listItems="capability res_schema res_table table_column res_detail interface intf_param relationship res_role validation res_date oairecs res_subject stc_spatial stc_temporal stc_spectral stc_redshift"> <events> <make table="\item" role="\item"/> </events> </LOOP> [...] </data>
If such a data item doesn’t exist, perhaps because the various tables are built in different data elements, just make a non-importable artificial collection of the tables, as in this example taken from arigfh/q:
<data id="gfhtables" auto="False"> <publish/> <make table="id"/> <make table="nid"/> </data>
Sets¶
The
ivo_managed set that came up in some of the examples above (it
is the default for
publish in data publications) has the special
role of indicating “put this service into the VO Registry”.
While you can define as many other sets as you want (by just mentioning
them in
sets attributes), DaCHS as delivered just uses one other set
name,
local. Register a service in that set, and it will be
displayed on the root page when you use one of the default root page
templates.
Doing the Publication¶
The
publish elements as such have no immediate effect. This is to
prevent accidental publications of unfinished resources, and it also
avoids having to speculatively re-publish resources when you change the
RD. I won’t hide that it’s also technically simpler this way.
So, to actually make the publication happen, run:
dachs pub q.rd
(you pass RD ids instead of filenames, too, as in
dachs pub
arigfh/q). When there are
local publications in the RD published,
the
//services RD on the running DaCHS instance has to be reloaded.
If you gave the [web]adminpasswd configuration item in your
gavo.rc
(and you’re running dachs pub on a machine that has serverURL configured
to point to the running instance), DaCHS will automatically do this;
otherwise, it will issue a warning.
This will still not automatically propagate your records to the VO Registry unless you’re running a publishing registry. The next three sections discuss the transport options to the VO Registry.
Running a Publishing Registry¶
If you run a largeish data center with perhaps dozens of resources that change now and then, you should run a publishing registry. This is not terribly hard, but it incurs that you owe it to the world to let your service run fairly continuously. If you’re not sure you’re up to that, choose another option (below). Likewise, if you’re only running one or two services, this is probably not for you either and you should read on below.
The first step to running a registry is to define what your authority corresponds to in the first place. DaCHS will then create a resource record based on that information. How to do this is described in the operator’s guide. The fact that that’s a bit involved is the main reason we’re discussion other options below.
The next step is to acquaint the VO with your publishing registry.
Technically, this is again a service that exposes a standard interface.
In this case, it is defined by the Open Archives Initiative; in case
you’re curious, you’ll find it at
/oai.xml on your site, and DaCHS
has several stylesheets in place that make it somewhat human-readable.
Once the VO knows about your publishing registries, full registries will
start pulling (“harvesting”) your resource records from there.
To make the VO aware of the existence of your data center, you will need
to tell the RofR (Registry of Registries) about your data center. Go
there, hit “Register/Validate a Registry”, enter
<your data center's
base URL>/oai.xml in the URL box and let it run.
If your endpoint does not validate, please run
dachs val on all RDs
that contain published services. If that doesn’t turn up the problem,
complain to us.
Restricting Access¶
Unfortunately, many data providers believe they want to have their data proprietary for a while. Although they are almost certainly misguided in this, it is hard to enlighten them, and so it’s preferable to have the data in a data center with encumbered access rather than just on the providers’ machines.
Therefore, DaCHS has features to restrict access. Right now, this is very basic and only provides what is known as “mild security”, since it is based on HTTP basic authentication over (usually) unencrypted lines. Given that we are not dealing with sensitive information and snooping attacks on our connections would be too much honor, we consider this enough. However, if you were interested in contributing support for OAuth (say), we’d gladly help.
Note, however, that even HTTP basic authentication needs client support. Recent versions of TOPCAT and Splat have that, others do not, and they simply will not work with password-encumbered services. The situation with OAuth is much worse.. Note that the password is stored in clear text in the database – which allows you to handle “I forgot my password” requests gracefully; as long as we only do HTTP Basic authentication, this doesn’t matter much since with it, the passwords traverse the net in basically cleartext anyway. Again: all this is mild deterrence rather than hard security. retstricted to happy.
To discover further commands manipulating the user table, try:
dachs admin --help
Important: When you use authentication, please set the
[web]realm
configuration item to some string reasonably characteristic for your
site. Many systems will store credentials by realm, and if different
sites use the same realm, their credentials will clobber each other.
For details see the customization info in the operators’ guide
Protecting Services¶
To password-protect entire services, use the
limitTo child of the
service element, for instance:
<service id="scs" core="scsCore" allowed="form,scs.xml" limitTo="happy"> ... </service>
Any access to the service will then require application building the rowdict, set the
owner
and
embargo keys. Owner is the name of a user created as described
above, embargo must eventually become a timestamp, so you’ll in general
come up with an ISO datetime string or a python
datetime.datetime
instance. Here, she can access the
data – see above for details on how to create users and groups. | https://dachs-doc.readthedocs.io/tutorial.html | CC-MAIN-2020-29 | refinedweb | 18,250 | 52.19 |
The methods you have seen so far have been called from within other methods, but a method can also call itself – something referred to as recursion. Clearly you must include some logic in a recursive method so that it will eventually stop calling itself. We can see how this might be done with a simple example.
We can write a method that will calculate integer powers of a variable, in other words, evaluate xn, or x*x...*x where x is multiplied by itself n times. We can use the fact that we can obtain xn by multiplying xn-1 by x. To put this in terms of a specific example, we can calculate 24 as 23 multiplied by 2, and we can get 23 by multiplying 22 by 2, and 22 is produced by multiplying 21, which is 2 of course, by 2.
Here is the complete program including the recursive method, power():
public class PowerCalc { public static void)); } // Raise x to the power n static double power(double x, int n) { if(n > 1) return x*power(x, n-1); // Recursive call else if(n < 0) return 1.0/power(x, -n); // Negative power of x else return n == 0 ? 1.0 : x; // When n is 0 return 1, otherwise x } }
This program will produce the output:
5.0 to the power 4 is 625.0 7.5 to the power 5 is 23730.46875 7.5 to the power 0 is 1.0 10 to the power -2 is 0.01
How It Works
The method power() has two parameters, the value x and the power n. The method performs four different actions, depending on the value of n:
Just to make sure the process is clear we can work through the sequence of events as they occur in the calculation of 54.
You can see from this that the method power() is called four times in all. The calls cascade down through four levels until the value of n is such that it allows a value to be returned. The return values ripple up through the levels until we are eventually back at the top, and 625.0 is returned to the original calling point.
As a rule, you should only use recursion where there are evident advantages in the approach, as there is quite of lot of overhead in recursive method calls. This particular example could be more easily programmed as a loop and it would execute much more efficiently. One example of where recursion can be applied very effectively is in the handling of data structures such as trees. Unfortunately these don't make convenient illustrations of how recursion works at this stage of the learning curve, because of their complexity.
Before we can dig deeper into classes, we need to take an apparent detour to understand what a package is in Java. | http://www.yaldex.com/java_tutorial/0167496290.htm | CC-MAIN-2017-04 | refinedweb | 479 | 69.82 |
By Mike Gunderloy
Reduced to its essentials, the job of a contract developer is pretty simple: Produce high-quality code that meets your customers' needs in the shortest possible time. There are many tools that can help you attain this goal. Requirements-management, bug tracking, source code control, and automated testing tools, for example, have their place in many offices.
One helpful tool that you may not have considered is a code generation tool. In this article, I'll show you some of what's available in that category for developers who use the Microsoft .NET platform. Depending on your needs and your applications, you may find that you can automate large sections of code that you're used to writing by hand.
Everyone's doing it
Let me quickly dispel the notion that code generation is strictly for inexperienced developers or those who don't really know what they're doing. In fact, if you're using any modern IDE, you're already using code generation tools, though often they're not explicitly labeled that way.
For example, when you add a new Windows form to a C# application, Visual Studio .NET generates 69 lines of code for you to handle the basics of referencing the appropriate libraries, declaring a namespace, instantiating and disposing of the form, and so on. Sure, you could write the equivalent code by hand, but why would you?
Visual Studio .NET features other code generators that are even more hidden. For example, what happens when you add a typed DataSet to your C# application and then drag a table to the XSD designer? The IDE automatically builds a class for you, based on the information in the designer.
Click the Show All Files button on the Solution Explorer toolbar to see the class. Even for a relatively simple DataSet (for example, one based on the sample Northwind Customers table that comes with Microsoft Access), you'll find that VS.NET generates 650 lines of code that you don't need to write yourself.
One of the great things about the .NET environment is that it's very easy to automate. There are well-documented ways to plug additional code generation tools into Visual Studio .NET, and many vendors have taken advantage of these hooks.
I can't possibly describe every .NET code generation tool in one short article, but I can give you a look at a few interesting ones. One way to think about code generation tools is by the amount of code they generate. In this article, I'll look at three broad categories:
- Simple code generators that build one or a few objects
- Data access layer generators that tie your application to a database
- Application generators that build a full solution
Depending on your needs, each of these types may have a place in your toolbox.
Simple code generators
As an example of the sort of problem that code generators can help you solve, consider the common requirement to maintain a collection of instances of a class. The .NET Framework provides classes such as System.Collections.HashTable and System.Collections.SortedList to make creating a collection very easy. But these classes only contain raw objects. That means that if you use, say, a SortedList to contain Customer objects, you'll be constantly casting back and forth from Customer to Object. Worse, there's no protection against accidentally storing an Order object in the list of customers.
Of course, you can derive your own class, say CustomerSortedList, from the base SortedList class and override all of its methods so that they explicitly take a Customer object. But why should you do all that work?
Enter .NET CollectionGen from Chris Sells. This code generator is implemented as a custom tool that integrates with Visual Studio .NET, just like the built-in DataSet designer. After you install CollectionGen, all you need to do is define your needs in a simple XML file:
<?xml version="1.0" encoding="utf-8" ?>
<typeSafeCollections>
<typeSafeCollection>
<templateKind>SortedList</templateKind>
<keyType>string</keyType>
<itemType>Customer</itemType>
<collectionName>CustomerSortedList</collectionName>
<collectionNamespace>MyCollections</collectionNamespace>
</typeSafeCollection>
</typeSafeCollections>
Set the Custom Tool property of the file to SBCollectionGen, save your project, and you'll get the desired class. For instance, the generated class will implement a Contains method that takes a string rather than an Object as a key:
Public Overridable Function Contains(ByVal key As string) As Boolean
' Determines whether the CustomerSortedList contains a specific key.
' Inputs:
' key = The key to locate in the CustomerSortedList.
Return (IndexOfKey(key) >= 0)
End Function
This is a typical pattern when using a code generator. Rather than write the code, you supply metadata defining the code that you'd like to have written (here, the template to use, the data types for the key and item, and the name and namespace for the collection). Based on this metadata, the code generator builds the code for you. In this case, you trade writing 10 lines of metadata for over a thousand lines of code.
CollectionGen is very tightly targeted to a single task: building type-safe collections. For a more flexible tool, take a look at Eric J. Smith's CodeSmith. CodeSmith uses its own syntax (very similar to that of ASP.NET pages) for templates. Here's a tiny piece of a template to generate SQL stored procedures:
<%@ Property Name="SourceTable" Type="RedRiver.SchemaExplorer.TableSchema" Category="Context" Description="Table that the stored procedures should be based on." %>
<%@ Property Name="IncludeDrop" Type="System.Boolean" Default="True" Category="Options" Description="If true drop statements will be generated to drop existing stored procedures." %>
<%@ Property Name="IncludeInsert" Type="System.Boolean" Default="True" Category="Options" Description="If true insert statements will be generated." %>
At runtime, CodeSmith translates this syntax into the user interface shown in Figure A. You then fill in each property specified in the template file and click the Generate button. CodeSmith uses the information you enter together with the rest of the template (which can contain quite complex logic) to generate the code. Although it can take a while to understand how it really works, CodeSmith ends up being a general-purpose tool to generate code in any language you can think of.
Building the data access layer
A large number of applications depend on moving data from a database to a user interface and vice versa. Indeed, it seems reasonable that the majority of business applications are concerned with manipulating databases. It's not surprising, then, that there are many products out there to make it easier to connect a database to a user interface.
One product in this category is ORM.NET from Olero Software. With data access layer generation, typically you select metadata by interacting with a database rather than entering it by hand. Figure B shows ORM.NET in action. After connecting to a database, you can use the ORM.NET interface to investigate the objects in the database and set properties that customize the generated code.
After setting options, you just click the Generate Data Layer button and specify a folder for the generated files. ORM.NET builds an entire Visual Studio .NET solution with a class library for data access and a test application. You can use the class library in any other application to abstract the entire database to objects, as shown here:
DataManager dm = new DataManager(Config.Dsn);
Customers c = dm.NewCustomers("DC Company", "DCCOM");
c.City = "Endicott";
c.Region = "Washington";
dm.CommitAll();
The major benefit of a product like ORM.NET is to take tricky but routine code for data access and hide it. You don't need to be a SQL or ADO.NET expert to use the generated classes to retrieve data from the database or add new data to it. All you need to do is understand the interface that ORM.NET builds for you.
Other products that specialize in generating data access layers include OlyMars, TierDeveloper, and LLBLGen.
Applications at the click of a button
If generating a data access layer is good, how much better would it be to create an entire application without writing any code? You can find out the answer by using application generators, which are typically the most complex (and expensive) of code generation products.
For example, Figure C shows part of the Application Builder in CodeCharge Studio 2.0. CodeCharge is typical of application builders in that you select a database connection, pick the tables you care about, decide which forms to build for each table, and choose a visual theme. The tool then generates everything you need to form a complete ASP.NET application (CodeCharge can also target other platforms such as Cold Fusion).
CodeCharge Studio goes beyond some other application generators in that it provides its own IDE to let you further edit the application's code after creation. When you're satisfied with the results, you publish the project to your Web server, and CodeCharge creates all of the necessary pages and class files.
Other tools in this category include DeKlarit and Dataphor.
So, is it for you?
If you think about the entire spectrum of code-generation tools, there are clear trade-offs between how much code the tool writes for you and how general-purpose that code is. At one extreme, you have the simple code generators that can automate the grunt work of things like collection classes. You can use a tool like CodeSmith to automate just about any repetitive programming task, but you'll need to put the classes together into an application yourself.
At the other end of the spectrum are tools such as CodeCharge Studio, which is great for building typical line of business applications that take a database to a Web user interface, but doesn't offer the flexibility of a general-purpose programming language. The more code the tool generates, the more you'll need to be sure that its end result is what you want.
Some developers seem to be prejudiced against all code generation tools, insisting that they can write better code by hand. While that may be true, you need to be very careful how you define "better." Remember, the goal is to deliver working applications to your clients as quickly as possible. There are no brownie points in general for delivering elegant source code, or source code that runs in the least possible space, or perfectly optimized source code.
With the exception of some limited realms of programming (such as development for embedded devices), it's often preferable to ship slightly suboptimal code today, as opposed to waiting for perfect code tomorrow. Choosing the correct code generator can help you meet that goal. | http://www.techrepublic.com/article/code-generators-help-you-deliver-high-quality-code-quickly/ | CC-MAIN-2017-09 | refinedweb | 1,778 | 55.24 |
Timeline
Jan 28, 2010:
- 9:42 AM Changeset [5177] by
- Make area unit tests actually test against known good values
- 7:51 AM Changeset [5176] by
- revert r5175 commit about points results on #304. Related to #395
- 7:28 AM Changeset [5175] by
- In regress/tickets* Add missing srid 32702 and 32602. Add results from …
- 7:09 AM Changeset [5174] by
- Fix 'maintainer-clean' rule
- 6:43 AM Ticket #396 (GCC warning - shp2pgsql) created by
- […] […]
- 6:37 AM Ticket #395 (Make check errors on Mac - spheroid area - srid 32702) created by
- Cunit error: Test: test_spheroid_area() ... FAILED 1. …
- 6:23 AM Changeset [5173] by
- Fix astyle.sh script so that if astyle cannot be found then it …
- 5:37 AM Ticket #386 (Within Function gives wrong result, Intersection threw an error.) closed by
- invalid: Okay i found the error its my fault.…
- 5:07 AM Ticket #394 (Add "make astyle" to trunk to format according to style guidelines) closed by
- fixed: Initial version committed as r5172.
- 5:07 AM Ticket #394 (Add "make astyle" to trunk to format according to style guidelines) created by
- By implementing "make astyle" as a fixed script, it makes it possible …
- 4:19 AM Changeset [5172] by
- Add "make astyle" target to clean up source tree formatting as per the …
- 1:21 AM OpenStreetMap edited by
- Fixed typos. (diff)
- 1:19 AM OpenStreetMap created by
- Added a page about the OpenStreetMap.
- 1:12 AM UsersWikiToolsSupportPostgis edited by
- Added a reference to the OSM2PostGIS project. (diff)
Jan 27, 2010:
- 1:22 AM Ticket #386 (Within Function gives wrong result, Intersection threw an error.) reopened by
- Sorry, i beleve that at least the Polygon for cuxhaven is valid. I …
Jan 26, 2010:
- 3:35 PM Ticket #386 (Within Function gives wrong result, Intersection threw an error.) closed by
- invalid: These polygons are invalid […]
- 1:44 PM Ticket #393 (shp2pgsql returns "fseek(-xxx) failed on DBF file." for large (>2GB) ...) created by
- Running shp2pgsql on large files fails when the .DBF is over 231 …
- 1:10 PM Changeset [5171] by
- Make GEOS test insist on >= 3.1.1
- 12:20 PM Changeset [5170] by
- Remove warning from lwline
- 11:30 AM Ticket #390 (ST_AddMeasure to change all the measures on a feature at once) closed by
- fixed
- 11:08 AM Changeset [5169] by
- Add example for ST_AddMeasure on multilinestring
- 10:56 AM Changeset [5168] by
- Make ST_AddMeasure handle multilinestrings as well as linestrings.
- 9:24 AM Changeset [5167] by
- Remove unneeded See Also section.
- 9:09 AM Changeset [5166] by
- Remove ST_StartMeasure ST_EndMeasure
- 5:40 AM Ticket #392 (st_locate_between measures built on deprecated) created by
- Just noticed that our […] This I think should be using …
Jan 25, 2010:
- 5:13 PM Changeset [5165] by
- Ignore postgis_comments.sql
- 1:08 PM Changeset [5164] by
- Replace soft tabs with hard.
- 1:06 PM Changeset [5163] by
- Add uninstall recipe for AddMeasure? (#390)
- 1:03 PM Changeset [5162] by
- Add ST_AddMeasure and associated documentations (#390)
- 4:53 AM Ticket #384 (documentation and clearifying of ~= change) closed by
- fixed: I don't think our SVN settings allow back commenting, since I tried …
Jan 24, 2010:
Jan 23, 2010:
- 3:31 PM Changeset [5160] by
- Tiny Typo
- 3:29 PM Changeset [5159] by
- remove ST_Maxdistance from TODO and note that C-version is still TODO …
Jan 22, 2010:
- 4:47 PM Ticket #391 (Unify Concept of "Edge") created by
- Right now, we have curves and lines, the "only" difference between …
- 2:51 PM Ticket #390 (ST_AddMeasure to change all the measures on a feature at once) created by
- […]
- 2:49 AM WKTRaster/SpecificationWorking01 edited by
- Typos (diff)
- 2:33 AM Ticket #350 ([wktraster] Premature use of geometry_samebox and geometry_gist_sel ...) closed by
- fixed: Done in r5158
- 2:32 AM Changeset [5158] by
- geometry_gist_joinsel replaced with postgis_gist_joinsel to keep …
Jan 21, 2010:
- 10:34 PM WKTRaster/SpecificationWorking01 edited by
- (diff)
- 10:21 PM Changeset [5157] by
- Getting the file import loop sorted.
- 10:20 PM WKTRaster/SpecificationWorking01 edited by
- (diff)
- 10:05 PM Changeset [5156] by
- Add note on removing milestone from trac
- 10:03 PM Milestone PostGIS 1.3.6 completed
-
- 7:10 PM Changeset [5155] by
- Adding a list-based multi-file selection.
- 7:06 PM Changeset [5154] by
- Creating a new spike for play.
- 5:02 PM Changeset [5153] by
- Removing a dead spike.
- 8:45 AM Changeset [5152] by
- Update version number in tag 1.5.0rc1
- 8:44 AM Changeset [5151] by
- Tag rc1
- 8:44 AM Changeset [5150] by
- Updates for 1.5.0rc1
- 5:08 AM Changeset [5149] by
- add missing comment
Jan 20, 2010:
- 11:28 PM Ticket #389 (Can't make check under MingW) closed by
- fixed: OK, committed at r5148. My first ever commit to the trunk :-)
- 11:19 PM Changeset [5148] by
- Fix for make check on MingW #389
- 5:14 PM Ticket #389 (Can't make check under MingW) created by
- Nicklas patch worked for me so waiting for him to close this out after …
- 5:13 PM Ticket #311 (Rename postgis.sql to postgis-1.5.sql) closed by
- fixed: fixed after Mark's last change. The make check is a separate issue so …
- 4:35 PM Ticket #236 (Test Geoserver and Mapserver) closed by
- fixed: GeoServer? works for geometry types, but does not recognize geography …
- 4:06 PM Ticket #374 (Update release_notes.xml for 1.5) closed by
- fixed: Updated the release notes section at r5147
- 4:06 PM Changeset [5147] by
- Updated XML release notes (#374)
- 3:01 PM Ticket #295 ([wktraster] Rename RT_Raster_Envelope to ST_Envelope) closed by
- fixed: Function renamed in r5142, and fixed in r5146. Old rt_raster_envelope …
- 2:55 PM Changeset [5146] by
- Error in ST_Envelope fixed. Related ticket: #348
- 12:17 PM Changeset [5145] by
- Make proper #! calls to perl in perl scripts
- 12:16 PM Changeset [5144] by
- Make proper #! calls to perl in perl scripts.
- 10:55 AM Changeset [5143] by
- Add Jorge Arevalo to list since he's contributing a lot of work to WKT …
- 10:35 AM WKTRaster/PlanningAndFunding edited by
- (diff)
- 10:20 AM Changeset [5142] by
- Added ST_Envelope function. Related ticket: #348
Jan 19, 2010:
- 6:17 AM Changeset [5141] by
- Changed function's name: rt_raster_get_envelope now is …
- 4:40 AM Changeset [5140] by
- Add George, Guillaume, and Vincent to contributors list
- 4:37 AM Changeset [5139] by
- Bump Nicklas up since he's added a lot to this release and now has …
- 1:41 AM WKTRaster/SpecificationWorking01 edited by
- (diff)
- 1:41 AM WKTRaster/SpecificationFinal01 edited by
- (diff)
Jan 18, 2010:
- 2:37 PM Ticket #387 (ST_Transform decimal issue on Win32) closed by
- fixed
- 12:11 PM Ticket #388 (Find manual errata for spatial_ref_sys in history and save in source tree) closed by
- fixed: Done, reviewed history of spatial ref sys and found no other manual …
- 11:43 AM Ticket #388 (Find manual errata for spatial_ref_sys in history and save in source tree) created by
- Review all spatial_ref_sys commits and find manual changes to the …
- 11:41 AM Changeset [5138] by
- Add towgs84 line into proj4text for srid = 28992 (#387)
- 11:40 AM Changeset [5137] by
- Add towgs84 line into proj4text for srid = 28992 (#387)
- 9:29 AM Ticket #387 (ST_Transform decimal issue on Win32) created by
- On Win32, SELECT …
Jan 17, 2010:
- 11:29 AM Ticket #386 (Within Function gives wrong result, Intersection threw an error.) created by
- I have two boundarys , first one is Lower Saxony the second one is …
Jan 15, 2010:
- 8:26 PM Changeset [5136] by
- Add Guillaume's PostgreSQL 8.5 contribution
- 2:06 PM Ticket #350 ([wktraster] Premature use of geometry_samebox and geometry_gist_sel ...) reopened by
- geometry_gist_joinsel should also be replaced with postgis_gist_joinsel
- 11:48 AM Changeset [5135] by
- 80col wrap NEWS
- 10:49 AM Changeset [5134] by
- add note about GEOS 3.2
- 10:41 AM Changeset [5133] by
- Short circuit on distance tests: only do full spheroidal calculation …
- 10:08 AM Changeset [5132] by
- Update version number in tag
- 10:07 AM Changeset [5131] by
- Tag 1.5.0b2
- 10:06 AM Changeset [5130] by
- Prepare for 1.5.0b2
- 9:55 AM Ticket #385 (Make GEOS 3.1 the new minimum GEOS version) closed by
- fixed: Configure updated, and #defines scrubbed at r5129.
- 9:54 AM Changeset [5129] by
- Make GEOS 3.1 the mandatory minimum (#385)
- 9:47 AM Changeset [5128] by
- Ignore all PNG files.
- 9:31 AM Ticket #385 (Make GEOS 3.1 the new minimum GEOS version) created by
- update configure.ac and and #defines in the code
- 1:24 AM Ticket #384 (documentation and clearifying of ~= change) created by
- The change #282 in behavior of ~= operator from working as a fast …
- 12:13 AM Changeset [5127] by
- Round decimal part in #58 ticket unit test. As the previous result was …
Jan 14, 2010:
- 10:14 AM WKTRaster edited by
- (diff)
- 10:00 AM Changeset [5126] by
- trivia: XXX (or FIXME or TODO) tag to mark comments on issues and problems.
- 8:08 AM Changeset [5125] by
- Minor bug fixed: Makefile.in was using an nonexistent enviroment var …
- 7:07 AM Ticket #383 (Liblwgeom not compile with POSTGIS_DEBUG_LEVEL 4) closed by
- fixed: Ok, And yes here on a linux box make/make check are fine. I close …
- 6:45 AM Changeset [5124] by
- Fix undefined vars in LWDEBUGF (#383)
- 6:40 AM Ticket #383 (Liblwgeom not compile with POSTGIS_DEBUG_LEVEL 4) created by
- […] […]
- 12:34 AM Changeset [5123] by
- Update TODO. remove ST_GeomFromKML entry
Jan 12, 2010:
- 8:57 PM UsersWikiPostgreSQLPostGIS edited by
- (diff)
- 8:33 PM Ticket #380 (Add files to final tarball) closed by
- fixed: Gr8, closing.
- 3:21 PM Ticket #382 (PostGIS native VC++ / Express build) created by
- I'm not sure if this changes how we do things, but I suspect it does. …
- 8:54 AM Changeset [5122] by
- Added rt_band_new_offline function.
- 2:33 AM Changeset [5121] by
- Add missing MODULE_big section for #311 which was preventing the main …
- 12:23 AM Changeset [5120] by
- slight typo correction
- 12:18 AM Changeset [5119] by
- Add ST_DFullyWithin and add analysis as descriptor to functions
Jan 11, 2010:
- 8:28 PM Ticket #378 (Change ST_Equals to use && instead of ~=) closed by
- fixed: OK, I can buy that. Done at r5118
- 8:28 PM Changeset [5118] by
- Change ST_Equals to use && instead of ~= (#378)
- 8:24 PM Changeset [5117] by
- Shorten trac URL.
- 5:01 PM Changeset [5116] by
- Add comment about postgis_comments.sql handling in 'clean' target of docs
- 5:00 PM Changeset [5115] by
- Don't remove postgis_comments.sql when doing a 'make clean' in doc, …
- 4:25 PM Changeset [5114] by
- Performance tweak to distance calculations with tolerance. If distance …
- 1:12 PM Ticket #381 (Add an optional parameter to ST_Scale to specify the anchor point) created by
- ST_Scale is a simple wrapper around ST_Affine, but it's missing a very …
- 11:11 AM Ticket #380 (Add files to final tarball) created by
- From robe […]
- 9:31 AM Changeset [5113] by
- added missing liblwgeom target needed to build the documentation images
- 1:43 AM Ticket #379 (shp2pgsql-gui not corrrectly passing password) closed by
- invalid: Nevermind just tested with new compiled version 5096 and that doesn't …
- 1:22 AM Ticket #379 (shp2pgsql-gui not corrrectly passing password) created by
- Well I haven't tried the latest latest version but my 5094 is not …
Jan 10, 2010:
- 2:59 PM WKTRaster edited by
- (diff)
- 2:58 PM WKTRaster edited by
- Display active tickets on WKT Raster wiki page (diff)
- 8:38 AM Ticket #378 (Change ST_Equals to use && instead of ~=) created by
- This is sort of getting to what Mark was saying. The behavior is …
- 8:33 AM Ticket #377 (Move ST_AS* in liblwgeom directory) created by
- Move ST_As* from postgis to liblwgeom directory. Rewrite units tests …
- 8:25 AM Ticket #376 (Add ST_GeomFromGeoJSON) created by
- Same behaviour than other import functions, but related to GeoJSON. …
- 8:21 AM Ticket #375 (Add lwcollection_homogenize and ST_Homogenize) created by
- […] I need this stuff for ST_GeomFromKML, to be able to return …
Jan 9, 2010:
- 1:03 AM Ticket #311 (Rename postgis.sql to postgis-1.5.sql) reopened by
- Okay finally got around to testing and testing the 1.50.b1. This …
Jan 8, 2010:
- 7:05 PM Changeset [5112] by
- fix typo
- 7:05 PM Changeset [5111] by
- Fill in missing spots in News
- 4:10 PM Changeset [5110] by
- Use macro define to determine default geometry column name in gui
- 3:43 PM Changeset [5109] by
- Update version to 1.5.0b1
- 3:42 PM Changeset [5108] by
- Tag for beta1 release
- 3:41 PM Ticket #374 (Update release_notes.xml for 1.5) created by
- Read from NEWS and make a better set of release notes…
- 3:39 PM Changeset [5107] by
- Update the NEW file
- 3:21 PM Ticket #311 (Rename postgis.sql to postgis-1.5.sql) closed by
- fixed
- 3:20 PM Ticket #330 (Test upgrade and uninstall prior to release) closed by
- fixed: Tested upgrades from 1.3 and 1.4 and uninstall procedure, verified all …
- 3:16 PM Changeset [5106] by
- Added in one removed function (st_max_distance, replaced by …
- 2:48 PM Changeset [5105] by
- Override pgxs defaults for install, from mcayland (#311)
Jan 7, 2010:
- 8:04 AM Changeset [5104] by
- Apply a modified version of Guillaume Lelarge's patch to allow …
- 6:21 AM Ticket #227 ([wktraster] Add out-db support in gdal2wktraster.py script) closed by
- fixed: Sure. I've deleted the commented code, TODO comment included (r5103). …
- 6:19 AM Changeset [5103] by
- Deleted unnecessary and commented code (it was a test for out-db …
Jan 6, 2010:
- 5:18 AM Ticket #373 (Documentation syntax error in hard upgrade) created by
- The instruction in "2.7.2 Hard upgrade" - last sentence on how to …
Jan 5, 2010:
- 5:43 PM WKTRaster/PlanningAndFunding edited by
- Added new milestone: Objective 0.1.6g (diff)
- 5:38 PM WKTRaster/SpecificationWorking01 edited by
- I can't see the Objective 0.1.6f in TOC during preview. Is it normal? (diff)
- 2:57 PM WKTRaster/SpecificationWorking01 edited by
- (diff)
- 2:49 PM WKTRaster/SpecificationWorking01 edited by
- (diff)
- 2:48 PM WKTRaster/SpecificationWorking01 edited by
- (diff)
- 2:47 PM WKTRaster/SpecificationWorking01 edited by
- (diff)
- 1:49 PM WKTRaster/SpecificationWorking01 edited by
- (diff)
- 1:25 PM WKTRaster/SpecificationWorking01 edited by
- (diff)
- 1:17 PM WKTRaster/SpecificationWorking01 edited by
- (diff)
- 11:18 AM Changeset [5102] by
- Out-db raster support added. Ticket #227 solved.
Jan 4, 2010:
- 3:25 PM Changeset [5101] by
- Initailize config value from simple_geometries
- 11:52 AM Changeset [5100] by
- Bracked and reformat comparison to be more explicit
- 10:00 AM WKTRaster/SpecificationFinal01 edited by
- (diff)
- 9:55 AM Ticket #370 (lwgeom_free not empty safe) closed by
- fixed: Fixed up de-serialization routines to avoid *geoms = malloc(0) cases …
- 9:55 AM Changeset [5099] by
- Fixed up de-serialization routines to avoid *geoms = malloc(0) cases …
- 9:24 AM Ticket #361 (PostGIS 1.4 Release documentation still pointing at 1.4.0) closed by
- fixed: Done. - Built tagged 1.4.1 docs - Updated sym links.
- 1:03 AM Ticket #372 (shp2pgsql-gui Move About button to menu) created by
- move to a menu item as noted in #371.
- 1:01 AM Ticket #371 (Put the r... svn version on shp2pgsql-gui screen) closed by
- fixed: Paul, This is just what the doctor ordered. I find the About button …
Jan 3, 2010:
- 9:48 PM Ticket #367 (Make iconv compulsory) closed by
- fixed
- 9:47 PM Changeset [5098] by
- Remove the ifdef/endif blocks for HAVE_ICONV (#367)
- 9:42 PM Changeset [5097] by
- Make configure error out when iconv is unavailable. (#367)
- 9:21 PM Changeset [5096] by
- Minor change to about dialog build.
- 8:52 PM Ticket #356 (Get rid of logging of password in shp2pgsql-gui) closed by
- fixed: Yeah, I'm sure we had this fixed. I'm going to trace back and see …
- 8:52 PM Changeset [5095] by
- Re-fix connection password hiding (#356)
- 4:34 PM Changeset [5094] by
- Fix the RCSID to actually substitute
- 4:32 PM Changeset [5093] by
- Add an About dialogue that contains the revision string (hopefully)
- 4:31 PM Changeset [5092] by
- Make lwcollection_extract slightly more empty-intelligent
- 4:05 PM Ticket #356 (Get rid of logging of password in shp2pgsql-gui) reopened by
- Only seems to do it when I click test connection. I thought we had …
- 4:04 PM Ticket #369 (shp2pg-gui the geometry column setting not sticking) closed by
- fixed: Okay works, but I see my password again when I click test connection. …
- 3:52 PM Ticket #371 (Put the r... svn version on shp2pgsql-gui screen) created by
- If its not too much trouble, can we have the r... version on the …
- 3:05 PM Changeset [5091] by
- Separate the options config persistence from the main persistence …
- 10:21 AM Ticket #370 (lwgeom_free not empty safe) created by
- […] Crashes server.
- 10:13 AM Ticket #369 (shp2pg-gui the geometry column setting not sticking) created by
- This is again testing my 12/31/ build so perhaps its been fixed since …
- 10:11 AM Ticket #368 (Geography showing cryptic type) created by
- I hope this has been fixed since. I just got around to stress testing …
Jan 2, 2010:
- 12:17 AM Changeset [5090] by
- Add initialization to fix one Win32 segfault.
Jan 1, 2010:
- 11:01 PM Changeset [5089] by
- Add getopt.o into the modules used by shp2pgsql-gui.exe
- 10:57 PM Changeset [5088] by
- Flip back to pgis_getopt
- 12:28 PM Changeset [5087] by
- Change log entry to reflect actual iconv target encoding (UTF-8, not UTF8)
- 12:05 PM Ticket #367 (Make iconv compulsory) created by
- * Remove ifdef blocks * Ensure configure blows chunks if iconv not found
- 11:44 AM Changeset [5086] by
- amend upgrade instructions to include description postgis_upgrade*.sql
- 11:30 AM Changeset [5085] by
- put in ?, -n and -N missing from loader list
- 2:56 AM UsersWikiWinCompile edited by
- (diff)
- 2:54 AM UsersWikiWinCompile edited by
- (diff)
- 2:52 AM UsersWikiWinCompile edited by
- (diff)
- 2:51 AM UsersWikiWinCompile edited by
- (diff)
Dec 31, 2009:
- 4:41 AM Changeset [5084] by
- minor change
- 4:35 AM Ticket #366 (Add append/prepare/overwrite option to PostGIS gui) created by
- I just noticed the c|a|d|p options are missing in the gui. So I …
- 3:56 AM Changeset [5083] by
- amend shp2pgsql section to mention gui loader and also -G geography switch
Dec 30, 2009:
- 7:31 AM Changeset [5082] by
- change wording in what is new titles to reflect they show both new and …
- 7:12 AM Changeset [5081] by
- Fix ST_Extent/ST_Expand docs to reflect change in behavior of …
- 6:52 AM Changeset [5080] by
- Fix ST_Envelope() and ST_Expand() so that they use double precision …
- 5:08 AM Changeset [5079] by
- ST_Box back to Box link ref
- 4:55 AM Changeset [5078] by
- Add some faqs I'm tired of answering
- 4:53 AM Changeset [5077] by
- oops revert change I guess ST_Box .. is the one that's deprecated. …
- 4:48 AM Changeset [5076] by
- amend faqs and change Box2D,Box3D to ST_Box…
- 4:20 AM Changeset [5075] by
- try to fix buildbot
- 1:15 AM Changeset [5074] by
- correct example
Dec 29, 2009:
- 11:22 PM Ticket #351 (Doc bug: Wrong return type for ST_Envelope()) closed by
- fixed: Fixed at r5070 - r5073 (also added an example which hopefully …
- 11:20 PM Changeset [5073] by
- more clarity on the float4/float8 for ST_Envelope
- 11:19 PM Changeset [5072] by
- more clarity on the float4/float8 for ST_Envelope
- 10:53 PM Changeset [5071] by
- #531 ST_Envelope has wrong return type changed from boolean to geometry
- 10:53 PM Changeset [5070] by
- #531 ST_Envelope has wrong return type changed from boolean to geometry
- 10:47 PM Ticket #365 (Document ST_GeogFromWKB and ST_GeogFromText) closed by
- fixed: fixed at r5066
- 10:45 PM Changeset [5069] by
- slight wording change
- 10:44 PM Changeset [5068] by
- fill in mising geography = operator
- 10:38 PM Changeset [5067] by
- fix typo
- 10:12 PM Changeset [5066] by
- #365 document ST_GeogFromWKB and ST_GeogFromText
- 5:27 PM Ticket #360 (st_geographyfrombinary is inconsistently named) closed by
- fixed: OK, changed to ST_GeogFromWKB() and also added ST_GeogFromText() alias …
- 5:26 PM Ticket #365 (Document ST_GeogFromWKB and ST_GeogFromText) created by
- As altered in r5065
- 5:25 PM Changeset [5065] by
- Rename ST_GeographyFromBinary to ST_GeogFromWKB. Add ST_GeogFromText …
- 5:20 PM Ticket #364 (Options NULL Policy Field is Obscure) closed by
- fixed: Removed the null policy line from the options dialog (r5064)
- 5:20 PM Changeset [5064] by
- Remove the NULL policy line from the GUI options (#363)
- 5:12 PM Changeset [5063] by
- Make a few things more explicit in the handling of encoding.
- 12:23 PM Changeset [5062] by
- Remove a couple compiler warnings following last change.
- 12:16 PM Changeset [5061] by
- Change options dialogue into actual GTK dialog and move to …
- 11:38 AM UsersWikiPostgisOnUbuntu edited by
- (diff)
- 11:28 AM Ticket #359 (Issue with gui when loading some files) closed by
- fixed: Remaining issues ticketed (separately!!) in #363 and #364.
- 11:27 AM Ticket #364 (Options NULL Policy Field is Obscure) created by
- The null policy needs to be changed into a dropdown. From Nik: …
- 11:26 AM Ticket #363 (GUI segfaults after iconv error during load) created by
- From Nik: One thing I discoverd now. If I close the options window …
- 11:23 AM Changeset [5060] by
- Try and get around the expanding window problem
- 7:19 AM UsersWikiPostgisOnUbuntu edited by
- (diff)
- 7:16 AM UsersWikiPostgisOnUbuntu edited by
- (diff)
- 12:52 AM Changeset [5059] by
- Add a filter name to the shapefile file selector; this is just a …
- 12:35 AM Changeset [5058] by
- Restrict SQL to only 255 characters when displaying erroneus SQL in …
Note: See TracTimeline for information about the timeline view. | http://trac.osgeo.org/postgis/timeline?from=2010-01-28T05%3A37%3A15-0800&precision=second | CC-MAIN-2016-30 | refinedweb | 3,646 | 53.04 |
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi,
Thanks in advance for your help. I am a beginner in Processing and in need of urgent advice. I need webcam to output frames into a second window, which I am using G4P library for. However, myCapture.read() either gets stuck in a frame or the fps count is very low so the video feed is not smooth. The draft code I tried is below:
import processing.video.*; import g4p_controls.*; Capture myCapture; private GWindow window2; GWinData data2; void setup() { size(640, 480); // The name of the capture device is dependent on // the cameras that are currently attached to your // computer. To get a list of the // choices, uncomment the following line println(Capture.list()); data2 = new GWinData(); window2 = new GWindow(this, "web cam", 0,0, width,height, true, OPENGL); window2.setActionOnClose(G4P.CLOSE_WINDOW); //window2.setResizable(true); //window2.addData(data2); window2.addDrawHandler(this, "Window2draw"); print("debug"); // To select the camera, replace "Camera Name" // in the next line with one from Capture.list() myCapture = new Capture(this, width, height, "FaceTime HD Camera (Built-in)", 30); // This code will try to use the camera used //myCapture = new Capture(this, width, height, 30); print("debug1"); myCapture.start(); } void Window2draw(GWinApplet b, GWinData d){ if(myCapture.available()) { myCapture.read(); b.image(myCapture, 0, 0); } } void draw() { if(myCapture.available()){ myCapture.read(); image(myCapture, 0, 0); } }
When I use 3 windows, the problem only gets worse and the camera freezes on the first frame. This is true for both the internal (Built in) and external logitech webcam. Im using Processing 2.0+ on Mac btw.
Thanks. BTW, G4P has been very helpful for this application.
Answers
I have never tried using Capture with Video library so I have had a play with your code and I have a number of comments.
Comment 1
The second window is defined with the OPENGL renderer but since you are only displaying a bitmap image this is over the top and I would use JAVA2D.
Comment 2
Do not make a GWindow resizeable, I am pretty certain it won't work properly but by all means try it. Also does the second window size have to be the same size as the main window or the same size as the video capture 8->
Comment 3
If you want each GWindow to have its own set of attributes then you need to create a class that extends GWinData and add attributes to that. See the G4P_WindowStarter example and visit this webpage to find out more. If your GWindows don't need their own data then don't use GWinData - simply ignore it.
Comment 4
This is the biggy, the one you have been waiting for. You have defined a capture
myCapturewhich will refresh 30 times a second. Now when myCapture.available returns true then it will read the image. While reading the image
myCaptureis no longer available. It means that the 30fps are shared by the two windows and since the draw method has priority the main window gets most of them and the GWindow gets very few. This will be made worse when another GWindow is added. There are two solutions - the first (see code below) simply displays the captured video in the GWindow so its gets all 30fps. The second approach (not discussed here) is only needed if you want the same video to be displayed in more than one window then you need a more sophisticated approach.
When I ran the code below on my iMac I got 60fps in both windows :)
Comment 1- Yea I was just playing around with the other settings to see if they would have an impact. I will change it to JAVA2D.
Comment 2/ 3- The resizeable option wasn't working to begin with so I will remove that. I will also remove the unneeded data. The two windows will not have different attributes.
Comment 4- Thank you. So I better understand how it works now. What I need basically is for one window to play a slideshow of pics, and another window to display photos of from webcam so I can screenshot it at certain times. I currently has a workable draft. draw() uses webcam feed and the GWindow plays the slideshow. Do you think this is the most reliable way of going about it? i need to make sure the webcam and slideshow matches up and no delay is created.
Also, just out of curiosity, what would be your second approach? you dont need to code it if it will take time, just a brief explanation would do :)
Thanks.
I assume you mean that one window is used to display a series of separate individual images (e.g. PImage objects) and the other window to display the webcam output (e.g. video)
In my example code I display the webcam output in the secondary window (GWindow) and the animation in the main window but I see no reason why you can't swap these. I suspect that it is important that the framerate for the webcam window is greater than the capture speed for the webcam i.e. > 30fps. The harder part will be to time the slide show so it syncs with the video.
The trick here is to store the captured image in a buffer (PImage) outside of any draw method and then display the buffer in any window we like.
The code below shows the video output in 3 windows (each window is running at ~60fps at least on my machine)
Yes, the hardest part has been getting the timing right. I have been trying it with flags and delay() so just a bit of tweaking is necessary. I think for the most part I got the pics to synchronize.
And I haven't looked at pre() but thanks! I will check up on the documentation to see if it fits my project.
Appreciate all the help :)
I wouldn't use delay() - there are numerous discussions on the forum using millis() to create a timer/watch type class for timing events. I suggest you search for a few.
Although this is not exactly what you need it shows how millis can be used.
Yea my timer uses millis() but delay() helps to synchronize it a bit. But I also read on another forum not to use it so i will tweak it with millis(). Your post was helpful. Thanks.
a good Timer class that I came across, if anyone reading this is interested- | https://forum.processing.org/two/discussion/comment/21157/ | CC-MAIN-2020-34 | refinedweb | 1,097 | 72.26 |
please change the java.swing to javax.swing..
Post your Comment
Java package,Java Packages
.
Packages in Core Java
Package
Description...
Java Package
Introduction to Java Package
A Java package is a mechanism for organizing a group
packages - Java Beginners
Java package creation example What is Package in Java? How can i create a package in Class
packages
packages how to work with packages in java?
Have a look at the following links:
packages
packages when i run a simple program on package it shows error
my program is
package world;
public class HelloWorld {
public static void main...");
it compiles succesfully
but when i do
c:\world>java world.HelloWorld
packages
packages how to save program created by sub package method
Hi...doubt on Packages - Java Beginners
Package in java..
I have downloaded one program on Password Authentication... ..Explain me. Hi friend,
Package javax.mail
The Java Mail API allows the developers to add mailing functionalities to their java applications
package in java
package in java when i run a package it give a error exception in thread "main"
java.lang.NoClassDefFoundError what i do
add new package java
add new package java How to add new package in Java
package - Java Beginners
Creating a package in Java Create a package called My Package. In this, create a class call Marks that specifies the name of student, the marks in three subjects and the total of these marks. Displays the details of three
Package in Java - Java Beginners
Package in Java Hi,
What is a package? Tell me how to create package?
Thanks
Hello,
packeage is nothing but you can say that folder of related java files.
ex,
if you write a jaava class like
Java packages
Java packages What restrictions are placed on the location of a package statement within a source code file
Java Util Package - Utility Package of Java
Java Util Package - Utility Package of Java
Java Utility package is one of the most commonly used packages in the java
program. The Utility Package of Java consist
sun.reflect.Reflection Package - Java Tutorials
sun.reflect.Reflection -
Package
2004-04-09 The Java Specialists....
Welcome to the 87th edition of The Java(tm) Specialists' Newsletter. We have... to not
have our traditional "April Fools" Java newsletter. However, I
Packages - Defining
Java NotesPackages - Defining
Package = directory. Multiple classes of larger programs are usually grouped
together into a package. Packages correspond...
into packages, but usually you won't define more than one package.
Summary of how many
Packages needed for JDBC in Linux
Packages needed for JDBC in Linux Can anyone tell me the packages needed to run a program with JDBC in Red Hat 5
regarding java package - Java Beginners
regarding java package can you provide tutorial for java.sql package
please help Hi friend,
I am sending you a link. This link will help you.
Please visit for more information.
errorrahul verma November 29, 2011 at 10:10 AM
please change the java.swing to javax.swing..
Post your Comment | http://www.roseindia.net/discussion/32262-Java-package-Java-Packages.html | CC-MAIN-2014-10 | refinedweb | 502 | 57.16 |
the trailboss abuses his CodeRanch power for his other stuff (power corrupts. absolute power
corrupts absolutely
is kinda neat!)
Programming Diversion 2b: Applying a hat
Jason Menard
Sheriff
Joined: Nov 09, 2000
Posts: 6450
posted
Sep 18, 2002 08:48:00
0
I was hoping these would generate more interest. On the other hand MD is probably not the best forum to try to get up a discussion on programming. Now if that algorithms forum had ever appeared as discussed...
Anyway I will continue for now and post the second part for Programming Diversion 2. If you recall in
Programming Diversion 2a
we discussed producing a cipher by applying a key to it. Admittedly that was fairly trivial. It gets a little more complicated (and therefore more fun to program) when we apply a
hat
to cipher to get a new one. The purpose of the hat is to re-order the cipher to jumble it up some more.
Like a key, a hat is simply a word. We place our cipher under this word, wrapping to the next row every n characters, where n is the length of the hat. After this we will end up with n columns of letters. We then derive a numeric sequence from the hat by giving each letter in the hat a number which equates to it's rank if the hat were sorted. Duplicate letters are kept, being ranked according to which appears first in the hat.
This is kind of confusing so let me show you what I mean. Let's say our hat is "ranch" and we want to get a sequence from it. If we sorted "ranch" we would get "achnr", so assigning a rank to each letter means a=1, c=2, h=3, n=4, and r=5. Looking back at our unsorted hat and applying these ranks, we see the sequence for the hat "ranch" is 51423. We can see this better if we write the sequence over the hat.
<pre>
51423
ranch
</pre>
If the hat were "java", our sequence would be 3142, with the first "a" that appears being given a rank of 1, and the second "a" that appears being given a rank of 2.
Remember I said we that to apply the hat we need to place our cipher (which we got from applying a key to the plaintext alphabet) uner it. Let's assume for now that our cipher is just the plaintext alphabet "abcdefghijklmnopqrstuvwxyz", and our hat is "ranch", we will now arrange our cipher under our hat like this:
<pre>
51423
ranch
=====
abcde
fghij
klmno
pqrst
uvwxy
z
</pre>
To get our final cipher, we pull each column of letters in rank order and
string
them together to form our cipher. So we will first pull the column of letters under the "a" in "ranch", then we will pull the column under the "c", etc... This gives us: bglqv + dinsx + ejoty + chmrw + afkpuz = bglqvdinsxejotychmrwafkpuz.
If we applied a key of "java" to the plaintext alphabet our resulting cipher is "javbcdefghiklmnopqrstuwxyz". If we then apply a hat of "ranch" to that cipher we end up with a new cipher "aekpubgmrxchnsyvflqwjdiotz". It's actually pretty simple once you work out a couple for yourself.
=============
The Challenge
=============
Given a String representing an input alphabet/cipher, apply a hat to it, returning the new cipher.
Here's our shell of a class as we layed out in Diversion 2a, adding an accessor and mutator for the "hat" attribute, and making slight changes to encrypt() and main(). I also included my applyKey() method although if you did 2a you can use your own. You will need to complete the applyHat() method.
import java.util.Arrays; public class Encryptor { public static final String PLAINTEXT_ALPHABET = "abcdefghijklmnopqrstuvwxyz"; private String cipher; private String key; private String hat; private int offset; private String plaintext; private String ciphertext; public String getCipher() { return cipher; } public String getHat() { return hat; } public void setHat(String hat) { this.hat = hat; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public void encrypt() { cipher = applyHat(applyKey(PLAINTEXT_ALPHABET)); } // apply a hat to an alphabet, returning the resulting cipher public String applyHat(String alphabet) { // complete this method } // apply a key to an alphabet, returning the resulting cipher private String applyKey(String alphabet) { StringBuffer temp = new StringBuffer(); if (key == null || key.length() < 1) return alphabet; // truncate key by removing duplicate characters for (int i = key.length() - 1; i >= 0; i--) { String next = key.substring(i, i + 1); if (key.indexOf(next) == i) temp.insert(0,next); } char[] truncatedKey = temp.toString().toCharArray(); StringBuffer tempCipher = new StringBuffer(alphabet); // remove key letters from alphabet and insert truncated key to form cipher for (int i = 0; i < truncatedKey.length; i++) { int j = tempCipher.toString().indexOf(truncatedKey[i]); tempCipher.deleteCharAt(j); } tempCipher.insert(0, truncatedKey); return tempCipher.toString(); } public static void main(String[] args) { long start = System.currentTimeMillis(); Encryptor e = new Encryptor(); e.setKey("java"); e.setHat("ranch"); e.encrypt(); long stop = System.currentTimeMillis(); System.out.println("Cipher: " + e.getCipher()); System.out.println("Time: " + (stop - start)); } }
Jessica Sant
Sheriff
Joined: Oct 17, 2001
Posts: 4313
I like...
posted
Sep 18, 2002 14:16:00
0
I'm interested... its just takin me a lil longer to figure out the algorithms for 1 and 3.
Maybe
Java
In General (Advanced) would be a better forum for the Programming Diversions rather than MD? Unless of course... that forum that we talked about gets created.
I just posted my key functionality for 2a, here goes 2b.
Jason Menard
Sheriff
Joined: Nov 09, 2000
Posts: 6450
posted
Sep 23, 2002 09:07:00
0
Thanks for the feedback Jessica. Maybe some kind moderator would like to move these to a forum they feel is more appropriate?
Anyway, here is the applyHat() method.
private String applyHat(String alphabet) { if (hat == null) { return alphabet; } char[] alphaArray = alphabet.toCharArray(); char[] sortedHatArray = hat.toCharArray(); Arrays.sort(sortedHatArray); int[] order = new int[hat.length()]; StringBuffer sortedHat = new StringBuffer(new String(sortedHatArray)); for (int i = 0; i < hat.length(); i++) { int index = sortedHat.toString().indexOf(hat.substring(i,i+1)); sortedHat.setCharAt(index,' '); order[i] = index; } char[] cipherArray = new char[alphaArray.length]; int rows = alphaArray.length / hat.length(); int mod = alphaArray.length % hat.length(); for (int i = 0; i < hat.length(); i++) { int col = order[i]; int count = rows; if (i < mod) count++; int additive = 0; for (int x = 0; x < order.length; x++) { if (order[x] < col) { additive += rows; if (x < mod) additive++; } } for (int j = 0; j < count; j++) { int k = i + (j*hat.length()); int cipherIndex = additive + j; cipherArray[cipherIndex] = alphaArray[k]; } } return new String(cipherArray); }
I agree. Here's the link:
subject: Programming Diversion 2b: Applying a hat
Similar Threads
Problem with char/string representation
Puzzle
Programming Diversion 2a: Applying a Key
javax.crypto.BadPaddingException: Given final block not properly padded
Crypto Challenge Instructions
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/37591/md/Programming-Diversion-Applying-hat | CC-MAIN-2014-49 | refinedweb | 1,166 | 64.61 |
iBATOR - Introduction
iBATOR is a code generator for iBATIS. iBATOR introspects one or more database tables and generates iBATIS artifacts that can be used to access the tables.
Later you can write your custom SQL code or stored procedure to meet your requirements. iBATOR generates the following artifacts −
- SqlMap XML Files
- Java Classes to match the primary key and fields of the table(s)
- DAO Classes that use the above objects (optional)
iBATOR can run as a standalone JAR file, or as an Ant task, or as an Eclipse plugin. This tutorial describes the simplest way of generating iBATIS configuration files from command line.
Download iBATOR
Download the standalone JAR if you are using an IDE other than Eclipse. The standalone JAR includes an Ant task to run iBATOR, or you can run iBATOR from the command line of Java code.
You can download zip file from Download iBATOR.
You can check online documentation − iBATOR Documentation.
Generating Configuration File
To run iBATOR, follow these steps −
Step 1
Create and fill a configuration file ibatorConfig.xml appropriately. At a minimum, you must specify −
A <jdbcConnection> element to specify how to connect to the target database.
A <javaModelGenerator> element to specify the target package and the target project for the generated Java model objects.
A <sqlMapGenerator> element to specify the target package and the target project for the generated SQL map files.
A <daoGenerator> element to specify the target package and the target project for the generated DAO interfaces and classes (you may omit the <daoGenerator> element if you don't wish to generate DAOs).
At least one database <table> element
NOTE − See the XML Configuration File Reference page for an example of an iBATOR configuration file.
Step 2
Save the file in a convenient location, for example, at: \temp\ibatorConfig.xml.
Step 3
Now run iBATOR from the command line as follows −
java -jar abator.jar -configfile \temp\abatorConfig.xml -overwrite
It will tell iBATOR to run using your configuration file. It will also tell iBATOR to overwrite any existing Java files with the same name. If you want to save any existing Java files, then omit the −overwrite parameter.
If there is a conflict, iBATOR saves the newly generated file with a unique name.
After running iBATOR, you need to create or modify the standard iBATIS configuration files to make use of your newly generated code. This is explained in the next section.
Tasks After Running iBATOR
After you run iBATOR, you need to create or modify other iBATIS configuration artifacts. The main tasks are as follows −
- Create or modify the SqlMapConfig.xml file.
- Create or modify the dao.xml file (only if you are using the iBATIS DAO Framework).
Each task is described in detail below −
Updating the SqlMapConfig.xml File
iBATIS uses an XML file, commonly named SqlMapConfig.xml, to specify information for a database connection, a transaction management scheme, and SQL map XML files that are used in an iBATIS session.
iBATOR cannot create this file for you because it knows nothing about your execution environment. However, some of the items in this file relate directly to iBATOR generated items.
iBATOR specific needs in the configuration file are as follows −
- Statement namespaces must be enabled.
- iBATOR generated SQL Map XML files must be listed.
For example, suppose iBATOR has generated an SQL Map XML file called MyTable_SqlMap.xml, and that the file has been placed in the test.xml package of your project. The SqlMapConfig.xml file should have these entries −
<.
Updating the dao.xml File iBATOR generated DAO interfaces and implementation classes.
For example, suppose iBATOR has generated a DAO interface called MyTableDAO and an implementation class called MyTableDAOImpl, and that the files have been placed in the test.dao package of your project.
The dao.xml file should have these entries −
<>
NOTE − This step is required only if you generated DAOs for the iBATIS DAO framework. | https://www.tutorialspoint.com/ibatis/ibator_introduction.htm | CC-MAIN-2018-26 | refinedweb | 651 | 56.86 |
table of contents
NAME¶
glob, globfree - find pathnames matching a pattern, free memory from glob()
SYNOPSIS¶
#include <glob.h>
int glob(const char *pattern, int flags, int (*errfunc) (const char *epath, int eerrno), glob_t *pglob); void globfree(glob_t *pglob);
DESCRIPTION¶ gl_pathv. */ } glob_t; ('\')'t match a leading period.
- GLOB_ALTDIRFUNC
- Use alternative functions pglob->gl_closedir, pglob->gl_readdir, pglob->gl_opendir, pglob->gl_lstat, and pglob->gl_stat for ('~') is the only character in the pattern, or an initial tilde is followed immediately by a slash ('/'), to->gl_pathc contains the number of matched pathnames and pglob-¶
On successful completion, glob() returns zero. Other possible returns are:
- GLOB_NOSPACE
- for running out of memory,
- GLOB_ABORTED
- for a read error, and
- GLOB_NOMATCH
- for no found matches.
ATTRIBUTES¶.
CONFORMING TO¶
POSIX.1-2001, POSIX.1-2008, POSIX.2.
NOTES¶
The structure elements gl_pathc and gl_offs are declared as size_t in glibc 2.1, as they should be according to POSIX.2, but are declared as int in glibc 2.0.
BUGS¶
The glob() function may fail due to failure of underlying function calls, such as malloc(3) or opendir(3). These will store their error code in errno.
EXAMPLES¶]);
SEE ALSO¶
ls(1), sh(1), stat(2), exec(3), fnmatch(3), malloc(3), opendir(3), readdir(3), wordexp(3), glob(7)
COLOPHON¶
This page is part of release 5.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at | https://dyn.manpages.debian.org/bullseye/manpages-dev/glob.3.en.html | CC-MAIN-2022-21 | refinedweb | 246 | 64.3 |
Rick Strahl presents a GUI utility to drive the aspnet_compiler command line tool, and voices valid criticisms of ASP.NET 2.0 deployment options with “ASP.NET 2.0 Application Deployment in the real world”.
Is pre-compilation for deployment worth the trouble? The performance advantages to pre-compilation are almost insignificant. Pre-compilation is not NGEN. There remains a hefty amount of JIT compiling at startup, not to mention warming up the cache, establishing connections … the to-do list for the runtime at startup goes on and on.
There are, however, at least two good reasons to pre-compile. First, pre-compilation will find any syntactical errors that might be lurking inside in the application. Even if you don’t deploy a pre-compiled version of an application, pre-compilation should be a part of every build process to ensure there are no errors.
A second reason, good for shared hosting environments, is that pre-compilation will lock down the application. You can deploy an ASP.NET application without deploying any source code whatsoever (not even ASPX files). No one can change your application, or even place a new ASPX file inside your directory in a hack attempt (the new page will throw an exception if executed). Note: you can pre-compile ‘for update’ if you still need dynamic compilation of aspx, ascx files, like for applications that use skins.
A drawback to pre-compilation that Rick points out is the lack of control you have over the /bin directory. Every folder with a web form inside will compile into a different .dll. In addition, the compiler generates part of the assembly’s name at random. The first time you precompile, you might see App_Web_vifortkl.dll appear. The second time, the same directory will produce an App_Web_snarkfob.dll assembly. Multiple XCOPY deployments with no clean up will result in a /bin directory littered with obsolete dlls.
The solution to this problem is to pass –fixednames as a parameter to the aspnet_compiler. The fixednames parameter will force the compiler to generate the same filename on each pre-compilation run for an application, but there is a catch. Each web form and user control will produce an individual assembly! If you have 5 web forms, you’ll find at least 5 assemblies in the bin. Actually, there will be 10 files total, because alongside each .dll file is a .compiled file filled with XML to map source files to assemblies.
You might also use the –d switch to place debugging information for each assembly into a pdb file. PDBs are essential if you want to see line numbers in a production exception’s stack trace. Now there are three files per form. I pre-compiled one of the smallest applications I have with –d –fixednames, an application with only 12 web forms and some user controls, and found 21 assemblies in /bin. 63 total files!
Sixty three!
Each assembly adds a little overhead to the working set of an application. I’m interested to see the impact on large applications where the number of assemblies reaches into the hundreds.
Each assembly also adds some overhead in getting files to a production server. If you are FTP-ing all these files to a shared host with the application online, remember each write to the /bin directory will put your application into a state of flux until all the files are complete.
The underlying problem isn’t performance worries or deployment overhead, but loss of control over the build outputs of an ASP.NET application. At first glance it would seem easy to map each directory and file name into a namespace and type name, then put all forms and controls into a single assembly, but then many problems seem easy at first glance.
I’m hoping the uneasy feeling I get when looking in a /bin directory goes away.
I really hate all the .compiled files and the randomly generated file names.
We work in an environment where we have to send a request to a release engineer to deploy these files to our production servers and this will make our life more difficult. The lack of control here is maddening.
Oh well. Hopefully this issue gets address somewhere down the road. I can hope.
Take a look at web deployment projects. It will make your life easier!
msdn.microsoft.com/.../wdp/
Even this tool, while better, still doesn't provide a "clean" way to compile things up for deployment being that you cannot completely get rid of the .compiled files. Also, even though you can name the outputted DLL (which is nice), the .compiled file still are generated using random names, which worries me.
Unfortunately the "cleanest" I've found is to not do full pre-compilation of all your .aspx files and to allow them to be updatable - which greatly reduces the number of .compiled files created. This, however, nullifies the benefit of pre-compilation, which is something I was looking forward to in 2.0. | http://odetocode.com/blogs/scott/archive/2005/06/29/when-deployment-gets-ugly.aspx | CC-MAIN-2014-15 | refinedweb | 836 | 56.76 |
Newbie to C++ here. I was reading A Deeper Look at Signals and Slots, which claims that 1) callbacks are inherently type-unsafe, and 2) to make them safe you need to define a pure virtual class wrapper around your function. I'm having a hard time understanding why that's true. As an example, here is the code Qt provides on their tutorial page for signals and slots:
// Header file
#include <QObject>
class Counter : public QObject
{
Q_OBJECT
public:
Counter() { m_value = 0; }
int value() const { return m_value; }
public slots:
void setValue(int value);
signals:
void valueChanged(int newValue);
private:
int m_value;
};
// .cpp file
void Counter::setValue(int value)
{
if (value != m_value) {
m_value = value;
emit valueChanged(value);
}
}
// Later on...
Counter a, b;
QObject::connect(&a, SIGNAL(valueChanged(int)),
&b, SLOT(setValue(int)));
a.setValue(12); // a.value() == 12, b.value() == 12
b.setValue(48); // a.value() == 12, b.value() == 48
#include <functional>
#include <vector>
class Counter
{
public:
Counter() { m_value = 0; }
int value() const { return m_value; }
std::vector<std::function<void(int)>> valueChanged;
void setValue(int value);
private:
int m_value;
};
void Counter::setValue(int value)
{
if (value != m_value) {
m_value = value;
for (auto func : valueChanged) {
func(value);
}
}
}
// Later on...
Counter a, b;
auto lambda = [&](int value) { b.setValue(value); };
a.valueChanged.push_back(lambda);
a.setValue(12);
b.setValue(48);
Counter
Why are signals and slots better than plain old callbacks?
Because signals are a lot like plain old callbacks, on top of having extra features and being deeply integrated with Qt APIs. It ain't rocket science - callbacks + extra features + deep integration is greater than callbacks alone. C++ might be finally offering a cleaner way to do callbacks, but that doesn't replace Qt signals and slots, much less render them obsolete.
The slot aspect got a little less relevant since Qt 5, which allowed signals to be connected to any functions. But still, slots integrate with the Qt meta system, which is used by a lot of Qt APIs to get things working.
Yes, you could use callbacks for pretty much everything which signals are supposed to achieve. But it is not easier, it is a little more verbose, it doesn't automatically handle queued connections, it won't integrate with Qt the way signals do, you could probably work around that as well, but it will get even more verbose.
And in the case of QML, which nowadays is the primary focus of Qt, you are essentially stuck with Qt's signals. So I presume signals are here to stay.
Signals and slots are "better" because Qt is conceptually built around them, they are part of the API and are used by a lot of the APIs. Those concepts have been in Qt for a long time, from back in the days C++ didn't offer much callback support aside from plain old function pointers it inherited from C. This is also the reason Qt cannot simply switch to std callbacks - it will break a lot of stuff and is a needless effort. The same reason Qt continues to use those evil unsafe plain old pointers instead of smart pointers. Signals and slots are not obsolete as a concept, even less so technically when using Qt. C++ simply got too late in the game. It is unrealistic to expect that everyone will now rush into moving away from their own implementations in their giant code bases now that C++ finally provides alternatives as part of the language standard library. | https://codedump.io/share/OK8FHqh9d1ee/1/why-are-signals-and-slots-better-than-plain-old-callbacks | CC-MAIN-2018-13 | refinedweb | 578 | 61.97 |
Subject: Re: [boost] transforming ex. boost lib into C++11-only lib?
From: Ben Pope (benpope81_at_[hidden])
Date: 2015-01-22 10:37:19
On Thursday, January 22, 2015 10:20 PM, Oliver Kowalke wrote:
> Hello,
> is it permitted to transform an existing boost library into a C++11-only
> library?
> best,
> Oliver
There has been some discussion on a C++11-only Boost, and Niall has
BindLib-soon-to-be-called-something-else-lib, which may reify some of
the specifics surrounding that.
In my personal opinion, I would say go for it (I've upgraded to C++14 on
multiple compilers and platforms); anybody that cannot upgrade to a
C++11 compiler should either fight harder, do it anyway and then ask for
forgiveness, or change jobs (in that order).
However, some authors/maintainers of various libraries are stuck with
older compilers for their customers and there's pretty much no way you
can convince them to help in a C++11-only effort, or to help maintain a
C++11-only branch. Also, if it ain't broke, don't fix it.
Ultimately, if it's your library and you feel it impractical to support
pre C++11 in your library, that's your choice, but you risk upsetting
customers if you break existing code.
So... onto the discussions of inline namespaces, suitable notice and
backporting bugfixes.
To pick a specific example (and not to pick on anybody or any library in
particular, but just because it's in my mind), I would say it's easier
and more convenient to move to say, Thread/v4 than it is to consistently
supply myriad defines across multiple build systems.
I would say go for a V(x+1) library and enjoy your coding life. Be
responsible where bugfixes are appropriate, but don't let it prevent you
from making progress*.
*Really; please don't let it prevent you from making progress.
Ben
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2015/01/219511.php | CC-MAIN-2020-45 | refinedweb | 346 | 62.07 |
You can convert a text file to a CSV file in Python in four simple steps: (1) Install the Pandas library, (2) import the Pandas library, (3) read the CSV file as DataFrame, and (4) write the DataFrame to the file:
- (Optional in shell)
pip install pandas
import pandas as pd
df = pd.read_csv('my_file.txt')
df.to_csv('my_file.csv', index=None)
Here’s a minimal example:
import pandas as pd read_file = pd.read_csv('my_file.txt') read_file.to_csv ('my_file.csv', index=None)
Of course, replace the filenames
'my_file.txt' and
'my_file.csv' with the path and name to your specific in and out files.
🌍 Related Tutorial: Python Convert String to CSV File
Also, you may be interested in our ultimate guide to converting CSVs back to various other formats.
In case you want to merge multiple text files into a single CSV, check out this guide with a quick hack.
Enjoy your day, my beautiful friend!
>. | https://blog.finxter.com/how-to-convert-a-text-file-to-a-csv-file-in-python/ | CC-MAIN-2022-33 | refinedweb | 156 | 62.17 |
outcomes from the kernel.org compromise is the
increased use of GPG among kernel developers. GPG keys are now required to
get write access to the kernel.org Git repositories, and folks are starting
to think about how to use those keys for other things. Authenticating pull
requests made by kernel hackers to Linus Torvalds are one possible
use. But, as the discussion on the linux-kernel mailing list shows, there
are a few different use-cases that
might benefit from cryptographic signing.
Most of the code that flows into the kernel these days comes from
Git trees that various lieutenants or maintainers manage. During the merge
window (and at other times), Torvalds is asked to "pull" changes from these
trees via an email from the maintainer. In the past, Torvalds has used some
ad hoc heuristics to determine whether to trust that the request (and the
tree) are valid, but, these days, stronger assurances are needed.
That's where GPG signing commits and tags may be able to help.
Conceptually the idea is simple: the basic information required to do a
pull (location and branch of the Git tree along with the commit ID of its
head) could
be signed by the developer requesting the pull. Torvalds could then use
GPG with
his keyring of kernel developer public keys to verify that the signature is
valid for the person who sent the request. That would ensure that the pull
request is valid. It could all be done manually, of course, but it could
also be automated by making some changes to Git.
The discussion on how to do that automation started after a signed pull
request for libata updates was posted by Jeff Garzik. The entire pull request
mail (some 3200+ lines including the diffs and diffstat) was GPG signed,
which mangled the diff output as Garzik noted. Beyond that,
though, it is unwieldy for Torvalds to check the signature, partly because
he uses the GMail web interface. In order to check it, he has to cut and
paste the entire message and feed it to GPG, which is labor intensive and
might be prone to the message being mangled—white space or other changes—that would lead to a false negative signature verification. As
Torvalds noted: "We need to automate this some sane way, both for the
sender and for the recipient."
The initial goal is just to find a way to ensure that Torvalds knows who
the pull
request is coming from and where to get it, all of which could be handled
outside of Git. Rather than signing the entire pull request email, just a
small, fixed-format piece of that mail could be signed. In fact, Torvalds
posted a patch to git-request-pull
to do just that. It still leaves the integrator (either Torvalds or a
maintainer who is getting a pull request from another developer) doing a
cut-and-paste into GPG for verification, however.
There are others who have an interest in a permanent trail of signatures
that could be audited if the provenance of a particular part of the kernel
needs to be traced. That would require storing the signatures inside the
Git tree somehow, so that anyone with a copy of Torvalds's tree could see
any of the commits that had been signed, either by Torvalds or by some
other kernel hacker. But, as Torvalds pointed
out, that information is only rarely useful:
Torvalds's idea is that the generation of the pull request is the proper time for a developer
to sign something, rather than having it tied to a specific commit. His
example is that a developer or maintainer may wish to push the tree out for
testing (or to linux-next), which requires that it be committed, but then
request a pull for that same commit if it passes the tests. Signing before
testing has been done is likely to be a waste of time, but signing the
commit later requires amending the commit or adding a new empty commit on
top, neither of which were very palatable. Git maintainer
Junio C. Hamano is not convinced that
ephemeral signatures (i.e. those that only exist for the pull-request) are
the right way to go, though: "But my gut feeling is that 'usually hidden not to disturb normal users,
but is cast in stone in the history and cannot be lost' strikes the right
balance."
The conversation then turned toward tags, which can already be signed with
a GPG key. One of the problems is that creating a separate tag for each
commit that gets signed rapidly becomes a logistical nightmare. If you
just consider the number of trees that Torvalds pulls in a normal merge
window (hundreds), the growth in the number of signed tags becomes
unwieldy quickly. If you start considering all of the sub-trees that get
pulled into the trees that Torvalds pulls, it becomes a combinatorial
explosion of tags.
What's needed is an automated method of creating tag-like entries that live
in a different namespace. That's more or less what Hamano proposed by adding a refs/audit
hierarchy into the .git directory data structures. The audit objects would act much like tags, but
instead carry along information about the signature verification status of
the merges that result from pulls. In other words, a git-pull
would verify the signature associated with the remote tag (which are often
things like "for-linus" that get reused over and over) and create an entry
in the local audit hierarchy
that recorded the verification. Since the audit objects wouldn't pollute
the tag namespace, and would be pulled and created automatically, they will
have much less of an impact on users and existing tools. In addition,
the audit objects could then be pushed
into Torvalds's public tree so that audits could be done.
So far, Hamano has posted a patch set that
implements parts of his proposed solution. In particular, it allows for
Other pieces of the problem are still being worked on.
As is often the case in our communities, adversity results in pretty rapid
improvements. For the kernel, the SCO case brought about the Developer's Certificate of
Origin, the relicensing of BitKeeper gave us Git, the kernel.org
break-in brought about a closer scrutiny of security practices, and the adoption
of GPG keys because of that break-in will likely lead to even better
assurances of the provenance of kernel code. While we certainly don't want
to court adversity, we certainly do take advantage of it when it happens.
Authenticating Git pull requests
Posted Nov 10, 2011 5:39 UTC (Thu) by dkk (subscriber, #50184)
[Link]
Use mutt+IMAP to the GMail servers, pipe to GPG?
Monotone
Posted Nov 10, 2011 11:14 UTC (Thu) by epa (subscriber, #39769)
[Link]
Posted Nov 11, 2011 11:32 UTC (Fri) by jnareb (subscriber, #46500)
[Link]
Monotone signs every commit, but Linus said in mentioned thread that this is major PITA for Monotone users (Monotone was considered as replacement for BitKeeper after BK fiasco).
Solutions: signing commits, pulling signed tags
Posted Nov 11, 2011 11:37 UTC (Fri) by jnareb (subscriber, #46500)
[Link]
* Signing commits (signature is hidden in commit object header, and stripped e.g. on rebase or amend)
* Puling signed tags, with merge and editing of its commit message enforced, and with saving the whole tag in commit object header for merge commit. Using "git pull <URL> <tag>" won't result in creating a new tag reference.
Posted Nov 12, 2011 13:07 UTC (Sat) by dmag (subscriber, #17775)
[Link]
One problem is that some people don't have/want their signing keys available all the time. I.e. they want commits to be lightweight, because signing them is heavy (may require another computer, or at least extra passwords.)
Posted Nov 11, 2011 14:27 UTC (Fri) by PaXTeam (subscriber, #24616)
[Link]
reactive security is the sign of the careless, not the careful...
Posted Nov 13, 2011 0:39 UTC (Sun) by giraffedata (subscriber, #1954)
[Link]
While we certainly don't want to court adversity, we certainly do take advantage of it when it happens.
reactive security is the sign of the careless, not the careful...
While we certainly don't want to court adversity, we certainly do take advantage of it when it happens.
And that's what "we certainly don't want to court adversity" means.
It's not the reacting that is the careless part of reactive security.
Posted Nov 18, 2011 14:42 UTC (Fri) by jflasch (guest, #5699)
[Link]
It's sad that a company like Google still does not allow GPG with there web mail interface, that said everyone knows why. The use of GPG signing would most likely eliminate Spam and this would change company's like Groupon forever. Knowing who sent a email makes email filtering easy and how do email providers give you something to make there product look better then others.
Even among top kernel developers we have such a slow rate of adoption GPG should have been every where 10 years ago, but still Spam continues to slow this rate of adoption. I am always amazed.
Posted Nov 18, 2011 16:32 UTC (Fri) by nybble41 (subscriber, #55106)
[Link]
Since when? I've never heard of people having trouble sending GPG-signed messages via the web interface. Sure, they don't integrate the feature, but you can always paste an ASCII-armored signed message, or use an extension like FireGPG. Anyway, would you really want Google to have access to your private signing key? They'd need it for that level of integration.
Posted Nov 18, 2011 17:38 UTC (Fri) by mathstuf (subscriber, #69389)
[Link]
Posted Nov 18, 2011 18:31 UTC (Fri) by nybble41 (subscriber, #55106)
[Link]
However, you'd still need GPG on your own system to send signed messages, and a local public keyring for encryption. Once you have that plus a browser extension like FireGPG, how much extra benefit would the direct integration bring?
Posted Nov 18, 2011 18:41 UTC (Fri) by mathstuf (subscriber, #69389)
[Link]
This brings up the problem that there needs to be a way to communicate that a signature is expected. Anything in the mail doesn't work, so there needs to be some server-side implementation for this.
Linux is a registered trademark of Linus Torvalds | http://lwn.net/Articles/466468/ | CC-MAIN-2013-20 | refinedweb | 1,741 | 65.96 |
To write a java program to get the IP address, we first need to understand what an IP address is. The IP address is a unique sequence of four-octet numbers which is separated by full stops. We represent it in decimal form than binary form. we use it to identify a device available on the network. We also use it to get the address of a device by following the internet traffic to that device simply by not revealing the location. It helps to set the communication with other connected devices on the network. The IP address has two versions: IPV4 and IPV6.
IPV4
- It is a 32 bit address length.
- IPV4 supports manual configuration.
- The security is totally dependent on the application.
- It has a header of 20-6- bytes.
- We denote this address numerical digits.
IPV6
- It is 64 bit address length.
- IPV6 supports auto configuration.
- It has an inbuilt security feature IPSEC.
- It has a header of 40 bytes.
- We denote this address by alpha-numerical digits.
Types of IP Address:
We have 4 types of IP addresses
- Public: It is a type of IP address that can easily be accessed over the internet.
- Private: It is used by the user in his own private space without exposing it to the internet.
- Static: static is an IP address that doesn’t change. It remains the same once assigned to the user.
- Dynamic: dynamic is an IP address that changes with time. It is cost-effective and generally, all the home networks tend to use the dynamic IP addresses.
Program to find IP Address of User
import java.net.InetAddress; public class DeveloperHelps { public static void main(String args[]) throws Exception{ InetAddress addr = InetAddress.getLocalHost(); System.out.println("Local Host Address is: "+addr.getHostAddress()); String hostname = addr.getHostName(); System.out.println("Local host name is: "+hostname); } }
The output of the above program in java will be:
Local Host Address is: 172.17.0.2 Local host name is: 0befd7fb6d92
In the above program, we have simply use getLocalAddress() method to fetch the IP address of the device. This address is bound to get the local address to which the system is concerned. | https://www.developerhelps.com/java-program-to-get-ip-address/ | CC-MAIN-2021-31 | refinedweb | 365 | 59.8 |
Break statement is also a loop control statement. It is used to terminate the loop. As the break statement is encountered, the loop stops there and execute the next statement below the loop. It is also used in switch statement to terminate the case.
Here is the syntax of break statement in C language,
break;
Here is an example of break statement in C language,
#include <stdio.h> int main () { int a = 50; while( a < 60 ) { if( a == 55) { break; } printf("Value of a: %d\n", a); a++; } return 0; }
Value of a: 50 Value of a: 51 Value of a: 52 Value of a: 53 Value of a: 54 | https://www.tutorialspoint.com/break-statement-in-c-cplusplus | CC-MAIN-2022-21 | refinedweb | 110 | 78.79 |
#include <deal.II/fe/fe_dgq.h>
Implementation of scalar, discontinuous tensor product elements based on Hermite polynomials, described by the polynomial space Polynomials::HermiteInterpolation. As opposed to the basic FE_DGQ element, these elements are not interpolatory and no support points are defined.
This element is only a Hermite polynomials for degrees larger or equal to three. For degrees zero to two, a usual Lagrange basis is selected.
See the base class documentation in FE_DGQ for details.
Definition at line 484 of file fe_dgq.h.
Constructor for tensor product polynomials based on Polynomials::HermiteInterpolation.
Definition at line 823 of file fe_dgq.cc.
Return a list of constant modes of the element. For the Hermite basis of degree three and larger, it returns one row where the first two elements (corresponding to the value left and the value at the right) are set to true and all other elements are set to false.
Reimplemented from FE_DGQ< dim, spacedim >.
Definition at line 834 of file fe_dgq.cc.
Return a string that uniquely identifies a finite element. This class returns
FE_DGQHermite<dim>(degree), with
dim and
degree replaced by the values given by the template parameter and the argument passed to the constructor, respectively.
Reimplemented from FE_DGQ< dim, spacedim >.
Definition at line 858 of file fe_dgq.cc.
clone function instead of a copy constructor.
This function is needed by the constructors of
FESystem.
Reimplemented from FE_DGQ< dim, spacedim >.
Definition at line 868 of file fe_dgq.cc. | https://dealii.org/8.5.0/doxygen/deal.II/classFE__DGQHermite.html | CC-MAIN-2018-34 | refinedweb | 242 | 51.34 |
Kubernetes for Application Developers (CKAD)
A blog about how to get certified as a Kubernetes developer (CKAD) with handy tips and tricks along the way
Join the DZone community and get the full member experience.Join For Free
Intro
I was lucky. I already had extensive knowledge of Docker before starting the certification for Kubernetes developer (CKAD), and I have an employer (Ordina) that gives me the space and time to invest in myself.
So I claimed a week of preparation and did the whole Kubernetes for Developers (LFD259) course. To follow this course, you have to prepare a practice environment, and you are given instructions on how to do that on AWS or Google Cloud (which can result in extra costs). It is also very possible to create a cluster on your local machine. To make my life easier (and cheaper) I opted for the last option and created a vagrant set up with instructions for it here.
The LFD259 course covers everything needed for the certification, and it is created by the organization also responsible for the certification exam. Much of the course is self-study and reading. One of the downsides of this course was that if something went wrong, and you had a question you had to ask it on a forum, and responses to that forum could take a long time.
So to prepare even more I bought the Udemy course Kubernetes Certified Application Developer (CKAD) with Tests. Normally this course is about $200,= but I bought it in a bundle (with Kubernetes for Administrators - CKA) for about $35,=. A good deal as far as I am concerned. Udemy excels in video courses and that visualization made the needed knowledge complete.
A nice extra of the Udemy course was that it came with prepared exercises on KodeCloud. Very nice! and with practice exams and lightning labs.
After a week of following courses and practicing a lot, I scheduled the exam. In all honesty, I was quite nervous. I scheduled my exam a week later for some extra practice and that is what I did.
Practice practice practice. Speed is what you need!
Tips & Tricks
I have created a GitHub page with all the resources I used, with an extensive list of tips and tricks. Here are some of the more important ones.
Practice for Speed!
The biggest challenge is getting it all done within the allotted time. You have to complete 19 questions in 2 hours and in that time you have to write YAML files and edit them in one of the basic Linux editors (vi / nano). I recommend investing in vi knowledge as it is much more powerful than nano.
The mentioned Udemy course has a few lightning labs at the end of the course. If you can finish them within the given time you are very much on track.
Use
kubectl over YAML as Much as You Can
YAML is a pain to write and cut and paste can be a hassle with mixed tab and whitespace characters. So much can go wrong here!
Please don't write yaml files from scratch!
Use
kubectl run with the dry-run (
--dry-run=client -o yaml) option, whenever you can, to at least generate as much of the YAML as you can. Practice this a lot and find more options.
# this is much faster kubectl create deploy mydeploy --image=nginx --port=80 --replicas=4 #than kubectl create deployment mydeploy --image=nginx --port=80 kubectl scale deployment mydeploy --replicas=4
and if you need to add more options not provided from the command line use the dry-run:
kubectl create deploy mydeploy --image=nginx --port=80 --replicas=4 --dry-run=client -o yaml>mydeploy.yml vi mydeploy.yml # edit what you need done and apply/create
Create a Good Set of Bookmarks
You are allowed to have the kubernetes.io docs open in a second tab during the exam and this is powerful stuff. Create an extensive set of bookmarks pointing to all the needed examples. I have exported the bookmarks I used during my exam, and it was pure gold! Very useful.
Use Bash to the Fullest
Typing
--dry-run=client -o yaml is very cumbersome every time you want a dry-run to generate a YAML but by putting it in a variable it becomes easy.
export DR='--dry-run=client -o yaml'
Now if you want a dry run you can just do:
kubectl create deploy mydeploy --image=nginx --port=80 --replicas=4 $DR >mydeploy.yml #or kubectl run hello --image=busybox $DR>hello.yml
This is just very basic stuff but saves a lot of time.
If you want to get more fancy do more!
source <(kubectl completion bash) #setting the namespace (just do this one again for another namespace if needed) export NS=default # You will do dry runs often and now you can just type $DR in stead of the whole thing export DR='--dry-run=client -o yaml' # use k to run the kubectl command in the exported namespace. Saves typing alias k='kubectl -n $NS' # Now get code completion on the 'k' commands complete -F __start_kubectl k
Now, this is a setup made for speed :-)!
You can use
k instead of
kubectl with bash-completion (tab) on the command, and you can make it into a dry-run by just adding
$DR to it. If you have to perform multiple commands on a different namespace just perform this command first
NS=otherns and use
k again as normal. All this demands practice because you must not forget to change back to the default namespace again when needed, but they can be great time savers.
Useful Resources
- CKAD-Resources - For many more tips tricks and useful links
- k8s-cluster - For a local VirtualBox/vagrant based k8s cluster
- Kubernetes for Developers (LFD259) - Linux Foundation CKAD course
- Kubernetes Certified Application Developer (CKAD) with Tests - Udemy CKAD Course
Published at DZone with permission of Ivo Woltring. See the original article here.
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/kubernetes-for-application-developers-ckad?fromrel=true | CC-MAIN-2021-43 | refinedweb | 1,008 | 70.02 |
Hangman Game in Python
Hangman is a word game in which computer will randomly select a word from the dictionary and player has to guess it correctly in given number of turns. The word to be guessed is represented by row of stars. If the guessed letter is present is word, script will automatically be placed to correct places.
Rules to guess the word :
- Input single letter in one turn.
- Don’t use repeated letters.
- Turns will be decremented after every guess.
This is the text file used inside the code words.txt, which contains 50,000 English words.
Module needed :
import random
Below is the implementation :
Output :
* * * * * Word has 5 letters Total turns: 11 Enter your guess: a Turns left 10 ********** Enter your guess: i Turns left 9 i **i**i**** Enter your guess: s Turns left 8 s **i**i**ss Enter your guess: r Turns left 7 **i**i**ss Enter your guess: h Turns left 6 **i**i**ss Enter your guess: e Turns left 5 e **i**i*ess Enter your guess: o Turns left 4 **i**i*ess Enter your guess: u Turns left 3 u *ui**i*ess Enter your guess: t Turns left 2 t *ui*ti*ess Enter your guess: n Turns left 1 n *ui*tiness Enter your guess: l Turns left 0 l *uiltiness Word is: guiltiness
Recommended Posts:
- Hangman Game in Python
- 21 Number game in Python
- Color game using Tkinter in Python
- Python | Catching the ball game
- Conway's Game Of Life (Python Implementation)
- Python program for word guessing game
- Python | Simple FLAMES game using Tkinter
- Python | Program to implement simple FLAMES game
- Python implementation of automatic Tic Tac Toe game using random number
- Python | Program to implement Jumbled word game
- Python | Program to implement Rock paper scissor game
- Project Idea | (A Game of Anagrams )
- Important differences between Python 2.x and Python 3.x with examples
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or. | https://www.geeksforgeeks.org/hangman-game-in-python/ | CC-MAIN-2019-22 | refinedweb | 334 | 59.57 |
In this section, you will learn about converting Array into ArrayList.
AdsTutorials
In this section, you will learn about converting Array into ArrayList.
Array is a data structure having fixed size which stores same type of elements in sequential manner. While ArrayList ,extends AbstractList and implements the List interface , supports dynamic array which can grow in size .
Situation comes when you have data in Array and you want to convert it into ArrayList. This can be done using asList() method as follows :
import java.util.*; public class ConvertArrayToArrayList { public static void main(String args[]) { String[] states= {"UP", "Bihar", "Kolkata", "Delhi"}; List stateslist = new Arrays(Arrays.asList(states)); System.out.println("ArrayList of states: " + stateslist); } }
OUTPUT :
ArrayList of states: [UP, Bihar, Kolkata, Delhi]
Advertisements
Fee:
Rs. 20,000 US$ 300
Today: Rs. 10,000 US$150
Course Duration: 30 hrs
Posted on: February 4, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles
Advertisements
Ads
Ads
Discuss: Convert Array to ArrayList
Post your Comment | http://roseindia.net/java/beginners/arrayexamples/Convert_Array_to_ArrayList.shtml | CC-MAIN-2017-30 | refinedweb | 172 | 56.66 |
How can I wait, at each iteration, within a for loop, that the user press a given QPushButton?
for i in range(10):
while (the button has not been pressed):
#do nothing
#do something
for i in range(10):
self.hasBeenProcessed = False
# only one function can modify this boolean
# and this function is connected to my button
while (self.hasBeenProcessed is not True):
QtCore.QCoreApplication.processEvents()
So, I share the slight skepticism as to whether you should want to be doing what you described. Also, I share that it would be better if you show a bit more code to describe the context.
Having said this, the code below is a stab at what you seem to be describing. Note that this is by no means meant to be production-ready code, but more a crude example to illustrate the principle.
What happens is that I call one function on the press of
Button1 and I keep the event loop spinning inside the
while loop by calling
QCoreApplication.processEvents() which means that the GUI will still accept e.g. mouse events. Now, this is something that you should not typically do. There are, however, certain situations where this can be needed, e.g. if you have a non-modal
QProgressDialog and you want to keep the GUI updating while the dialog counter increases (see e.g.)
Then the second part is only to modify the global variable in the second function when you press button 2 and the
while loop will exit.
Let me know if this helps
import sys from PyQt4.QtCore import * from PyQt4.QtGui import * btn2pushed = False def window(): app = QApplication(sys.argv) win = QDialog() b1 = QPushButton(win) b1.setText("Button1") b1.move(50,20) b1.clicked.connect(b1_clicked) b2 = QPushButton(win) b2.setText("Button2") b2.move(50,50) QObject.connect(b2,SIGNAL("clicked()"),b2_clicked) win.setGeometry(100,100,200,100) win.setWindowTitle("PyQt") win.show() sys.exit(app.exec_()) def b1_clicked(): print "Button 1 clicked" i = 0 while ( btn2pushed != True ): # not doing anything if ( i % 100000 == 0 ): print "Waiting for user to push button 2" QCoreApplication.processEvents() i += 1; print "Button 2 has been pushed" def b2_clicked(): global btn2pushed btn2pushed = True if __name__ == '__main__': window() | https://codedump.io/share/uqSYADzaZwQ1/1/wait-for-a-clicked-event-in-while-loop-in-qt | CC-MAIN-2018-05 | refinedweb | 369 | 56.66 |
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).
So it was announced that scripts will now get access to an on/off state for their icons.
I see that right in the script manager it tells how to work with it using the state() function. I have 2 questions about this.
def state():
obj = doc.GetSelection()
if obj != []:
print "disabled"
return c4d.CMD_ENABLED
else:
print "enabled"
return c4d.CMD_ENABLED|c4d.CMD_VALUE
It also seems to update in real time, if I select something the icon becomes instantly enabled without executing the script. I feel like I'm doing it wrong haha.
Only passing True, False and c4d.CMD_ENABLED|c4d.CMD_VALUE will effect the icon state correct? it can't be done outside of the state() function?
Yes. You may be able to perform calculations elsewhere and store a state value in the document's container that you access in the state() method, but I don't believe you can change the state elsewhere.
state()
I noticed when I put a print function inside of the state() function it seemed to loop endlessly? if I use this code:
Yes, it's "looping" every time the Cinema 4D interface updates/redraws.
The state() function is seemingly run every time Cinema 4D's interface is redrawn. It's really there for determining whether a command that requires an object be selected is enabled or not. As it's run so frequently, any code you put in there could slow down all of C4D, so ensure that your state check is actually important, and if so, do your check as quickly as possible.
For example, a script that prints the name of the selected object should only be enabled when an object is selected.
"""Name-en-US: Echo Name
Description-en-US: Opens a message dialog with the name of the selected object.
"""
import c4d
from c4d import gui
def state():
"""Gray out icon if no objects are selected, or more than one object is selected.
"""
# `op` is a variable provided by C4D that represents the selected object.
# I'm not certain, but I think this is faster than call doc.GetActiveObject()
# but it will return `False` if more than one object is selected.
if op is not None:
return c4d.CMD_ENABLED
else:
return False
def main():
"""Open a dialog with the selected object's name.
"""
if op is None:
return
active_obj_name = op.GetName()
gui.MessageDialog("You selected: " + active_obj_name)
if __name__=='__main__':
main()
Hi,
state() is called by Cinema 4D whenever needed to update the UI.
main() of a script is called when a script is executed but state() does not get called.
If you implement state() it is important to use main() like the default script does. Otherwise any code called outside of main() is evaluated with state().
Note returning c4d.CMD_ENABLED enables the state and returning 0 disables the state. Also True or False can be returned to respectively enable/disable the state.
c4d.CMD_VALUE can be returned in association with c4d.CMD_ENABLED to enable and check the script state.
c4d.CMD_ENABLED
0
True
False
c4d.CMD_VALUE
The state() implementation posted by Donovan can be optimized and simply be defined as:
def state():
return op is not None
@y_puech and @dskeith Thank you both, that is extremely helpful as I didn't see any other documentation on that. I can see how state() could become very dangerous very quickly. I will certainly proceed with caution and hope this will help others will to not abuse the state() function as well:)
I guess I'll append my question here.
How could this be optimized ?
def state():
test = doc.GetActiveBaseDraw()
if test[c4d.BASEDRAW_DATA_SHOWSAFEFRAME] == 1:
return c4d.CMD_ENABLED|c4d.CMD_VALUE
else:
return c4d.CMD_ENABLED
Thanks in advance,
kind regards
mogh
Hi mogh,
I don't see much room for optimization here.
Cheers,
Andreas
Thanks a_block,
Sadly I had to disable the state() function because it breaks (delays forever) Material Preview/Shader rendering.
This State() function should somehow be isolated if possible ... but i guess this is the limitation of "checking the gui state".
kind regards
mogh | https://plugincafe.maxon.net/topic/10994/r20-script-state-function | CC-MAIN-2021-49 | refinedweb | 717 | 67.15 |
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1b99) Gecko/20090605 Firefox/3.5b99 Build Identifier: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1b99) Gecko/20090605 Firefox/3.5b99 Firefox always crashes under Fedora 11 using 10.0.22.87 flash player. Fedora 11 and flash player are necessary to cause the crash. Reproducible: Always Steps to Reproduce: 1. Under Fedora 11 2. flash player under ~/.mozilla/plugins 3. Browser webpage a few seconds Actual Results: Crash Expected Results: No Crash
Can you give a stacktrace of the crash?
(In reply to comment #2) > Can you please create a new profile, and try to reproduce there. Are you using > an official build of firefox, or a linux distro release? As I've mentioned this happens with a new profile. I'm using Firefox trunk version. I'll try to post stacktrace later.
I mean,, are you using a version from the official mozilla ftp site, or a something through the package manager? Can you give the full version info, something like Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2a1pre) Gecko/20090610 Minefield/3.6a1pre (.NET CLR 3.5.30729) ID:20090610042525.
Also, what version of the Flash plugin are you using? Does Flash work in other browsers?
Reproduced a crash on youtube with the latest flash plugin from adobe.com. Waiting for the stack trace now.
Note: this was with version 10, r22.
Sorry, that's 10.0 r22 in about:plugins. To be more specific.
Crashes Firefox 3.0.10 as well.
I'm also using Mozilla's builds here. Not Fedora's.
Michelle, could the Adobe team have a look at this bug too?
I cannot repro on Ubuntu 8.10 with Flash 10.0.22.87-1 installed. Means I cannot run a debug session on it to get more information.
caillon, you might want to have a look at this - seems F11-specific and affects both Fx 3 and Fx 3.5.
So, based on my understanding: * Fedora's firefox binaries running on F11 works * Mozilla's firefox binaries running on F11 crashes Offhand, I have no idea what's up :( Martin, when you get a chance, can you help pinpoint what the issue is? Possibly a glibc mismatch?
Created attachment 382659 [details] Crash Log Since Crash Reporter doesn't work for (a clear regression - earlier bug reported did NOT required GConf2) me, I'm posting crash log/dump here. Again: clean profile, flash-plugin-10.0.22.87, Firefox nightly..
I can confirm and emphasize further: With F11 the flash-plugin 10.0 r22 crashes all my mozillas: Firefox 3.5b4 (official Fedora distribution), my own builds in F11 -gcc 4.4.0, Minefield 3.6a1, and Seamonkey 2.0b1pre. Unfortunately I can't provide crash reports as the crashreporter won't build with gcc 4.4.0.
(In reply to comment #19) > Unfortunately I can't provide crash reports as the crashreporter won't build > with gcc 4.4.0. That's true but you should be able to catch the stack by running your builds inside gdb. Do you have debug builds?
(In reply to comment #18) >. Strange, I've manually removed libcurl RPM from my Fedora 11 installation and Firefox still crashes. Probably the problem lies somewhere else.
Please also see. From this location you can also download a debug version of Flash. That could help to track down this issue if one of you is familiar with gdb.
(In reply to comment #20) > (In reply to comment #19) > > Unfortunately I can't provide crash reports as the crashreporter won't build > > with gcc 4.4.0. > > That's true but you should be able to catch the stack by running your builds > inside gdb. Do you have debug builds? I'm afraid I did not make debug builds. Unfortunately I am not too familiar with gdb. But give me some time, perhaps I will be successful... BTW Flashplayer ver 9 works fine with these F11 builds. Also from the same source, but built in Windows XP with VS 2005 works fine, also with Flash 10.
Creating a debug build is simple and only needs some small modifications to your .mozconfig. Everything is documented here: Debugging information can be found here:
According to, the problem has to do with a conflict between the /lib/libfreebl3.so that Fedora 11 provides as part of its nss packages and the libfreebl3.so that Firefox uses internally as part of its own nss. Flash 10 uses libcurl which in turn uses libfreebl3. One of the suggested workarounds is to remove Firefox's libfreebl3.so. If you are building your own Firefox, using the --with-system-nss option avoids the conflict as well. I am guessing that the Firefox that comes with Fedora was built with --with-system-nss. There is another crash that happens, at least for me, when Flash actually tries to play a sound, and it attempts to load libasound_module_pcm_pulse.so. That may be the crash people are seeing with the Fedora provided Firefox.
(In reply to comment #25) > There is another crash that happens, at least for me, when Flash actually tries > to play a sound, and it attempts to load libasound_module_pcm_pulse.so. That > may be the crash people are seeing with the Fedora provided Firefox. That one looks like to be the same as bug 496034 which also happens on other distributions and for video too.
Created attachment 383367 [details] Output from gdb bt after crash
Sadly there is no useful information in it. :/
(In reply to comment #28) > Sadly there is no useful information in it. :/ Yes, I noticed that. The good thing, however, is that I now got some debugging experience..:)- It is true that the Fedora distributed Firefox is built with --with-system-nss I will now try that, and see if I also get the sound bug..
This bug is also present in the Linux version of Firefox 3.5 rc2.
This same issue is happening on OpenSuse 11 and OpenSuse 11.1 for us with slightly different results. It's very easy for me to replicate. If I download and use version 3.0.X from Mozilla, Flash 10 is very stable and everything works fine. When I use 3.5 it always crashes at shutdown after playing flash content. This is happening even though both versions reside on the same server and in theory have access to identical libraries. 3.5 also seems to crash when you play flash content in a second window and then close it and return back to the original window instance. If you feel that installing the debug Flash version + running against gdb will produce output....I'm very willing to help. It's easily replicated here.
Created attachment 386423 [details] gdb backtrace of 3.5 under Fedora 11 gdb backtrace with most symbols available
Craig thanks but this backtrace looks like another bug. There is no Flash stack frame listed. You should better file a new Audio/Video bug.
Could there be some differences in the ABI of Fedora's libfreebl3.so? Looks like trunk mozilla-central is using NSS 3.12.4 RC0, and mozilla-1.9.1 is using NSS 3.12.3, while Fedora has NSS_3_12_4_FIPS1_WITH_CKBI_1_75 plus a few changes:
Redhat just pushed out Firefox 3.5 final to the yum mirrors. It no longer crashes on Flash or video for me. I imagine this bug will rear its head again when Mozilla does a Firefox update, and Fedora (and SuSE?) users upgrade outside of the package system. It's fairly obvious that there is some library issue. I was wondering if someone would like me to go back to Mozilla's Firefox 3.5 and to try some different things (such as setting LD_LIBRARY_PATH to my local Firefox install)? This has been very frustrating; although it appears that RedHat is at fault, perhaps the Firefox startup script needs to accommodate this situation.
(In reply to comment #18) Mike Melanson <mmelanso@adobe.com> wrote: >.
Actually, this could also be if some distro distributes an incomplete set of NSS .so files. NSS adds new .so files from time to time, and every time we do, there's always some distro that ships an incomplete set, causing problems until they ship the complete set.
> >. > > *** This bug has been marked as a duplicate of bug 494107 *** Fixed in trunk? I'm not noticing that - today's trunk still crashes when visiting a web page which contains flash. > To anyone who still wants to use Mozilla's Firefox in Fedora: If you have installed Mozilla's Firefox under root user then just delete all libns*.so files in the root Firefox directory. If you have installed it under your user account (and you can update it), then use this script to avoid crashes (call it, e.g. fx and put it in your $PATH): ---------------------------------- #! /bin/bash cd "/firefox/installation/dir" || exit 1 mkdir -p save mv libns* save &> /dev/null exec ./firefox & sleep 60 mv save/libns* . ----------------------------------
Fedora Project has apparently solved the problem for Fedora-fc11. The problem is native on the DVD install set. I removed /opt/Adobe/Reader9/Reader/intellinux/lib/libflashsupport.so, /usr/lib/mozilla, /usr/lib/flash-plugin and all firefox directories under /usr as a start to set the stage. I used yum to erase 'flash-plugin' and 'firefox' and root to remove the rest. I then used yum to install firefox, which updated three other packages, and used yum to install 'flash-plugin'. Fedora-fc11 yum sites installed firefox-3.5.1 and Adobeflash-10.0-r22. At the end of this process every site which crashed my browser operated correctly and everything I had removed had been replaced, except for the usual Java, etc., plugins.
(In reply to comment #40) >> As for dlopen failures with NSS, that's a known bug, already fixed on trunk. > > Fixed in trunk? I'm not noticing that - today's trunk still crashes when > visiting a web page which contains flash. Fixed on the NSS trunk. NSS is its own separate project with its own repository (which is Mozilla's CVS repository). Any other repositories that contain copies of NSS sources, such as any of Mozilla's Hg repositories, or any of Red Hat's repositories, are downstream repositories, and they contain snapshots of NSS (matching certain CVS tags in the NSS repository). The NSS team does not control when the maintainers of these downstream repositories update their copies. However, we do request that they only take snapshots of "official" NSS release tags, unless they're prepared to fully support NSS, because the NSS team cannot support versions other than its own releases. The NSS team produces new release tags rather frequently, generally when any downstream project needs an update. > To anyone who still wants to use Mozilla's Firefox in Fedora: > > If you have installed Mozilla's Firefox under root user then just delete all > libns*.so files in the root Firefox directory. Um, no. It's true that you can just remove the NSS shared libraries from Mozilla's directory to use the OS's "native" copy, but to do that, you really need to delete ALL the NSS files from the Firefox directory, and removing libns*.so doesn't do that. I suggest the following variant of your shell script: cd "/firefox/installation/dir" || exit 1 mkdir -p save touch libfoopy3.so mv lib*3.so save &> /dev/null || true exec ./firefox & This will move all of NSS's files and also libsqlite3.so, which is OK if your system has a copy in /usr/lib, but not otherwise. If your firefox doesn't start, then move libsqlite3.so back from save to . "there was a change between Fedora 10 and Fedora 11 that might be related. In F11, glibc has started to depend on libfreebl3.so, in order to centralize all operating system use of cryptography. But at the same time, there was a desire to keep the list of dependencies as small as possible. Usually, libfreebl3.so depends on libraries from nspr.rpm Bob Relyea had invented mechanisms to use a dynamic runtime decision, whether libfreebl3.so should use some internal minimal nspr replacements, or whether it should link against the real nspr. The idea was, if libfreebl3.so gets referenced by glibc, it shall use its internal nspr replacements (stubs), and in other scenarios it should load the real nspr libs."
It looks like symbols in nsslowhash.c are only defined with FREEBL_NO_DEPEND, which Fedora 11 defines but Mozilla does not. Anyone seeing "version `NSSRAWHASH_3.12.3' not found" messages? When are the symbols in nsslowhash used? Should they be defined even without FREEBL_NO_DEPEND? What is the equivalent API without FREEBL_NO_DEPEND?
They are private to softoken.
(In reply to comment #45) > They are private to softoken. I don't think I understand. They are exported with FREEBL_NO_DEPEND: Are you saying that something similar exists in softoken but is private without FREEBL_NO_DEPEND? Or are you saying that these symbols should only be used by softoken?
Sorry, my comment 45 was mistaken. I believe these symbols define a private interface between glibc and freebl on Red Hat Linux. I believe it is not intended to be a public interface to be called by just any application software that wishes to do so. I believe Mozilla itself should be making no direct calls to those functions, and hence there should be no unresolved externals naming those functions when linking any Mozilla software. I may be mistaken about that interface being private. My words below presume the interface is indeed private. Since it is intended to be a (Red Hat) Linux system private interface, it makes sense (to me) that it would be provided in Red Hat Linux's system builds, and not in Mozilla's builds which are intended to run on all Linux distros. So, I think it is likely appropriate that those symbols should only be defined in Fedora builds and not in Mozilla builds. I see that the problem you are dealing with is that an attempt to link freebl into a .so is complaining about the missing symbols. I think this is because the mapfile is the wrong mapfile. There are two .def files in lib/freebl, which are freebl.def and freebl_hash.def During the make, one of them gets copied into OBJDIR. If you have the wrong one in OBJDIR, and you try to build, you will get this error. Perhaps you changed the setting of FREEBL_NO_DEPEND but then did not do a clean build?
I can reproduce the crash. Fedora 11 system, using flash-plugin installed from Adobe yum repository. I crash using a downloaded nightly firefox 3.5 build from I also crash using a local debug build of the Firefox 3.5 branch (using internal nss, not system nss). In order to trigger the crash, I simply navigated to and clicked on the first video.
I guess the problem is caused by having two different freebl libraries used in the process. I suspect the globally installed flash-plugin may use the system-wide installed libfreebl (a): # ldd /usr/lib/flash-plugin/libflashplayer.so |grep -i nss libnss3.so => /lib/libnss3.so (0x00624000) libnssutil3.so => /lib/libnssutil3.so (0x00800000) while the Firefox application uses the libfreebl (b) that was shipped/built together with the application. (a) was built using FREEBL_NO_DEPEND (b) was built without I don't understand what conflict this can produce, but I assume that Bob Relyea can tell us, and maybe he has an idea for a fix, he invented the FREEBL_NO_DEPEND solution. Maybe one library attempts to free memory that the other library created?
My installed flash-plugin.rpm is version 10.0.32.18 I downloaded I extracted fp10_debug_archive/10r32_18/flashplayer_10r32_18_linux_debug.tar.gz I moved the installed /usr/lib/flash-plugin/libflashplayer.so away I copied file libflashplayer.so extracted from flashplayer_10r32_18_linux_debug.tar.gz to /usr/lib/flash-plugin/libflashplayer.so I started my debug version of Firefox in gdb. Unfortunately this didn't give me a better stack trace. I still see: #0 0x00000000 in ?? () #1 0xaa0af7d0 in ?? () from /usr/lib/flash-plugin/libflashplayer.so #2 0xaa23c285 in ?? () from /usr/lib/flash-plugin/libflashplayer.so #3 0xaa436d00 in ?? () from /usr/lib/flash-plugin/libflashplayer.so #4 0xaa0b55d6 in ?? () from /usr/lib/flash-plugin/libflashplayer.so #5 0xaa0a7fac in ?? () from /usr/lib/flash-plugin/libflashplayer.so #6 0xaa09a319 in ?? () from /usr/lib/flash-plugin/libflashplayer.so #7 0xaa09d599 in ?? () from /usr/lib/flash-plugin/libflashplayer.so #8 0xb7d42180 in ?? () #9 0xb7d4091c in ?? () #10 0x00000001 in ?? () #11 0x00000009 in ?? () #12 0xb7d84b20 in ?? () #13 0xb7d84bb0 in ?? () #14 0x00000000 in ?? ()
(In reply to comment #44) > > Anyone seeing "version `NSSRAWHASH_3.12.3' not found" messages? Yes. When I start my local debug build (internal nss) in gdb, then I get: $ .) /usr/bin/gdb ./firefox-bin -x /tmp/mozargs.iAvn5G GNU gdb (GDB) Fedora (6.8.50.20090302-37.fc11) ...
inside the directory where I run ./firefox : $ strings ./libfreebl3.so |grep -i rawrash => nothing $ strings /lib/libfreebl3.so |grep -i rawhash NSSRAWHASH_3.12.3 I used "thread apply all backtrace" to inspect the other threads at the same we have crasahed. Threads number 1, 2, 3 and 4 have damaged threads. The other threads have usual correct looking threads. Looks like memory corruption to me.
I tried to step into plugin init code. nsNPAPIPluginInstance::InitializePlugin 1030 NS_TRY_SAFE_CALL_RETURN(error, (*fCallbacks->newp)((char*)mimetype, &fNPP, (PRUint16)mode, count, (char**)names, (char**)values, NULL), fLibrary,this); But I can't. When I use "s" command, the next thing that happens is fork and the crash. I re-attempted to debug, and just before this call I used set follow-fork-mode child Didn't work, gdb didn't give me any chance to try further, but printed it' starting bash, then starting ps, then firefox crashed and the stack was shown.
Even if both freebl libraries where built the same way, you will run into problems if you have both installed. bob
(In reply to comment #54) > Even if both freebl libraries where built the same way, you will run into > problems if you have both installed. But people never saw this bug prior to Fedora 11. My primary development system has been the latest Fedora version since 2006, I did always have system nss installed globally, and I had always developed Mozilla using my local builds with internal nss, and I never saw such a problem. I believe this is a new problem.
Prior to Fedora 11, we didn't have libgcrypt using freebl. Now that libgcrypt used freebl, users which continue to try to use their own copy of freebl will have problems removing the private freebl copy should solve the problem. bob
I confirm that I don't crash when having moved libfreebl3.so away, but what should our message be? People don't use "their own copy" of libfreebl, they have downloaded a software package and attempt to run it. Should Mozilla stop shipping libfreel in their Linux binaries? Should Mozilla begin to produce distribution+release specific Linux downloads? Should Mozilla provide a document "how to tweak your downloaded binary so it won't crash on your system" and force all Linux users to read it?
The takeaway message for most users will be "use Ubuntu, because it works". Firefox is a critical application for Fedora, and Flash is a critical plugin.
I suggest that we add ifeq ($(OS_ARCH),Linux) DEFAULT_GMAKE_FLAGS += FREEBL_NO_DEPEND=1 endif to mozilla/security/manager/Makefile.in.
Which Fedora are you running? Mine is Fedora-11. Downloads for auto update left me with Firefox-3.5.2 and that works perfectly. Every image gets shown, all videos get shown. Exactly WHAT are you talking about?! I don't have to go to Adobe to get flash; it gets downloaded automatically from Fedora. DUH! Use yum.
(In reply to comment #51) > $ .) Attachment 394923 [details] [diff] will help here (allowing arguments to be passed to firefox-bin).
(In reply to comment #56) > removing the private freebl copy should solve the problem. This will only work until a new symbol is added to libfreebl.so and newer applications start to depend on this symbol. (In reply to comment #54) > Even if both freebl libraries where built the same way, you will run into > problems if you have both installed. I don't see why this needs to be the case. Provided newer versions of libraries maintain backward compatibility, it should be sufficient to merely ensure that the library with the newest ABI is loaded first. (If newer versions do not maintain backward compatibility then they'll need to use different soname / versioned symbols / etc.) The problem here is that the ABI depends on how the library was configured (but the soname does not). (In reply to comment #59) > I suggest that we add > > ifeq ($(OS_ARCH),Linux) > DEFAULT_GMAKE_FLAGS += FREEBL_NO_DEPEND=1 > endif > > to mozilla/security/manager/Makefile.in. Always building with FREEBL_NO_DEPEND on Linux looks to me like it would work around the problem here (because the FREEBL_NO_DEPEND=1 version of the ABI is a superset of the FREEBL_NO_DEPEND= ABI.) I can't comment on whether this would impact performance at all (given that some apps will know that they'll need nspr anyway). But why not make the ABI independent of the FREEBL_NO_DEPEND=1 environment variable? If Fedora's libcrypt wants the functionality provided through NSSRAWHASH_3.12.3, then why assume that no other clients want that functionality?
Also crashed "Mozilla/5.0 (X11; U; Linux i686 (x86_64); en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3".
As of today, Fedora 11 doesn't use Firefox/3.5b99 and, so far, doesn't issue Firefox/3.5.3 Use yum and get the correct updates for Fedora 11 from the 'update' and 'fedora' sites. As usual, all beta testers can ignore that advice.
Firefox 3.5.2 as provided by Fedora 11 ("Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2") doesn't crash when I access pages using Flash (for this one I use the 64bit Flash Plugin as downloaded at). However, if I install a separate copy of Firefox, like the "Mozilla/5.0 (X11; U; Linux i686 (x86_64); en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3" using the 32bit Flash Plugin from the adobe-linux-i386 repository, it crashes.
Removing libfreebl3.so from the Firefox program directory (of my individual installation, not the one provided by Fedora) seems to solve the problem.
Even trying to remove libfreebl3.so from the Firefox program directory, /usr/lib/firefox-3.5.2/, on Fedora 11 wont work; there is none there. Maybe that's why the Mozilla.com version doesn't work on Fedora 11; Mozilla uses it's private version of libfreebl3.so?! Or is it the other way around? Does Fedora compile a static version into their Firefox? My Fedora 11 installation has /usr/lib/libfreebl3.chk, /usr/lib/libfreebl3.so as part of the regular installation. Why provide a private version? Obviously, if flash works with Fedora 11 firefox-3.5.2 on an independent download from Adobe there is probably some peculiarity of the Mozilla.com version of firefox that is starting to drift from Posix standards. In other words, it ain't compliant any more.
I have a libfreebl3.so in the /lib directory which I guess is the one that Firefox (3.5.2) as provided by Fedora uses. I additionally have Firefox 3.5.3 (the candidate 1 build) installed in /opt/firefox, there was a libfreebl3.so in exactly this directory. After I deleted the libfreebl3.so in /opt/firefox, this instance (3.5.3) could handle Flash well (before it crashed). The Firefox 3.5.2 installation provided by Fedora 11 worked well in regard to Flash all the way. One another thing I haven't mentioned yet: I updated from Fedora 10 to 11 this week. With Fedora 10 there was no problem with Flash at all (also not with my own installation in /opt/firefox), it only started after the update to Fedora 11.
I filed bug 513024 for the workaround suggested in comment 59. I'd appreciate it if someone experiencing this crash (with Fedora 11) could test the build linked there, please. Note that the build is based on trunk, so I suggest either back up your profile or "mkdir ~/tmp/new-profile" and run with "-profile ~/tmp/new-profile -no-remote".
Created attachment 398822 [details] [diff] [review] Proposed patch Always build with FREEBL_NO_DEPEND=1 on current versions of Linux. When I build NSS on Fedora 11 and set LD_LIBRARY_PATH to point to the NSS libraries in my build tree, I can't even use vi to edit a file because of this bug (NSSRAWHASH_3.12.3 not found, required by /lib/libcrypt.so.1). Any NSS-based product that uses its own NSS libraries rather than the system NSS libraries could be affected by this bug when it runs on a Fedora/RHEL system >= Fedora 11.
Wan-Teh, I sympathize with the problem you're having, but Sun's NSS team (or at least I personally) need to understand the full ramifications of this proposed change better before approving this. The number 1 top priority of Sun's NSS team for 3.12.5 is to eliminate, on all platforms, the present perception that 3.12.5 is a regression, as compared to 3.11.x, with respect to ability to load and initialize the necessary NSS shared libraries. I don't want to have to release 3.12.6 and/or 3.12.7 before we eliminate that perception. I fear that unintended consequences may cause the change proposed in this patch to turn into a case of "one step forward, and one step back". Let's discuss this on Thursday morning.
Perhaps ifdef Mozillla && Linux would be the right compromise? bob
(In reply to comment #72) > Perhaps ifdef Mozillla && Linux would be the right compromise? It is not only Mozillla but any app that wants to ship a libfreebl.so and run on Fedora 11, so it would be ifdef WANTS_TO_BE_COMPATIBLE_WITH_FEDORA_11. I'm curious as to what Fedora's libcrypt needs in NSSRAWHASH_3.12.3 that isn't available through FREEBLVectorStr::p_HASH_GetRawHashObject? Or is NSSRAWHASH_3.12.3 merely making something public, that should be public in all builds?
1. In general, you should probably be using system NSS for your application. If you are using mozilla provided by the OS provider, it probably already does, it's just the mozilla builds that are a problem. If you're app believes it really needs to include it's own version of NSS on linux, it could set FREEBL_NO_DEPEND itself. 2. NSSRAWHASH is pretty much strictly for gcrypt. The FREEBLVector interface is private (and a good way to get your app to break on various NSS releases as the NSS team may feel free to change that API if necessary).
(In reply to comment #74) > 1. In general, you should probably be using system NSS for your application. That prevents the app from using new features in NSS. > 2. NSSRAWHASH is pretty much strictly for gcrypt. The FREEBLVector interface > is private (and a good way to get your app to break on various NSS releases as > the NSS team may feel free to change that API if necessary). Thanks. FREEBLVector was the only interface to libfreebl3.so, so I infer from that that libfreebl3.so was only ever intended to be used within NSS. Fedora's libcrypt.so.1 apparently needed a feature that NSS didn't provide and so this feature was provided through new NSSRAWHASH ABI on libfreebl3.so. Why would other clients not want this feature?
Nelson: You can feel free to mark my patch review-. My intention is to call your attention to this potential issue if any of Sun's NSS-based applications bundle NSS libraries (rather than using the system NSS libraries) on Linux and need to support a Fedora or RHEL release >= Fedora 11. Bob: It is very hard to ship a product that uses system NSS and some bleeding edge NSS feature, because if that feature has a bug without a workaround, you are hosed. For a recent example, see bug 515279. (Chromium uses system NSS and the new NSS function CERT_PKIXVerifyCert.)
I'm afraid that, at the moment, no one working on NSS at Sun knows (or remembers, if he ever did know) all the implications of FREEBL_NO_DEPEND. If it's absolutely not a problem for us, then I absolutely do not oppose it. At the moment, I just don't know. We need to bring more of Sun's remaining NSS staff up to speed on this. Maybe we can have a conference call to discuss this on Wednesday or Thursday?
Longer term, we should build libfreebl3.so with FREEBL_NO_DEPEND=1 on Linux. The way we build libfreebl3.so on Linux should not differ between Red Hat and Sun or between Linux distributions. Perhaps I will adapt my patch For now, you can wait until your applications actually encounter this problem to make a decision. The symptom of this bug is a "libfreebl3.so: version `NSSRAWHASH_3.12.3' not found (required by /lib/libcrypt.so.1)" error message. You can't miss it. I will create an alternative patch for the SOFTOKEN_3_13_BRANCH.
> That prevents the app from using new features in NSS. Most Linux distributions stay pretty up-to-date on their version of NSS. It's better to just require the appropriate NSS version. If you use rpm or apt, those requirements are usually picked up automatically by your app because NSS has versioned it's API (the binary has the right symbols to determine dependencies). > I infer from that that libfreebl3.so was only ever intended to be used within NSS. yes. > Fedora's libcrypt.so.1 apparently needed a feature that NSS didn't provide and > so this feature was provided through new NSSRAWHASH ABI on libfreebl3.so. > Why would other clients not want this feature?).
> I will create an alternative patch for the SOFTOKEN_3_13_BRANCH. I would be OK with that. > Longer term, we should build libfreebl3.so with FREEBL_NO_DEPEND=1 > on Linux. The way we build libfreebl3.so on Linux should not differ > between Red Hat and Sun or between Linux distributions. I'm not against that, but remember Sun builds on very old versions of Linux. There may be some issues in the NO_DEPEND mode. I believe that it's all clear, but it really hasn't been tested on something like RHEL 2.1 or earlier. (Actually it's not even turned on on any version of RHEL from Red Hat, and won't be until the FIPS evaluation has been completed. -- on the other hand libgcrypt doesn't try to use it on those platforms either). bob
(In reply to comment #79) >). Thanks for the explanation. My understanding of the issues here is not sufficient to grasp why the bar is high or why other apps wouldn't need it in a FIPS certified way. However, may I make a suggestion for consideration (by people who understand the issues better than I): Currently FREEBL_NO_DEPEND looks like it controls two different features. 1) Enables the new NSSLOWHASH functionality. 2) Enables on-demand loading of nspr4 and nssutil3. Although these features are currently coupled, it doesn't look like they need to be. IIUC only the second feature needs to have the (possibly-recent-)Linux-dependency. If the FREEBL_NO_DEPEND environment variable controlled only the second feature then the ABI could be consistent wrt configuration.
Created attachment 399664 [details] [diff] [review] Proposed patch (for SOFTOKEN_3_13_BRANCH) v2 Set FREEBL_NO_DEPEND = 1 for Linux 2.6 or later in mozilla/security/nss/lib/freebl/config.mk on the SOFTOKEN_3_13_BRANCH. This patch should be less controversial.
Comment on attachment 399664 [details] [diff] [review] Proposed patch (for SOFTOKEN_3_13_BRANCH) v2 Neither the original patch nor this patch works, because mozilla/security/nss/lib/freebl/manifest.mn tests FREEBL_NO_DEPEND. With the current makefiles, FREEBL_NO_DEPEND must be set in the environment or on the gmake command line.
A patch in coreconf/Linux2.6.mk should work, though..... bob
No. manifest.mn is the very first makefile included by mozilla/security/nss/lib/freebl/Makefile: So any variable tested by manifest.mn must come from the environment or the gmake command line.
That's why there are not supposed to ever be any ifdefs or other conditionals in manifest.mn
FWIW, I have worked around this bug by using nspluginwrapper. My .mozilla/plugins/ directory contains the following (lines folded here): lrwxrwxrwx 1 root root 45 2009-10-02 05:39 npwrapper.so -> /usr/lib/mozilla/plugins- wrapped/npwrapper.so* lrwxrwxrwx 1 root root 66 2009-10-02 05:38 nswrapper_32_32.libflashplayer.so -> /usr /lib/mozilla/plugins-wrapped/nswrapper_32_32.libflashplayer.so On an x86_64 computer, I do not have the problem with flash, and this was because I've been using nspluginwrapper all along.
I've provided some updates in the Fedora bug at I've created a wiki page describing the understood issue around the Mozilla and NSS library conflict and linked it from the "common bugs" pages of fedora 11/12. It contains a workaround for end users (delete libraries from downloaded Linux builds.) The bugfix (as proposed in comment 69) has been applied to Firefox trunk and Firefox 3.6.pre already. We'll propose in bug 513024 that the fix gets applied to Firefox 3.5.x stable branch, too. According to my testing it works. There remain crashes using 64 bit versions of the flash plugin with 64 bit Mozilla. Some flash pages (e.g. ) always crash on 64 bit Firefox, whether the Firefox binary was produced by Fedora or by Mozilla. And the page works fine using 32 bit flash. Therefore this is suspected to be a separate bug. Some people have reported they crash using 32 bit fedora firefox and 32 bit flash, but I've never been able to reproduce this. Let's consider this a separate unconfirmed bug. We'll collect information about this in Fedora bug This bug 497251 says "Firefox always crashes using flash. I can confirm "always crashes" when having the mentioned library conflict. I therefore propose to close this bug as "fixed" and "fixed1.9.2", and once we commit bug 513024 to 1.9.1, declare it as fixed1.9.1, too. I propose to open a separate bug report for people crashing on "some" flash content using "64 bit flash", after they have ensured they don't suffer from the library conflict issue described at
IMO bug 513024 is only a workaround. The bug is that the ABI of libfreebl3.so depends on the environment variable FREEBL_NO_DEPEND at build time, and this bug should be kept open to track that until it is fixed.
Karl, I'd agree with you, the better plan is to change NSS, so it will always build with FREEBL_NO_DEPEND on Linux. However, it's a common practice in NSS to drive the build using environment variables. If you look at the makefile you have modified, you'll find several other variables that are set to build NSS in the desired way, for example: DEFAULT_GMAKE_FLAGS += MOZILLA_CLIENT=1 DEFAULT_GMAKE_FLAGS += NO_MDUPDATE=1 ... etc.
I don't mind keeping this bug, but I believe this is fixed. I've filed bug 527557 to suggest changing NSS default Linux FREEBL_NO_DEPEND compilation mode. If you think the makefile change is a undesirable workaround, we could: - close this bug - make bug 513024 depend on bug 527557 - undo bug 513024 (on trunk) once Firefox picks up a fixed NSS (at some later time)
(In reply to comment #90) > If you look at the makefile you have modified, you'll find several other > variables that are set to build NSS in the desired way, for example: I haven't checked all the variables there but > DEFAULT_GMAKE_FLAGS += MOZILLA_CLIENT=1 AFAICS this doesn't change the ABI of any library. > DEFAULT_GMAKE_FLAGS += NO_MDUPDATE=1 This doesn't seem to be used in Mozilla's NSS version:[Nn]O_MDUPDATE
(In reply to comment #91) > I've filed bug 527557 to suggest changing NSS default Linux FREEBL_NO_DEPEND > compilation mode. I've commented there. I'm OK with closing this, if people think that appropriate, provided there is an open bug report that tracks the problem.
Created attachment 411403 [details] [diff] [review] Patch v3 Proposed patch v3. Ideally the patch shouldn't be limited to the future softoken branch, but applied to the current stable version of NSS. I understand that directory freebl must not be modified, therefore I propose to add this fix to the directory one level above. This patch assumes that export/unexport commands are available in all "make" software we're using. The patch will define FREEBL_NO_DEPEND on Linux by default. (Maybe it's unnecessary, but I added a mechanism to request the current default mode using FREEBL_NO_DEPEND=0 ) FWIW, reporting another scenario where this problem bites people: On Fedora 11, when testing a local build (without freebl_no_depend), it's even impossible to run perl or curl.)
Created attachment 411406 [details] [diff] [review] Patch v4 removed invalid "then" from makefile patch
Comment on attachment 411406 [details] [diff] [review] Patch v4 Kai, thank you for the patch. Your patch helps when we do "make" in the mozilla/security/nss or mozilla/security/nss/lib directory. But it's possible to do "make" in mozilla/security/nss/lib/freebl. In fact, I do that often when I work on freebl. It's fine to fix this bug only on the SOFTOKEN_3_13_BRANCH.
The ideal place to make this change is in coreconf/Linux.mk. It's out of the FIPS boundary. It doesn't need an ifdef LINUX. I would be tempted to make it conditional on ifndef FREEBL_DEPEND Rather than interpreting FREEBL_NO_DEPEND value, but I'm ok with kai's formulation.
Bob, we need to change more than coreconf/Linux.mk. See comment 83 - comment 85.
Flash Player 10.1 beta is available for Linux (x86_32) now: This Player should no longer crash when encountering the conflict described in this bug. Note that it won't completely load or show any content, but that's a lesser evil than crashing outright.
I had almost the exact same symptoms suddenly appear a few days ago. turns out I had conflicting flash support installed. Problem appears after yum updating: mplayer-1.0-0.111.20090923svn.fc11.i586 mencoder-1.0-0.111.20090923svn.fc11.i586 I guess firefox was handling the conflict until the update fix is to remove libflashsupport pkg [sonik@alienproject ~]$ rpm -qa | grep -i flash libflashsupport-000-0.5.svn20070904.i386 flash-plugin-10.0.32.18-release.i386 [sonik@alienproject ~]$ rpm -ql libflashsupport-000-0.5.svn20070904.i386 /usr/lib/libflashsupport.so [sonik@alienproject ~]$ rpm -ql flash-plugin-10.0.32.18-release.i386 /usr/lib/flash-plugin /usr/lib/flash-plugin/LICENSE /usr/lib/flash-plugin/README /usr/lib/flash-plugin/homecleanup /usr/lib/flash-plugin/libflashplayer.so /usr/lib/flash-plugin/setup /usr/share/doc/flash-plugin-10.0.32.18 /usr/share/doc/flash-plugin-10.0.32.18/readme.txt [sonik@alienproject ~]$ sudo yum erase libflashsupport-000-0.5.svn20070904.i386 [sudo] password for sonik: Loaded plugins: dellsysidplugin2, refresh-packagekit Setting up Remove Process Resolving Dependencies --> Running transaction check ---> Package libflashsupport.i386 0:000-0.5.svn20070904 set to be erased --> Finished Dependency Resolution Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Removing: libflashsupport i386 000-0.5.svn20070904 installed 11 k Transaction Summary ================================================================================ Remove 1 Package(s) Reinstall 0 Package(s) Downgrade 0 Package(s) Is this ok [y/N]: y Downloading Packages: Running rpm_check_debug Running Transaction Test Finished Transaction Test Transaction Test Succeeded Running Transaction Erasing : libflashsupport-000-0.5.svn20070904.i386 1/1 Removed: libflashsupport.i386 0:000-0.5.svn20070904 Complete!
Bob, we should target this bug for the FIPS revalidation (always build freebl with FREEBL_NO_DEPEND=1 on Linux).
If you can supply a patch, I think it's appropriate for inclusion. (It will probably involve moving some changes to manifest.mn into Makefile for config.mk bob
Oh, and any patch that you add should have an additional environment variable to optionally turn off FREEBL_NO_DEPEND if it's the default. bob
Created attachment 442573 [details] [diff] [review] Patch v5 (checked in) Bob, please review this patch. Re: comment 104 You can turn off FREEBL_NO_DEPEND on the make command line: make FREEBL_NO_DEPEND= I'd like to avoid an additional environment variable to turn off FREEBL_NO_DEPEND. Is this acceptable?
I'd prefer the environment variable.
Comment on attachment 442573 [details] [diff] [review] Patch v5 (checked in) r+ if the ifeq line also includes && FREEBL_FORCE_DEPEND bob
(In reply to comment #107) > (From update of attachment 442573 [details] [diff] [review]) > r+ if the > > ifeq line also includes > && FREEBL_FORCE_DEPEND Bob, I understand we want the default to be "no depend". I guess you intended to request something like && (FREEBL_FORCE_DEPEND != 0) That is, if nobody asked to force, it will be "no depend". Bob, do you agree? Is it already too late to include this patch for the revalidation?
Quite right. It should default to NO_DEPEND on Lunix unless someone purposefully requests depend. It's not yet too late to get in. bob
Comment on attachment 442573 [details] [diff] [review] Patch v5 (checked in) I checked in the patch on the NSS trunk (NSS 3.12.7). Checking in coreconf/Linux.mk; /cvsroot/mozilla/security/coreconf/Linux.mk,v <-- Linux.mk new revision: 1.44; previous revision: 1.43 done Checking in nss/lib/freebl/Makefile; /cvsroot/mozilla/security/nss/lib/freebl/Makefile,v <-- Makefile new revision: 1.112; previous revision: 1.111 done Checking in nss/lib/freebl/config.mk; /cvsroot/mozilla/security/nss/lib/freebl/config.mk,v <-- config.mk new revision: 1.25; previous revision: 1.24 done Checking in nss/lib/freebl/manifest.mn; /cvsroot/mozilla/security/nss/lib/freebl/manifest.mn,v <-- manifest.mn new revision: 1.58; previous revision: 1.57 done And on the SOFTOKEN_3_13_BRANCH (Softoken 3.13). Checking in nss/lib/freebl/Makefile; /cvsroot/mozilla/security/nss/lib/freebl/Makefile,v <-- Makefile new revision: 1.108.4.4; previous revision: 1.108.4.3 done Checking in nss/lib/freebl/config.mk; /cvsroot/mozilla/security/nss/lib/freebl/config.mk,v <-- config.mk new revision: 1.23.4.2; previous revision: 1.23.4.1 done Checking in nss/lib/freebl/manifest.mn; /cvsroot/mozilla/security/nss/lib/freebl/manifest.mn,v <-- manifest.mn new revision: 1.57.8.1; previous revision: 1.57 done
Created attachment 450800 [details] [diff] [review] Set FREEBL_NO_DEPEND to 0 to force a "depend" build (checked in) Rather than adding FREEBL_FORCE_DEPEND (which would require documenting the precedence if both FREEBL_NO_DEPEND and FREEBL_FORCE_DEPEND were set), I suggest that we just use a FREEBL_NO_DEPEND of 0 to force a "depend" build. This requires changing ifdef FREEBL_NO_DEPEND to a comparison with 1 ifeq ($(FREEBL_NO_DEPEND),1) Bob, what do you think?
Slavo: The patch I checked in for this bug yesterday caused new memory leaks on the "memleak dopushups Linux" tinderbox. Here is a new stack: nss_Init/SECMOD_LoadModule/SECMOD_LoadModule/secmod_LoadPKCS11Module/secmod_ModuleInit/FC_Initialize/nsc_CommonInitialize/RNG_RNGInit/freebl_RunLoaderOnce/PR_CallOnce/freebl_LoadDSO/FREEBL_GetVector/FREEBL_InitStubs/dlopen@@GLIBC_2.1/_dlerror_run/_dl_catch_error/dlopen_doit/_dl_open/_dl_catch_error/dl_open_worker/_dl_map_object_deps/malloc Note the FREEBL_InitStubs call in FREEBL_GetVector, which is introduced by the patch. This leak in dlopen can be safely ignored. (We call dlclose here: ) Could you please add a suppression for it? Perhaps the suppression should start from dlopen: dlopen@@GLIBC_2.1/_dlerror_run/_dl_catch_error/dlopen_doit/_dl_open/_dl_catch_error/dl_open_worker/_dl_map_object_deps/malloc This part of the stack is common to many of your existing suppressions, so this leak seems like a bug of dlopen. Thanks.
Added stack: **/FREEBL_InitStubs/dlopen@@GLIBC_2.1/** Checking in ignored; /cvsroot/mozilla/security/nss/tests/memleak/ignored,v <-- ignored new revision: 1.80; previous revision: 1.79 done
Comment on attachment 450800 [details] [diff] [review] Set FREEBL_NO_DEPEND to 0 to force a "depend" build (checked in) r+ rrelyea
Comment on attachment 450800 [details] [diff] [review] Set FREEBL_NO_DEPEND to 0 to force a "depend" build (checked in) I checked in this patch on the NSS trunk (NSS 3.12.7) and SOFTOKEN_3_13_BRANCH (Softoken 3.13). Checking in coreconf/Linux.mk; /cvsroot/mozilla/security/coreconf/Linux.mk,v <-- Linux.mk new revision: 1.45; previous revision: 1.44 done Checking in nss/lib/freebl/Makefile; /cvsroot/mozilla/security/nss/lib/freebl/Makefile,v <-- Makefile new revision: 1.113; previous revision: 1.112 done Checking in nss/lib/freebl/config.mk; /cvsroot/mozilla/security/nss/lib/freebl/config.mk,v <-- config.mk new revision: 1.26; previous revision: 1.25 done Checking in nss/lib/freebl/Makefile; /cvsroot/mozilla/security/nss/lib/freebl/Makefile,v <-- Makefile new revision: 1.108.4.5; previous revision: 1.108.4.4 done Checking in nss/lib/freebl/config.mk; /cvsroot/mozilla/security/nss/lib/freebl/config.mk,v <-- config.mk new revision: 1.23.4.3; previous revision: 1.23.4.2 done
Now nsslowhash.h doesn't get installed in dist/public/nss as we need downstream for building softoken in fedora and rhel. I will enter a separate bug and refer to this one. | https://bugzilla.mozilla.org/show_bug.cgi?id=497251 | CC-MAIN-2017-22 | refinedweb | 7,608 | 59.6 |
NAMEposix_fallocate - allocate file space
SYNOPSIS
#include <fcntl.h>
int posix_fallocate(int fd, off_t offset, off_t len);
posix_fallocate():
_POSIX_C_SOURCE >= 200112L
DESCRIPTIONThe function posix_fallocate() ensures that disk space is allocated for the file referred to by the fileposix_fallocate() returns zero on success, or an error number on failure. Note that errno is not set., or the underlying filesystem does not support the operation.
- ENODEV
- fd does not refer to a regular file.
- ENOSPC
- There is not enough space left on the device containing the file referred to by fd.
-posix_fallocate() is available since glibc 2.1.94.
ATTRIBUTESFor an explanation of the terms used in this section, see attributes(7).
CONFORMING TOPOS.
NOTESIn the glibc implementation, posix_fallocate() is implemented using the fallocate(2) system call, which is MT-safe. If the underlying filesystem does not support fallocate(2), then the operation is emulated with the following caveats:
- The emulation is inefficient.
- There is a race condition where concurrent writes from another thread or process could be overwritten with null bytes.
- There is a race condition where concurrent file size increases by another thread or process could result in a file whose size is smaller than expected.
- If fd has been opened with the O_APPEND or O_WRONLY flags, the function fails with the error EBADF.. | https://man.archlinux.org/man/posix_fallocate.3 | CC-MAIN-2022-27 | refinedweb | 212 | 55.54 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
Don't allow to quote below the sales price of a product?
While we make quotations to customers, don't allow users to quote below the sales price of products. How can we achieve this? Please help me. Am using v7.. Thanks in advance
Call the function for the field
price_unit in the view xml
<xpath expr="//field[@name='price_unit']" position="attributes"> <attribute name="on_change">check_margin(product_id,price_unit)</attribute> </xpath>
and in the class, define the function to process it.
def check_margin(self, cr, uid, ids, product_id, unit_price, context=None): res = {} warning = {} sale_price = None if product_id: sale_price = self.pool.get('product.product').browse(cr, uid,product_id).list_price if unit_price is None: pass elif unit_price < sale_price: warning = { 'title': _("Warning"), 'message': _('Unit price given, is less than the sales price of the selected product. Please change (or contact your sales manager to change) the sales price of the selected product.'), } res = {'value': {'price_unit':sale_price}} elif unit_price >= sale_price: res = {'value': {'price_unit':unit_price}} pass return {'value': res.get('value'), 'warning':warning}
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/don-t-allow-to-quote-below-the-sales-price-of-a-product-51004 | CC-MAIN-2018-05 | refinedweb | 224 | 57.67 |
This is the mail archive of the cygwin@cygwin.com mailing list for the Cygwin project.
RM> fatal ("SHEAP_ADJUSTMENT needs to be modified to reduce memory waste!"); JB> The proper thing to do is adjust SHEAP_ADJUSTMENT like the message says. JB> I think the SLOP parameter is a comparison fuzz setting. Okay, I'm forced to admit how lame I am, but I can't figure out how to reset this value. The error messages says: Static heap usage: 2129280 of 10648960, slop is 65536 -- 8320k wasted -- reset to 2194816k emacs: SHEAP_ADJUSTMENT needs to be modified to reduce memory waste! So I edit emacs-21.2/src/sheap.c to: #ifdef HAVE_X_WINDOWS #define SHEAP_ADJUSTMENT 2194816 /* XEmacs does this dynamically */ #else #define SHEAP_ADJUSTMENT 2194816 /* XEmacs does this dynamically */ #endif But it has no effect on the error/build. I then notice emacs-21.2-build/src/sheap-adjust.h which is generated by sheap.c: /* Do not edit this file! Automatically generated by XEmacs */ # define SHEAP_ADJUSTMENT (-8454144) Well, changing this doesn't do any good, it just gets regenerated (as the comment says!). Furthermore, a tags search fails to find any file which includes this header. Then I notice that emacs-21.2.install actually writes sheap.c, so I edit the script to change the -620000 to: +#ifdef HAVE_X_WINDOWS +#define SHEAP_ADJUSTMENT 2194816 /* XEmacs does this dynamically */ +#else +#define SHEAP_ADJUSTMENT 2194816 /* XEmacs does this dynamically */ +#endif Still no joy. I'll perform the penance of your choice if you tell me how to set SHEAP_ADJUSTMENT and the appropriate value! Thanks, -- Robert -- Unsubscribe info: Bug reporting: Documentation: FAQ: | http://cygwin.com/ml/cygwin/2003-03/msg02020.html | CC-MAIN-2014-42 | refinedweb | 266 | 58.58 |
CodePlexProject Hosting for Open Source Software
In my app, when I attempt to move a dockable window (let's say from the right side of my screen to dock on the left) ... an exception is thrown within this block of code:
public class ContentControlRegionAdapter : RegionAdapterBase<ContentControl>
{
/// <summary>
/// Adapts a <see cref="ContentControl"/> to an <see cref="IRegion"/>.
/// </summary>
/// <param name="region">The new region being used.</param>
/// <param name="regionTarget">The object to adapt.</param>();
};
}
/// <summary>
/// Creates a new instance of <see cref="SingleActiveRegion"/>.
/// </summary>
/// <returns>A new instance of <see cref="SingleActiveRegion"/>.</returns>
protected override IRegion CreateRegion()
{
return new SingleActiveRegion();
}
}
This is the line of code that throws the error:
if (regionTarget.Content != null || (BindingOperations.GetBinding(regionTarget, ContentControl.ContentProperty) != null))
This is the error text:.
In other words, it seems I am dragging one of the dockable windows to a different 'region' with the composite app and viola, problem occurs ...
Any ideas, suggestions or advice?
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://compositewpf.codeplex.com/discussions/34965 | CC-MAIN-2017-34 | refinedweb | 192 | 50.43 |
Hi to all, Matt, thank you for approving the request! I'm going to release Perl implementation for Google's protocol buffers under name Google::ProtoBuf, and if you have objections or better names - it's not too late.Currently, I'm working on documentation (pod is attached), 540-tests suite says ok and I'm going to release in the beginning of the week. There are 2 more or less similar projects - Protobuf-PerlXS,, Project is ready, no CPAN distribution and name conflict is expected, because this project makes XS wrappers for C++ user-named classes (C++ code of the classes is generated by Google's IDL translator, protoc). Protobuf-Perl, is in alpha stage, no CPAN distribution is expected as it's going to be code generator for the official Google's IDL translator.The namespace used internally is 'Protobuf'. If you have suggestions/opinions, please share! (I'm going offline till Monday, so I wouldn't answer immediately, sorry). Have a good day, regards,Igor Gariev. > Date: Sat, 18 Oct 2008 15:53:24 +0100> From: mst@shadowcat.co.uk> To: gariev@hotmail.com> Subject: Welcome to PAUSE! - also pointers to the protobuf-perl project> > Welcome to PAUSE! Please before you upload think carefully about the namespace> for your new module - the name is often how people will discover and remember> it and CPAN already has a common system of namespaces that people will use.> > If you aren't sure, please drop a mail to modules@perl.org and we'd be happy> to talk it over with you.> > Also, the people already working on getting perl onto the google app engine> have got much of the protobuf work done - see> >> > for source and what still needs doing; Brad of LiveJournal fame is the main> guy at google driving this stuff and #appengine on irc.perl.org has a fair> few of the interested people - see also> >> > -- > Matt S Trout Need help with your Catalyst or DBIx::Class project?> Technical Director> Shadowcat Systems Ltd. Want a managed development or deployment platform?>
_________________________________________________________________
News, entertainment and everything you care about at Live.com. Get it now! | https://grokbase.com/t/perl/modules/08ajse9v6p/name-for-cpan-module | CC-MAIN-2021-21 | refinedweb | 358 | 65.01 |
welcome to my blue-eyed leopard tutorial
Things We Will be Plaing with
this tutorial could not have been written without the toys from Andrew Buckle, AKA Andrew's Plug-In, Andrew's Filters.
Andrew graciously consented to allow the bundling of his brush and mask for this tutorial,
so, please show your thanks by checking out his toyland at
GraphicXtras
this snowleopard is now my image, so, whoever has provenance let me know, so i can recieve permission for useage or take down if necessary
this tutorial was written in PSPX,
you can get a 30 day free trial here
everything else you need is in the materials zipped HERE LET THE GAMES BEGIN
PREP WORK Open your PSPX,
your Zip file save the gradient to your gradients folder(tiger1.PSPgradient),
import the brush your brush folder
the mask (SF12_015.jpg) to your mask folder
and then drag your tiger picture called "snow.leopard.pspimage" to a blank spot on your work space by left clicking and holding it down while you drag your mouse to an open space on your work area when your image shows up and in the layers palette you see a layer with your tiger image left click on the tiger again and pull that image into your work area, and you have just duplicated your image, minimize both of your tigers.
next we will prepare the materials palette,
double click on your background patch of your
materials palette preview,
when the materials palette opens,
click on edit
scroll through to your "tiger1.Pspgradient"
double click,the settings are: | http://www.angelfire.com/nc3/skddleworkbeadsn/tiger.html | crawl-002 | refinedweb | 265 | 51.55 |
view raw
I am making a python program in which random values are generated n times, to be used as parameter values for model simulation.
I have a dictionary defining the boundaries for each parameter, for example:
parameters = {'A': random.uniform(1,10), 'B': random.uniform(20,40)}
params = {'C1': random.uniform(0.0,1.0), 'C2': 1 - params['C1']}
KeyError: 'C1'
params = {'A': random.uniform(1,10), 'B': random.uniform(20,40), 'C': {'C1': None,'C2': None}}
def class_fractions():
for key in params['C']:
if key == 'C1':
params['C'][key] = random.uniform(0.0,1.0)
if key == 'C2':
params['C'][key] = 1.0 - params['C'][key]
TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'
From your use of the
for loop it looks like you may really have many more parameters than just two. In that case you can generate a list of values filled with random numbers, and then scale it to sum to one, as described in this other answer. Then iterate over a zipped view of your dictionary keys and the list items and assign the items to the dictionary.
Or, operating directly on the dictionary:
params = {k: random.uniform(0, 1) for k in ('C1', 'C2', 'C3')} total = sum(params.values()) params = {k: (v / total) for k, v in params.items()} | https://codedump.io/share/m5zqkPgsZA8W/1/python-dictionary-assign-random-values-the-sum-of-which-is-a-certain-value | CC-MAIN-2017-22 | refinedweb | 218 | 58.38 |
5. The Switch, callbacks and interrupts¶
The pyboard has 2 small switches, labelled USR and RST. The RST switch is a hard-reset switch, and if you press it then it restarts the pyboard from scratch, equivalent to turning the power off then back on.
The USR switch is for general use, and is controlled via a Switch object. To make a switch object do:
>>> sw = pyb.Switch()
Remember that you may need to type
import pyb if you get an error that
the name
pyb does not exist.
With the switch object you can get its status:
>>> sw.value() False
This will print
False if the switch is not held, or
True if it is held.
Try holding the USR switch down while running the above command.
There is also a shorthand notation to get the switch status, by “calling” the switch object:
>>> sw() False
5.1. Switch callbacks¶
The switch is a very simple object, but it does have one advanced feature:
the
sw.callback() function. The callback function sets up something to
run when the switch is pressed, and uses an interrupt. It’s probably best
to start with an example before understanding how interrupts work. Try
running the following at the prompt:
>>> sw.callback(lambda:print('press!'))
This tells the switch to print
press! each time the switch is pressed
down. Go ahead and try it: press the USR switch and watch the output on
your PC. Note that this print will interrupt anything you are typing, and
is an example of an interrupt routine running asynchronously.
As another example try:
>>> sw.callback(lambda:pyb.LED(1).toggle())
This will toggle the red LED each time the switch is pressed. And it will even work while other code is running.
To disable the switch callback, pass
None to the callback function:
>>> sw.callback(None)
You can pass any function (that takes zero arguments) to the switch callback.
Above we used the
lambda feature of Python to create an anonymous function
on the fly. But we could equally do:
>>> def f(): ... pyb.LED(1).toggle() ... >>> sw.callback(f)
This creates a function called
f and assigns it to the switch callback.
You can do things this way when your function is more complicated than a
lambda will allow.
Note that your callback functions must not allocate any memory (for example they cannot create a tuple or list). Callback functions should be relatively simple. If you need to make a list, make it beforehand and store it in a global variable (or make it local and close over it). If you need to do a long, complicated calculation, then use the callback to set a flag which some other code then responds to.
5.2. Technical details of interrupts¶
Let’s step through the details of what is happening with the switch
callback. When you register a function with
sw.callback(), the switch
sets up an external interrupt trigger (falling edge) on the pin that the
switch is connected to. This means that the microcontroller will listen
on the pin for any changes, and the following will occur:
- When the switch is pressed a change occurs on the pin (the pin goes from low to high), and the microcontroller registers this change.
- The microcontroller finishes executing the current machine instruction, stops execution, and saves its current state (pushes the registers on the stack). This has the effect of pausing any code, for example your running Python script.
- The microcontroller starts executing the special interrupt handler associated with the switch’s external trigger. This interrupt handler get the function that you registered with
sw.callback()and executes it.
- Your callback function is executed until it finishes, returning control to the switch interrupt handler.
- The switch interrupt handler returns, and the microcontroller is notified that the interrupt has been dealt with.
- The microcontroller restores the state that it saved in step 2.
- Execution continues of the code that was running at the beginning. Apart from the pause, this code does not notice that it was interrupted.
The above sequence of events gets a bit more complicated when multiple interrupts occur at the same time. In that case, the interrupt with the highest priority goes first, then the others in order of their priority. The switch interrupt is set at the lowest priority.
5.3. Further reading¶
For further information about using hardware interrupts see writing interrupt handlers. | https://docs.micropython.org/en/v1.10/pyboard/tutorial/switch.html | CC-MAIN-2022-05 | refinedweb | 737 | 73.47 |
return information about a terminal device
#include <sys/dev.h> int dev_fdinfo( pid_t server, pid_t pid, int fd, struct _dev_info_entry *info );
The dev_fdinfo() function returns information about the terminal device that is controlled by the given server process, and that is associated with file descriptor fd belonging to process pid.
If the call is successful, the structure pointed to by info contains the same information as that returned by the dev_info() call. In general, you'll want to use dev_info() to get information on your own file descriptors, however dev_fdinfo() provides a mechanism of querying the status of all devices that are opened by a given device driver process.
Zero on success. The structure pointed to by info contains information about the file descriptor fd belonging to the process pid. A return of -1 indicates failure, in which case the global variable errno is set, and the info structure isn't filled.
#include <sys/dev.h> #include <stdio.h> /* * Display information about a file * that is opened to the driver 'server' * by 'pid' with handle 'fd' */ int main( int argc, char *argv[] ) { pid_t server, pid; int fd; struct _dev_info_entry info; server = atoi( argv[1] ); pid = atoi( argv[2] ); fd = atoi( argv[3] ); if( dev_fdinfo( server, pid, fd, &info) == 0 ) { printf( "Node: %d, TTY %d\n", info.nid, info.tty ); printf( "also known as: %s\n", &info.tty_name[0] ); printf( "is a %s device\n", &info.driver_type[0] ); } else { printf( "Unable to obtain information\n" ); } return( EXIT_SUCCESS ); }
QNX
dev_info(), errno, open() | https://users.pja.edu.pl/~jms/qnx/help/watcom/clibref/qnx/dev_fdinfo.html | CC-MAIN-2022-33 | refinedweb | 250 | 51.99 |
This site uses strictly necessary cookies. More Information
is there a mod operator? example c = b%a or c = b mod a e.g., 5%2 = 1
Answer by spinaljack
·
Aug 21, 2010 at 10:12 PM
Yes,
if(Time.frameCount%10 == 0)
returns true every 10 frames
Sweet. Thanks. I was using it with = overloaded i.e., %=, and got an error.
You may have the value you want from this, but this is incorrect. The % operator means remainder. If you use this with a negative value, you will have strange results.
Answer by InoGamalinda
·
Aug 10, 2013 at 03:55 PM
The % operator is the Remainder operator Example:
% 3 -> 0
% 3 -> -2
% 3 -> -1
0 % 3 -> 0
1 % 3 -> 1
2 % 3 -> 2
3 % 3 -> 0
% 3 -> 0
% 3 -> -2
% 3 -> -1
0 % 3 -> 0
1 % 3 -> 1
2 % 3 -> 2
3 % 3 -> 0
To do a real Modulo, you need to make or find a function similar to this:
function modulo(dividend : int, divisor : int) : int {
return (((dividend) % divisor) + divisor) % divisor;
}
Results:
% 3 -> 0
% 3 -> 1
% 3 -> 2
0 % 3 -> 0
1 % 3 -> 1
2 % 3 -> 2
3 % 3 -> 0
% 3 -> 1
% 3 -> 2
Notice you get the same 0, 1, 2 cycle even when you reach the negative numbers. With this, you can get a consistent indexing for say like enumerators or arrays.
Note: This assumption is from Google calculator's -2 % 3 = 1 in contrast with JavaScripts -2 % 3 = -2.
This is by far and away the best answer and gets over javascripts idea that a negative remainder can exist!!!
Answer by photon
·
Aug 27, 2010 at 08:30 AM
If you are looking for a math function though, just use Javascripts %-operator.
Meaning, if you want to calculate number mod 2 use number%2 The value of this operation is the division remainder (9%2 = 1)
Answer by Dansl
·
Sep 30, 2010 at 09:07 PM
You can. Just Do (a = a % b) because (a %=.
Shorthand for checking for multiple if's.....
2
Answers
If value is multiple of
1
Answer
Setting Scroll View Width GUILayout
1
Answer
Overload Operator in UnityScript?
0
Answers
Javascript And operator not working
1
Answer
EnterpriseSocial Q&A | https://answers.unity.com/questions/25583/is-there-a-modulus-operator-in-unity-javascript.html | CC-MAIN-2021-49 | refinedweb | 369 | 70.53 |
The System.Drawing namespace, which contains types that help you with drawing, plays
an important role in Windows programming. You need its members to draw a custom
control user interface and for sending text and graphics to a printer.
Even when you are only using standard controls on your form, you have used some of its members, probably without realizing it. Understanding the System.Drawing namespace enables you to write better -- and probably faster -- code. Here is a 10-minute crash course to familiarize you with it.
System.Drawing
There are probably only 10 members of the System.Drawing namespace
that you use in 99% of your programs. Out of these, the Point, Color, and Size structures are always
present in any form-based applications. Let's start with the easiest ones: Point and PointF,
structures that represent a location in a two-dimensional plane; and Size and SizeF, two
structures that represent a width and a height. We will continue with the Color structure,
as well as the Pen and Brush classes. Finally, the Graphics, Font, Image, and Bitmap
classes are discussed. Note that all examples in this article assume that System.Drawing
is imported; i.e., the following line is added to the beginning of your class or module:
Point
Color
Size
PointF
SizeF
Pen
Brush
Graphics
Font
Image
Bitmap
using System.Drawing;
using System.Drawing;
In the next article, I will demonstrate how these classes and structures are used in Windows printing.
A Point object represents a coordinate in a two-dimensional plane. The easiest way to
construct a Point is to pass two integers as the abscissa and the ordinate parts of the
coordinate, such as the following:
Point myPoint = new Point(1,2);
Point myPoint = new Point(1,2);
Point is frequently used not only when drawing a shape, but also when writing a form-
based application. For example, to adjust the position of a Button control on a form, you
can assign a Point object to the button's Location property to indicate the position of the
top-left corner of the button on the form. The following code places the button's top-left
corner at coordinate (100, 30) in the form -- i.e., 100 pixels from the left edge of the
form, and 30 pixels from the upper edge of the form's client area:
Button
Location
button.Location = new Point(100, 30);
Assigning a Point object to a control's Location property is the shortest way of
positioning that control in its container. Another way is to use the Left and Top properties
of the control, but this approach requires two lines of code instead of one.
The Point structure has the X and Y properties, from which you can obtain the abscissa
and ordinate of the coordinate a Point object represents. Also, IsEmpty is a read-only
property that returns true only when both the X and Y properties of a Point object have
the value of zero. (Note, though, that this can be misleading; (0, 0) can represent a valid
coordinate for a Point object.)
Left
Top
IsEmpty
You can also construct a Point object by passing a Size object. In this case, the Size
object's width will become the abscissa of the Point, and the Size object's height will
become the ordinate of the Point object. For example:
Size mySize = new Size(13, 133);
Point myPoint = new Point(mySize);
System.Console.WriteLine("X: " + myPoint.X + ", Y: " + myPoint.Y);
produces the following output:
X: 13, Y: 1
For more information on the Size structure, see the "Size and SizeF Structures" section below. The third way of constructing a Point is by passing an Integer. The low-order 16 bits of
the integer will become the value of the Point's abscissa, and the high-order 16 bits the
value of the Point's ordinate.
Integer
If you need more precision in your Point object, you can use the PointF structure. Instead
of representing a coordinate with a pair of integers, PointF takes floats as the X and Y parts
of a coordinate. PointF has only a single constructor with the following signature :
public PointF (
float x, float y
);
The Size structure represents the width and height of a rectangular area. The easiest way
to construct a Size object is by passing two integers as its width and height, as in the
following code:
Size mySize = new Size(10, 30);
The Size object above has a width of 10 pixels and a height of 30 pixels. In a form-based
Windows application, the Size structure is often used to set or change the size of a
control. The Control class has a Size property to which you can assign a Size object. For
instance, the following code sets the size of a button so that it will be 90 pixels wide and
20 pixels tall:
Control
button1.Size = new Size(90, 20);
In addition, you can also construct a Size object by passing a Point object, as in the
following code:
Point myPoint = new Point(10, 50);
Size mySize = new Size(myPoint);
In this case, the width and height of the resulting Size object will have the value of X and
Y properties of the Point object, respectively.
You can obtain the width and height values of a Size object by retrieving the value of its
Width and Height properties. Another property, IsEmpty, is a read-only property that
returns true only if both the Width and Height properties have the value of zero.
The SizeF structure is very similar to Size, except that its width and height are
represented by float. You use SizeF if you want more precision in your Size object.
Width
Height
Related Reading
Programming C#
By Jesse Liberty
The Color Structure represents a color that you can use in drawing shapes or to assign to
the BackColor or ForeColor properties of a control. To obtain a Color object, you don't
use any constructor, because this structure does not have one. Instead, the structure
includes a large number of static properties that represent various colors. For example,
the Brown property represents a brown Color object. Because these properties are static,
you don't need to instantiate a Color object to use them. The following code shows how
to use the Brown property of the Color structure to assign a brown color to the BackColor
property of a Button control:
BackColor
ForeColor
Brown
Color myColor = Color.Brown;
button1.BackColor = myColor;
In addition to common colors such as green, blue, yellow, red, white, and black,
you can choose more exotic colors such as azure, beige, coral, or powder blue. There are
more than 140 properties representing different colors.
If that is not enough, you can compose a custom color by passing the R, G, and B
components of an RGB color to the FromArgb static method. Again, since this method is
static, you can use it without instantiating a Color object. As an example, the following
code constructs a Color object whose R, G, and B components are all 240:
FromArgb
Color myColor = Color.FromArgb(240, 240, 240);
Note that even though the arguments are all integers, the values passed must be in the
range of 0 and 255; this will result in a 32-bit color, in which the first eight bits represent
the alpha value.
In fact, you can also specify all 32 bits of a Color object through another overload of
the FromArgb method that accepts four integers:
public static Color From Argb(
int alpha, int red, int green, int blue
);
You can retrieve the individual alpha, red, green, and blue components of a Color object
by calling its toArgb method, which returns an integer representing all of the four
components (alpha, red, green, blue). This integer indicates the Color object's color
value as follows:
toArgb
Another way of constructing a Color object is by using the Color structure's FromName
method. For example, the following code constructs a blue color by passing the string
blue to the FromName method:
FromName
blue
Color myColor = Color.FromName(. | http://www.onjava.com/pub/a/dotnet/2002/05/20/drawing.html | CC-MAIN-2014-52 | refinedweb | 1,355 | 58.32 |
Our latest and greatest ReSharper Ultimate 2017.3 has just received the second bugfix update – download ReSharper Ultimate 2017.3.2!
We added more than 100 fixes in this build. Here are the notable changes:
- Returned MSTest support for UWP and CodedUI tests.
- Fixed “Inconclusive: Test not run” issue when running/debugging MSTest unit tests.
- Improved support for Razor Pages.
- Fixed bogus unresolved symbols in a React and Redux project.
- Lots of improvements/fixes in the new code formatting engine.
- Fixed a ReSharper integration issue for Visual Studio 2017 on Windows 10 machines.
- Surround typing does not interfere with closing brace overtyping anymore.
- The Sort by drop-down list and the Switch to Constraint View icon are back on the File Layout page.
- Symbols from .NET Framework 4.7.1 projects are now properly resolved in .NET core projects.
- Lots of improvements in the Generate engine.
- A fix for “Configure settings to improve performance” message in the VS notifications panel.
- A bunch of fixes in refactorings.
- Several fixes/improvements in Navigation/Find Usages logic and presentation.
- Debugger extensions support Visual Studio 2010.
Apart from all that, the ReSharper 2017.3.2 update has a heap of improvements for hiDPI support and performance/stability fixes in TypeScript and C#.
ReSharper C++ 2017.3.2 includes a significant number of performance and stability fixes, enhanced code analysis, and Generate action improvements. Please refer to this list to see all fixed issues.
You can either download the build from our site or use the ReSharper | Help | Check for update menu in Visual Studio.
Noticed right away that my TypeScript in React stops warning me about invalid fields that were in fact valid. Good job! Sadly, the generic types are still confusing the system. For instance, the below will tell me that id and title are unknown properties.
interface ITitleProps {
id?: string;
title: string;
}
class BaseTitle extends React.Component {
constructor(props: T) {
super(props);
}
render() {
return (
{this.props.title}
);
}
}
@Joshua, I’ve filed a new request on YouTrack for deeper investigation.
Since I updated, I’ve noticed that highlighting no longer works on Console.WriteLine, string.Format, etc. (the {0} {1} markers don’t turn green).
@Dave What type of project do you see it in – a classic .NET, a .NET core, a .NET Standard?
VS 2013, classic .NET I think.
Thanks for the reply, does the issue happen in a newly created solution?
Hmm, no. If I create a new .NET 4 Console Application, the string.Format highlighting works.
With two instances of VS2013 open under the same user, my old solution does not work, and the newly created one does work.
Actually… it works for my own methods that use StringFormatMethodAttribute. It just doesn’t work for Console.WriteLine, StringBuilder.AppendFormat, etc.
Is there an easy fix for this?
I’ve just upgraded to VS2017 and it still has the same problem. I tried deleting my .suo file but that broke ReSharper and I had to run a repair install.
Well I guess now that I have string interpolation I can just use that instead of fixing this.
Thanks for nothing I guess
@Dave Please accept my apologies for not replying you earlier, I was out of office. Please file a new request here, the blog is not the right place to continue the investigation, we will need some log files and screenshots, so, a support request will cover all these things.
DotCover integration with VS2017 does not work for me. The DotCover menu does not show up after installation and I have tried to reinstall resharper 2017.3.2 but still no luck. VS2015 has no issue for the integration with dotcover.
Has anyone encountered the same issue?
@QJ Please file a support request for dotCover support team here | https://blog.jetbrains.com/dotnet/2018/02/01/resharper-ultimate-2017-3-2-bugfix/ | CC-MAIN-2018-47 | refinedweb | 628 | 69.48 |
canned black cherry
US $10-30 / Carton
10 Metric Tons (Min. Order)
Canned black cherries
US $15-35 / Carton
10 Strands (Min. Order)
Canned Sour Black Cherries Cherry on Top
US $6.0-10.0 / Cartons
300 Cartons (Min. Order)
canned black cherry in syrup
1 Unit (Min. Order)
Best Price Canned Black Cherries without Stem
US $10-17 / Carton
5 Tons (Min. Order)
canned black cherry in light syrup
US $8-20 / Carton
1800 Cartons (Min. Order)
Canned Cherry
US $10-18 / Carton
1600 Cartons (Min. Order)
Canned Cherry
US $15-25 / Carton
1360 Cartons (Min. Order)
Fresh Sweet Cherry / Fresh Cherry Fruit /Red Cherry
US $300-400 / Ton
25 Tons (Min. Order)
fresh canned cherry for sale
US $9-16 / Carton
1800 Cartons (Min. Order)
canned cherry in syrup
20 Long Tons (Min. Order)
Delicious canned cherry
US $2-10.5 / Pack
13.5 Tons (Min. Order)
Dark cherry in Syrup
US $10-40 / Carton
600 Cartons (Min. Order)
canned cherry in syrup supplier
US $7.99-17.99 / Carton
1 Twenty-Foot Container (Min. Order)
Walmart valuable supplier cherry fruit cocktail fruit cups
US $3.7-4.8 / Carton
1 Carton (Min. Order)
canned black sour cherries fresh sour cherries
US $6.0-10.0 / Cartons
300 Cartons (Min. Order)
Delicious Canned black cherries
US $18-22 / Carton
2000 Cartons (Min. Order)
New Crop Canned Black Cherries in syrup
US $10-17 / Carton
3 Tons (Min. Order)
Chinese canned cherry in syrup price
US $7.99-18.99 / Carton
1 Twenty-Foot Container (Min. Order)
Canned black cherry in syrup
US $13-17 / Carton
Factory price Black Canned Cherry without stem, unpitted
US $14-17 / Carton
1 Twenty-Foot Container (Min. Order)
tasty canned fresh cherry
US $10-15 / Carton
1800 Cartons (Min. Order)
canned cherry in syrup
US $8.99-18.99 / Carton
1 Twenty-Foot Container (Min. Order)
Canned Black Cherry
1 Twenty-Foot Container (Min. Order)
dried black cherries
US $2800-3800 / Ton
1 Ton (Min. Order)
2013 new crop canned cherry red cherry black cherry green cherry
US $10-100 / Carton
1 Twenty-Foot Container (Min. Order)
Turkish Cherries
US $2-4 / Kilogram
1200 Kilograms (Min. Order)
import export greece dried cherries
US $2900-4500 / Metric Ton
1 Metric Ton (Min. Order)
FRESH CHERRY
5 Tons (Min. Order)
- About product and suppliers:
Alibaba.com offers 399 black cherry products. About 76% of these are canned fruit, 9% are dried fruit, and 6% are fresh cherries. A wide variety of black cherry options are available to you, such as cherry, strawberry. You can also choose from dried, fresh, and frozen. As well as from common, organic. And whether black cherry is whole, ball, or sliced. There are 374 black cherry suppliers, mainly located in Asia. The top supplying countries are China (Mainland), Bulgaria, and United States, which supply 89%, 1%, and 1% of black cherry respectively. Black cherry products are most popular in North America, Eastern Europe, and Eastern Asia. You can ensure product safety by selecting from certified suppliers, including 25 with Other, 10 with HACCP, and 5 with BRC certification.
Buying Request Hub
Haven't found the right supplier yet ? Let matching verified suppliers find you. Get Quotation NowFREE
Do you want to show black cherry or other products of your own company? Display your Products FREE now! | http://www.alibaba.com/showroom/black-cherry.html | CC-MAIN-2017-51 | refinedweb | 556 | 78.25 |
tl;dr If you want to get started developing a new library for Q#, check out this template repo I made to get you going with the right structure, project files, and build automation with GitHub actions.
I have been really excited to start working on a new project with some colleagues building a new library for Q#, and wanted to share with you our journey so far!
The team will probably post more about the content of what the library is doing (implementing memory for a quantum computer), but here I want to focus on the infrastructure that we needed to get from an empty repo to a built and hosted NuGet package for a Q# library via GitHub Packages.
Libraries in general are a great way to extend languages without having to expand the base language thus increasing the maintenance and scope of the language.
Q# has a bunch of official libraries already provided already in the Microsoft/QuantumLibraries repo.
Part of our goal with this project is to show how leverage the existing Q# libraries and runtime and extend them to add new features and content.
This is certainly not a complete guide, and I'll highlight some improvements I plan to make in the future as we go!
Step 0: Setup your repo
This is probably a step that most of you can skip, but I wanted to add a few notes/reminders of things that are good to setup on a new git repo for a project like this.
Don't forget to:
- Add a licence file (otherwise people won't be able to use your library!)
- If you want to learn more about your options, check out this licence selection assistant from GitHub.
- Add a
.gitignorefile for Q#, you can just use the same
.gitignorewe did for our qRAM library.
- Add a
README.mdso that there is a nice description of your project to folks visiting your repo 💖
- There are some good references out there for writing a good README, like this post from Akash Nimare , this one from Divyansh Tripathi, and this one by Danny Guo.
- Add a
CODE_OF_CONDUCT.mdto your repo, check out GitHub's documentation for adding a code of conduct to your repo.
Also for running Q# code you will want to install the QDK, or setup a Docker container to do your work in.
Step 1: Create your Directory Structure
After looking at the microsoft/QuantumLibraries repo for a bit, I worked out how I wanted to structure the code in our repo.
There are three main directories that we needed, one for the source of the library, one for the samples demonstrating the library, and one for tests.
The samples directory will have a bunch of subdirectories (eventually) for each qRAM implementation we want to demo, as well as some samples showing how to do resource estimation for the various implementations.
│ .gitignore │ LICENSE │ README.md │ CODE_OF_CONDUCT.md │ ├───samples │ ├───src │ └───tests
You can make these folders/directories however you want, you will just need three folders in your base or root project folder called
src,
tests, and
samples.
NOTE: There is nothing magical about these names, it just happens to be what my team and I decided so if you have other naming conventions, go ahead and change them!
Just make sure then as you are reading the rest of this post to make the right replacements for your names in the commands and files I show below 👍
Step 2: Create the Q# projects
Now that you have the folder structure, its time to create the Q# project files that will allow you and the later automation to build your library.
These project files are kinda like Makefiles and use the C# infrastructure (MsBuild) to actually control the Q# compilation.
Library source
Navigate to the
src folder and run the following command:
dotnet new classlib -lang Q#
This will create two files in the
src/ directory:
Library.qs and
src.csproj.
You can see the contents below.
Library.qs
namespace src { open Microsoft.Quantum.Canon; open Microsoft.Quantum.Intrinsic; operation HelloQ () : Unit { Message("Hello quantum world!"); } }
NOTE: You can change the namespace name to better reflect what your library is about!
The Q# API design documentation has some good guidance on how to make good namespace names, e.g.: Organization.Product.DomainArea.
src.csproj
<Project Sdk="Microsoft.Quantum.Sdk/0.11.2004.2825"> <PropertyGroup> <TargetFramework>netstandard2.1</TargetFramework> </PropertyGroup> </Project>
You can see that the
src.csproj file has a reference to the version of the QDK that it was created with as well as what .NET framework it is being built for.
You can test that this template was created correctly by running:
> dotnet build Microsoft (R) Build Engine version 16.4.0+e901037fe for .NET Core Copyright (C) Microsoft Corporation. All rights reserved. Restore completed in 284.96 ms for C:\Users\skais\qsharp-library-template\src\src.csproj. Restore completed in 29.64 ms for C:\Users\skais\qsharp-library-template\src\src.csproj. ____________________________________________ Q#: Success! (0 errors, 0 warnings) src -> C:\Users\skais\qsharp-library-template\src\bin\Debug\netstandard2.1\src.dll Build succeeded. 0 Warning(s) 0 Error(s) Time Elapsed 00:00:12.79
Generally you will not need to do much with the project files here in Q# other than to make sure to add references to other projects and packages you might take as dependencies for your project.
Speaking of, let's try that now by starting our tests project.
Testing
Navigate to the
tests/ folder and run the following command:
dotnet new xunit -lang Q#
This should create two new files in the
tests/ directory,
Tests.qs and
tests.csproj
Tests.qs
namespace tests { open Microsoft.Quantum.Canon; open Microsoft.Quantum.Diagnostics; open Microsoft.Quantum.Intrinsic; @Test("QuantumSimulator") operation AllocateQubit () : Unit { using (q = Qubit()) { Assert([PauliZ], [q], Zero, "Newly allocated qubit must be in |0> state."); } Message("Test passed."); } }
tests.csproj
<Project Sdk="Microsoft.Quantum.Sdk/0.11.2004.2825"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <IsPackable>false</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Quantum.Xunit" Version="0.11.2004.2825" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" /> <PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" /> <DotNetCliToolReference Include="dotnet-xunit" Version="2.3.1" /> </ItemGroup> </Project>
Now the project file here is almost good to go, but it needs to know about our library project in the
src/ folder.
Let's add that now by running this command in the
tests/ directory.
dotnet add reference ..\src\src.csproj
That should add the following
<ItemGroup> to your
tests.csproj file:
<ItemGroup> <ProjectReference Include="..\src\src.csproj" /> </ItemGroup>
Now when you go to run the tests you write for your library the compiler knows where to find your actual library code!
You can test that this tests project is setup correctly by running
dotnet test.
> dotnet test Test run for C:\Users\skais\foo\tests\bin\Debug\netcoreapp3.1\tests.dll(.NETCoreApp,Version=v3.1) Microsoft (R) Test Execution Command Line Tool Version 16.3.0 Copyright (c) Microsoft Corporation. All rights reserved. Starting test execution, please wait... A total of 1 test files matched the specified pattern. Test Run Successful. Total tests: 1 Passed: 1 Total time: 1.7436 Seconds
Samples
The last directory we need to setup is
samples/.
Navigate back to the project root and into the
samples/ folder.
Now, I plan to have multiple samples for my project so I'll make one more folder in
samples/ called
sample1.
Navigate into the
sample1 folder and run the following command:
dotnet new console -lang Q#
This should create two files,
Program.qs and
sample1.csproj.
Program.qs
namespace sample1 { open Microsoft.Quantum.Canon; open Microsoft.Quantum.Intrinsic; @EntryPoint() operation HelloQ() : Unit { Message("Hello quantum world!"); } }
NOTE: You can change the namespace name to better reflect what your sample is about!
sample1.csproj
<Project Sdk="Microsoft.Quantum.Sdk/0.11.2004.2825"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.1</TargetFramework> </PropertyGroup> </Project>
Again, you will want to run
dotnet add reference to make sure the sample also knows about your library.
dotnet add reference ..\..\src\src.csproj
This will add the same
ProjectReference to your
sample1.csproj file.
You can check that this sample was created correctly by running the following:
> dotnet run Hello quantum world!
Step 3: Setup the GitHub Actions to build and publish a package
Now that you have your repo structure setup, it's time to hook up the GitHub automation that will automatically do some maintenance on the repo.
We will setup two automation workflows for this repo, one that will make sure tests pass on code that is committed to master, and the other will build and publish a NuGet package when a new commit is made to master.
Both of these workflows are examples of GitHub Actions, learn more about this feature of GitHub repos here.
Automating test builds
We can use yaml files to configure these workflows, and to make sure that GitHub finds these files let's make the following folders at the root of your project:
.github/workflows/
In the
workflows folder create a file called
test.yml with the following contents.
# This is a workflow that will run `dotnet test` on your tests directory. name: Run Tests # Controls when the action will run. Triggers the workflow on push or pull request # events but only for the master branch. on: pull_request: branches: [ master ] # set of commands using the runners shell - name: .NET tests run: dotnet test working-directory: tests
This action will fire whenever you make a pull request on the master branch.
In the PR window you will see the feedback from the tests (passing/not passing).
You may want to modify this flow to fire on other branches or conditions, check out all the possible triggers for GitHub actions.
If you want to see all of the actions that have been run on your repo you can look at the actions tab:
The above screen cap is from the qRAM library's actions page.
You can see the details of a particular action run here:
Now that you are sure your code is building and ready to merge it into master, let's take a look at the workflow that will package our library!
Automating packaging
In the same
workflows/ folder, create a file called
publish.yml with the following contents:
name: Build and publish NuGet package to GitHub packages on: push: branches: [ master ] jobs: build: runs-on: windows-latest steps: # Same checkout action as before, but adding an authentication token to # help push the package to the GPR. - uses: actions/checkout@v2 # NUGET_AUTH_TOKEN trick from - name: "Setup .NET Core @ Latest" uses: actions/setup-dotnet@v1 with: dotnet-version: '3.1.x' source-url: env: NUGET_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}} # The command `dotnet pack` will build your project and then pack it up in # a NuGet package. The `-c` switch to indicate the build configuration # here "Release" and `-o` indicates where it will put the output. We just # make a new directory called `drop` at the project root and will get the # built package from there later. - name: .NET pack run: dotnet pack -c Release -o ../drop /p:Version="0.1.$Env:GITHUB_RUN_NUMBER" shell: pwsh working-directory: src # The command `dotnet nuget push` takes the package we made in the previous # step in the `drop` directory and pushes it to the GitHub Package Registry. - name: Push to GitHub Packages run: dotnet nuget push (Join-Path "drop" "*.nupkg") shell: pwsh
The line you will have to change for your repo is the
source-url: line.
Change the
qsharp-community to the repo owner of the repo you are working in.
For more information on this configuration see the docs.
FIXME: So the numbering of the packages here is still not perfect, and is keyed off of the
GITHUB_RUN_NUMBERof the action.
In order to be SemVer 2.0 compliant, it needs to start over when the minor or major version is incremented but I haven't figured out a good way to do this yet. 😆
Next steps: Templates and NuGet.org
So if you made it here and haven't made your repo yet, I saved you some time by making a template repo on GitHub.
I will keep it up to date while we continue with the qRAM project and when I figure out how to increment versions numbers better, I'll push the fix there too.
Also when the qRAM library is ready to go to version 1.0 and publish it on NuGet.org, I will add another workflow to the template repo to publish your library there too!
Hopefully you found this post helpful, and are ready to start making your own library for Q# today! 💖
Top comments (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/crazy4pi314/building-and-packaging-a-q-library-1ce0 | CC-MAIN-2022-40 | refinedweb | 2,143 | 65.32 |
I am trying to use the arcballcontrols into my 3dscene but i am facing this issue.
Module parse failed, need an appropriate loader to handle this file type while using Arcballcontrols
As the error message suggests, I guess you need to configure an appropriate loader that can handle
jsm module format. In my own projects I configured
Webpack to use
babel-loader. Maybe this helps:
I have only issue with the arcballcontrols.js from jsm, orbitcontrols works fine for me from same nodemodules.
the difference i see from orbitcontrols and arcballcontrols are the functions for orbitcontrols are inside the constructors and arcballcontrols functions are outside the constructors.
I am bruteforcing my way to make it work, so if things i mentioned just now doesnt make sense sorry.
I can’t reproduce it with my Webpack setup.
ArcballControls can be loaded and is defined.
import { ArcballControls } from 'three/examples/jsm/controls/ArcballControls'; console.log(ArcballControls); /* Output -> class ArcballControls extends three__WEBPACK_IMPORTED_MODULE_0__.EventDispatcher { constructor( camera, domElement, scene = null ) { super(); this.camera = null; this.domElement = domElement; th… */
The issue is that it’s using an arrow function as a class method. You need to use the appropriate Babel plugin in order to get it to compile.
This link should hopefully be enough info to install the plugin ( you can use babel preset-env like in their example as it contains the transform-arrow-functions plugin ). Be careful with the
exclude parameter, as in their examples it excludes node-modules which is where you’re getting arcball controls from.
module: { rules: [ { test: /\.(js|jsm)$/, include: path.resolve(__dirname, 'node_modules/three'), use: { loader: 'babel-loader', options: { presets: [['@babel/preset-env', { targets: 'defaults' }]], }, }, }, ], },
this is my config file, i have added the include options also. But it doesnot work, i think i have done something wrong try to use the babel-loader. My knowledge is very less in this topic.
"dependencies": { "babel-loader": "^8.2.4" } "devDependencies": { "@babel/core": "^7.17.8", "@babel/preset-env": "^7.16.11" }
This is version of babel loader i am using.
module.exports = { presets: ['@vue/cli-plugin-babel/preset'], }
This is babel.config.js
I am still getting the same error.
| https://discourse.threejs.org/t/module-parse-failed-need-an-appropriate-loader-to-handle-this-file-type-while-using-arcballcontrols/36531 | CC-MAIN-2022-27 | refinedweb | 360 | 51.55 |
)
27 Comments
David Svoboda
I have no arguments with this as a rule. But I must point out that enforceability of macro-related rules is very difficult for all software we use to write rule checkers. Moreover, there is significant overlap between this rule and EXP30-C (depending on order of evaluation between sequence points.)
In the noncompliant example, the expanded macro (which is normally all Fortify or Rose will ever see) yields an expression with three invocations of ++n. Multiple instances of an increment or decrement of a variable, or of an assignment to a variable within one expression seems like a violation of EXP30-C, which our checkers should be easily able to handle.
The upshot being than any unsafe macro containing an expression with side effects will yield an expression that violates EXP30-C, which our checkers can catch, even if they can't identify that the unsafe macro is to blame.
Robert Seacord
From comp.lang.c:
These are all the kinds of side effects:
1 object modification
2 volatile access
3 file write
4 function call that results in one or more of the previous three.
Also, it should be OK to invoke a function in an unsafe macro, provided the function call has no side effects, yes?
Douglas A. Gwyn
(1) The last two sentences in the first paragraph ("Any input or output ...") seem to be versions of what should have been a single sentence.
(2) In the interface documentation describing the macro, or in case that doesn't exist, in a comment attached to the macro definition, a rule should be to flag the macro as "UNSAFE", as a warning to programmers using the macro. E.g.
#define ABS(a) ((a) <0?-(a) :(a) ) // UNSAFE
That doesn't need to be a separate rule, but should be mentioned here.
David Svoboda
fixed and fixed
David Svoboda
Macros that never evaluate their argument, or sometimes evaluate their arg, sometimes not, are also unsafe, since the programmer generally expects macro args to evaluate once.
Added this info to 1st paragraph, and added link to EXP39-C, which deals with
assert, the archetypal example.
David Svoboda
ROSE cannot enforce this rule, because it can not identify usage of a macro (though it can identify macro definitions). Besides, violation of this rule will generally cause a violation of other rules, usually EXP30-C.
Martin Sebor
This rule effectively requires users to inspect the definition of every macro before using it (and inspect the declaration of every function to make sure it's not masked by an unsafe macro). I have a feeling that might be too much to expect.
I would like to see a guideline to avoid writing unsafe macros (PRE00-C. Prefer inline or static functions to function-like macros notwithstanding).
Also, wouldn't Avoid side-effects in arguments to unsafe macros be a better name for this rule (more consistent with EXP31-C. Avoid side effects in assertions)?
Robert Seacord (Manager)
I agree that writing unsafe macros is the real problem, but what is wrong with PRE00-C. Prefer inline or static functions to function-like macros? Is it too strong? The first noncompliant code example involves passing an expression that contains side effects.
I also thinking that having a static analysis tool flag every macro is a non-starter, which is why PRE00-C is a recommendation.
I recently used PCLINT to uncover the following problem:
g_htonl()is a GLib unsafe byte order macro that converts a 32-bit integer value from host to network byte order (but you probably already knew this).
So anyway there are some tools that can help enforce this, or you can dump your preprocessor output to a file and look for nasty surprises.
I sort of agree with your title change. I sort of recall that David Keaton preferred this title, but it may only have been to try to use normal programming speak instead of standardese, which is probably a lost cause at this point and possibly counter-productive. We should check with him about changing.
Martin Sebor
PRE00-C is great as far as it goes, but it does allow for 5 classes of exceptions. Since there are valid uses for function-like macros even in new code, a guideline for how to write them safely is called for.
The
g_htonl()macro problem is exacerbated by the fact that its documentation doesn't mention that its argument is evaluated more than once. This IMO, underscores the need for a guideline discouraging the coding of such macros. There are efficient ways to do it without evaluating the argument more than once, either by relying on language extensions (such as gcc's Statements and Declarations In Expressions ) or by introducing a [possibly inline] function (such as OpenSolaris
htonl()), so the burden to do the right thing should be on the implementer rather than on the user (although users should be aware of how to avoid getting bitten by badly written macros as well, which is where PRE31-C comes in).
I know little about the internals of static analysis tools but I would expect the better ones to be able to examine the definitions of macros and flag violations of the guideline I'm proposing even more effectively than is possible after preprocessing.
I'll wait for you to let me know how to proceed with the title change after you get feedback from David.
Robert Seacord (Manager)
OK, I'm convinced. Please go ahead and draft a new guideline for review.
Thanks.
Martin Sebor
Okay, I'll work on it. Btw., I note that you've already renamed the rule as I suggested – thanks!
I've added PRE12-C. Do not define unsafe macros.
Martin Sebor
The Remediation Cost of medium seems rather high given the relative simplicity of the available solutions:
The first approach is by far easier to implement but it relies on the ability to modify the source code of the macro which may not be possible when the macro is defined in a third party library.
The second approach is more involved but can be automated via a simple script.
I changed the Cost to low and adjusted Priority and Level accordingly.
Martin Sebor
I just noticed that the last paragraph in the first NCCE and the comment in the code are wrong. The
ABS()macro has well-defined semantics and does not depend on the order of evaluation of operands between two consecutive sequence points. (As specified in 6.15.5, p4, there is a sequence point between the evaluation of the first operand of the conditional expression and the evaluation of the second or third operand (whichever is evaluated)).
David Svoboda
Fixed, thanks!
Martin Sebor
Now that PRE12-C exists, I think the second and third compliant solutions should be removed, since they strictly speaking don't follow the requirement to
but rather change the macro definition to be safe.
David Svoboda
I added a reference to PRE12-C to the 2nd CS. We do like our rules (of which this is one) to exist somewhat independently of our recommendations (PRE12-C, for instance), so a little redundancy is OK.
Matt Kraai
I think that the typeof example violates DCL37-C. Do not declare or define a reserved identifier. The example declares a variable named "__tmp" that starts with two underscores and DCL37-C indicates that "[a]ll identifiers that begin with an underscore and ... another underscore are always reserved for any use."
David Svoboda
You're right. Furthermore, this code is...passable. I wouldn't call it 'good', but it is the best you can do under some circumstances. I've added an exception to DCL37-C to allow this example, and also overhauled this example.
Aaron Ballman
Perhaps this is a terrible idea, but you could use the __LINE__ predefined macro to generate a likely-unique identifier without requiring the identifier to stray into the reserved namespace.
That will create two identifiers named TestXXX where the XXX is whatever line number the declaration is on. It strays quite a bit from the goal of this guideline, but then again, there's a whole lot of words talking about why not to do what's being done already.
Robert Seacord
I think we should add a type generic solution because this is a C11 standard.
Aaron Ballman
Honestly, I'm not certain that'd be worth the effort. Off the top of my head, it would be:
That's a pretty big mess of code to write for a generic abs function, and would require updating were another type to come along for which abs could be well-defined. At least with the macro, anything for which < and - are defined operators will suffice.
Robert Seacord
i don't know, I think it is beautiful. 8^)
Aaron Ballman
Hmm, you could argue that it's safer since any usage of the ABS macro based on _Generic for a type not listed would generate a compile error (since there's no default selection), which would give the programmer better diagnostics if used with a type not listed, unlike the current macro. An immediate case that springs to mind are pointers...
Aaron Ballman
The more I think about it, the more I like it. I will add it as an additional compliant solution.
Emily Evans
Shouldn't there be a (v) after the_Generic(v, generic assoc list)?
Aaron Ballman
Yes, there should be! Good catch.
Ark Khasin
A simplified rule could be "a function-like macro can only have (a) constants and (b) identifiers as parameters. That way, the whole notion of unsafe macros can be buried in motivation and explanation part. With modern compilers, I would expect no performance/footprint penalty. | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152163 | CC-MAIN-2019-22 | refinedweb | 1,630 | 60.85 |
Java file mkdir()
This section demonstrates you the use of method mkdir().
Description of code:
Now the manipulation of files is become an easy task. Java has provide various useful classes and their methods to handle the file operations. This makes the programming much easier. If you want to create a file, delete a file, create a directory then by just using the built in methods provides by the java.io.* package, you will get the required result.
You can see in the given example, we have created an object of File class and parse a string representing the directory name along with the path. Then we have called the method mkdir() through the object of file class. On executing the given code, you will get the newly generated directory in the given path.
Here is the code:
import java.io.*; public class Filemkdir { public static void main(String[] args) { File f = new File("C:/hello"); f.mkdir(); } }
Through the use of method mkdir(), you can create a directory of your choice.
Advertisements
Posted on: April+ | http://www.roseindia.net/tutorial/java/core/files/filemkdir.html | CC-MAIN-2015-22 | refinedweb | 176 | 75.1 |
Drop rows in a subset of columns in mixed data type data frame
r subset dataframe by list of values
r subset dataframe by multiple column value
r subset matrix by column names
r subset dataframe by column name
subset in r
r extract rows with certain value
r subset dataframe based on vector
Hello I am trying to drop values that are not equal to
1 or
0 across several columns but not including some columns
this is what I started with
df=pd.read_csv('df.csv') df.head() Age Prod1 Prod2 Day 4 Day 5 ... Region 0 18 1 0 1.0 5.0 0 1 1 89 3 1 1.0 1.0 1 1 2 100 4 7 0.0 1.0 1 0 3 200 0 1 0.0 0.0 1 0 4 300 1 1 0.0 1.0 1 1 5 19 1 1 1.0 1.0 6 1
there are a total of 10,000 rows and 34 columns
the first two columns I have cleaned successfully because they have numeric values that are different from the rest.
Here is what I did
ageindex = df[ (df['Age'] < 18) & (dfl['Age'] > 150) ].index df.drop(ageindex)
I want to drop the rows from columns
Prod1 through the end
Region. It is only 34 columns but I cannot seem to figure out how to do this.
I have found a way to drop NaN values here but not how to drop using conditions based on values.
Here is what I have tried
prodindex1 = df[ (df.loc['Prod1':'Region'] > 1) ].index df.drop(prodindex1)
but that just returns the same dataframe. I also tried
prodindex = df[ (df.loc['Prod1':'Region'] > 1) & (df.loc['Prod1':'Region'] < 0) ].index df.drop(prodindex)
The Expected output should be
Age Prod1 Prod2 Day 4 Day 5 ... Region 3 200 0 1 0.0 0.0 1 0 4 300 1 1 0.0 1.0 1 1
I think I have some problems because some of them are whole numbers and some are floats. Any guidance is appreciated.
EDIT: i want to drop where values are not equal to or not equal to 0
import pandas as pd import numpy as np # Sample data d = np.array([[18, 1, 0, 1.0, 5.0, 0, 1], [89, 3, 1, 1.0, 1.0, 1, 1], [100, 4, 7, 0.0, 1.0, 1, 0], [200, 0, 1, 0.0, 0.0, 1, 0], [300, 1, 1, 0.0, 1.0, 1, 1], [19, 1, 1, 1.0, 1.0, 6, 1]]) df = pd.DataFrame(data=d, columns = ['Age','Prod1','Prod2', 'Day 4', 'Day 5', 'Day 6', 'Region']) df = df.drop(df[~df.loc[:, 'Prod1':'Region'].isin([0, 1]).all(axis=1)].index) print(df)
should give the expected output:
Age Prod1 Prod2 Day 4 Day 5 Day 6 Region 3 200.0 0.0 1.0 0.0 0.0 1.0 0.0 4 300.0 1.0 1.0 0.0 1.0 1.0 1.0
Comment on your code:
Your conditions are wrong but this is not the reason why you are getting the same dataframe. This happens because you are not passing
df.drop(prodindex) to a variable, i.e:
# Your code prodindex = df[ (df.loc['Prod1':'Region'] > 1) & (df.loc['Prod1':'Region'] < 0) ].index df = df.drop(prodindex) print(df) Empty DataFrame Columns: [Age, Prod1, Prod2, Day 4, Day 5, Day 6, Region] Index: []
4 Subsetting, Subsetting operators interact differently with different vector types (e.g., atomic vectors, x[c(-1, 2)] #> Error in x[c(-1, 2)]: only 0's may be mixed with negative subscripts Each row in the matrix specifies the location of one value, and each column corresponds Data frames with a single column will return just that column:. Drop specified labels from rows or columns. Remove rows or columns by specifying label names and corresponding axis, or by specifying directly index or column names. When using a multi-index, labels on different levels can be removed by specifying the level. Parameters labels single label or list-like. Index or column labels to drop.
This should work:
df[df.loc[:, 'Prod1':'Region'].isin([0, 1]).all(axis=1)]
pandas.DataFrame.select_dtypes — pandas 1.1.0 documentation, Return a subset of the DataFrame's columns based on the column dtypes. Parameters Return Series with the data type of each column. Notes. To select all� The most easiest way to drop columns is by using subset () function. In the code below, we are telling R to drop variables x and z. The '-' sign indicates dropping variables. Make sure the variable names would NOT be specified in quotes when using subset () function.
If you wish to remove rows containing values 1 or 0, following works:
df.loc[~df.loc[:, 'Prod1':'Region'].isin([0, 1]).any(axis=1), :]
Subsetting � Advanced R., You'll start by learning the six types of data that you can use to subset atomic vectors. x[c(-1, 2)] #> Error in x[c(-1, 2)]: only 0's may be mixed with negative Blank subsetting is now useful because it lets you keep all rows or all columns. Omitting drop = FALSE when subsetting matrices and data frames is one of the most� When using the column names, row labels or a condition expression, use the loc operator in front of the selection brackets []. For both the part before and after the comma, you can use a single label, a list of labels, a slice of labels, a conditional expression or a colon. Using a colon specificies you want to select all rows or columns.
15 Easy Solutions To Your Data Frame Problems In R, Discover how to create a data frame in R, change column and row Each column needs to consist of values of the same type, since they Note that you can also define this subset with the variable names. If you want to remove values or entire columns, you can assign a NULL value to the desired unit:..
[PDF] Subsetting Data in R, Subset rows of a data.frame. 4. Subset Add/remove new columns to a data. frame. 6. What about selecting rows based on the values of two variables? namespace:dplyr, which means when you type filter, it will use. This version of the subset command narrows your data frame down to only the elements you want to look at. Other Ways to Subset A Data Frame in R. There are actually many ways to subset a data frame using R. While the subset command is the simplest and most intuitive way to handle this, you can manipulate data directly from the data frame syntax.
Subsetting data – Environmental Computing, We often want to subset our data, whether it's to examine particular rows or columns of our dataset, or to pull out observations with particular� subset: It’s an array which limits the dropping process to passed rows/columns through list. inplace: It is a boolean which makes the changes in data frame itself if True. Code #1: Dropping rows with at least 1 null value.
- Do you delete rows whose columns (between Prod1..Region) are not equal to 1 and 0, or those which are between 0 and 1?
- Not equal to 1 or 0 ill edit to make more clear
- If i use this I get "'DataFrame' object is not callable" error
- Works fine for me. I updated my answer in order to include the full script.
- Ok that dropped rows but it dropped all rows. I started with a csv file that has 34 columns. Do I need to specify a dataframe and type out all the column names for all 34 columns?
- If this hasn’t worked as expected then you have desribed your problem or dataset incorrectly.
- I added more details I am not sure what I am missing. I started with a csv file if that makes a difference. Do i need to explicitly name all 34 column names like in your example? I started with just df=pd.read_csv('df.csv')
- There is at least one row that does not drop when I use this. The row has a value equal to 1 0 and it is still present.
- @aardvark I cannot reproduce that. When run on your provided data, only rows 3 and 4 are left, as stated in the question.
- Weird. I am missing something in this so I'm sorry. I have to assume your solution works and it is on my end that I am messing up. thanks
- @aardvark do you mean that it doesn't work on your full dataset? Could you provide more details please?
- Yes on the full data set this is not working. It does not drop one row where Day6=10 I added details to the original post. I started with a csv file. I know how to go through each column individually and drop the values just not how to do it quicker. I have removed NaN values and dropped values using the Age column before this step. | https://thetopsites.net/article/54953980.shtml | CC-MAIN-2021-25 | refinedweb | 1,523 | 74.29 |
Refactoring to tests is no easy task. The largest problem that you run into is moving around code with no feedback as to whether you are breaking modules other than doing very high level user/functional testing directly against the UI. This makes the first step of refactoring to tests the most difficult to take.
Before I begin describing the technique at hand I would like to prefix it with a disclaimer and a warning: DO NOT use this to replace actual unit tests. This type of testing should ONLY be used as a baseline so that you can start to do larger refactorings that could potentially break portions of code. This gives you the start of a safety net, albeit a pretty flimsy one.
Awhile back Joe Ocampo mentioned a technique that Michael Feathers called ‘vice’ testing. I recently came across an article on infoq where Ian Roughley calls it Logging Seam Testing. At the core, it’s the same thing just named a little differently. The article on infoq is in java, so I created a utility to do the same thing in c# that you can find in my github repository here. Here is a direct download link to a zip archive.
This is quite the interesting technique. One thing to note: I have yet to use this technique myself, so please take it with a grain of salt. Seems like this could work well for extremely tightly coupled, monolithic code and wouldn’t necessarily fit for every scenario. I could see this being a good fit while trying to reduce cyclomatic complexity or breaking large methods/classes into smaller ones. That being said, let’s dive in.
The basic idea here is you want to get some form of tests into your code, but it’s much too difficult to break dependencies and create seams to get unit tests in. That’s where vice testing comes in. It’s actually very simple and straightforward. The process goes like this.
- Determine what it is that you want to test, in this sample its the amount of deductions and the amount paid to an employee via an Employee.Pay method
- Insert logging statements in your production code that simply log internal state of an object. In the example it is deduction total, salary and ‘completed’
- Write a test that sets up the class under test, intializes the log4net logger, sets the expectations to be met
- Execute the method on the class under test and assert that all expectations were met via the ViceAppender class
First let’s look at the actual test code that would do the work for us:
1: [TestFixture]
2: public class EmployeeTests
3: {
4: private ViceAppender _viceAppender;
5:
6: [TestFixtureSetUp]
7: public void TestFixtureSetUp()
8: {
9: _viceAppender = new ViceAppender(new log4net.Layout.SimpleLayout());
10: log4net.Config.BasicConfigurator.Configure(_viceAppender);
11: }
12:
13: [Test]
14: public void employee_is_paid_expected_amount()
15: {
16: _viceAppender.AddVerification("deduction total=" + 70m);
17: _viceAppender.AddVerification("salary=" + 330m);
18:
19: IList<decimal> _deductions = new List<decimal>();
20: _deductions.Add(50m);
21: _deductions.Add(20m);
22:
23: var employee = new Employee(400m, _deductions);
24: employee.Pay();
25:
26: _viceAppender.PrintExpectations();
27: Assert.IsTrue(_viceAppender.Verify(), "Expectations not met");
28: }
29: }
In the example you can see that I am initializing a log4net logger and setting some configuration on it. Then you setup verifications on the ViceAppender class that matches expectations added to your class along with the expected internal state that will result from the input.
Here is the Pay method from the Employee class:
1: private ILog _log = LogManager.GetLogger(typeof(Employee));
2:
3: public void Pay()
4: {
5: // bunch of code outside the scope of this test
6:
7: foreach (var deduction in _deductions)
8: _salaryPerWeek -= deduction;
9:
10: _log.Info("deduction total=" + _deductions.Sum());
11: _log.Info("salary=" + _salaryPerWeek);
12: _log.Info("completed");
13:
14: // more code we don't want to test right now
15: }
Now that we have the expected output, you can now assert what was dumped to a log file and determine if your tests are passing or not. This is achieved pretty easily with a simple Expectation class and a derived Appender class that is called ViceAppender. We have a ‘Verify’ method here that will iterate over the logging statements using the message as a key and see if the expected message is actually in the logger. The verify method returns a boolean to indicate if all expectations were met during the test run. The message is used as the key on a dictionary. Therefore the message needs to match exactly in order to match an expectation.
1: public bool Verify()
2: {
3: bool result = true;
4: foreach (string key in _verifications.Keys)
5: if (!_verifications[key].WasCalled)
6: result = false;
7:
8: return result;
9: }
Also on the ViceAppender I have the PrintExpectations() method that outputs the expectations to the Console:
1: public void PrintExpectations()
2: {
3: foreach (string message in _verifications.Keys)
4: {
5: var sb = new StringBuilder();
6: sb.Append("Logger called '")
7: .Append(message)
8: .Append("'. Was Called? '")
9: .Append(_verifications[message].WasCalled)
10: .Append("'");
11:
12: Console.WriteLine(sb.ToString());
13: }
14: }
Produces the following output:
1: Logger called 'deduction total=70'. Was Called? 'True'
2: Logger called 'salary=330'. Was Called? 'True'
The benefit from doing this type of testing is no modification of the class under test needs to take place. All you need to add is logging statements and a field for getting at the ILog instance. This gives you a solid foundation to begin doing refactoring.
This could be viewed as integration tests as well as unit testing because your class under test may leak into other portions of code. Make sure you make your scope of your test as narrow as possible to combat the problem. This is a good place to start, but use wisely. It’s not meant to be a long term solution and can be abused just like any other technique.
After typing out some code and playing with it for awhile, You could get this to work without even using a logging utility and just make one yourself. The java example on infoq used the java equivalent of log4net so I did the same here. One other thing I left out was that Ian in his infoq article had the ability to assert on expectations that were called when not expected. While this is a good feature, I decided it was a little overkill for a simple example and left it out for brevity.
Post Footer automatically generated by Add Post Footer Plugin for wordpress. | http://lostechies.com/seanchambers/2009/04/22/vice-testing/ | CC-MAIN-2014-42 | refinedweb | 1,104 | 63.39 |
Skip navigation links
java.lang.Object
oracle.jbo.common.CharacterEncodingMapping
public class CharacterEncodingMapping
Provides two static conversion functions to translate between IANA names for character set encodings and JDK names.
The code for this class is partially generated, using the (unpublished) utility oracle.xml.parser.v2.MapReverser, the source for which is controlled by the Oracle Business Components for Java team. see and for the published list of JDK encodings. The JDK code in 1.1 and 1.2 is slightly incomplete: there are a few mappings defined in the doc that don't exist: ISO2022CN ISO2022KR, MS950 and GBK There's nothing we can do abpout that problem till its fixed by Sun
public static java.lang.String convertIanaToJdk(java.lang.String ianaName)
public static java.lang.String convertJdkToIana(java.lang.String jdkName)
Skip navigation links | http://docs.oracle.com/cd/E35521_01/apirefs.111230/e17483/oracle/jbo/common/CharacterEncodingMapping.html | CC-MAIN-2016-36 | refinedweb | 137 | 51.44 |
Discover the meaning of public, private and protected in the Java programming language. Public, private and protected are confusing for beginners, but once you understand how to use classes, they're actually quite simple.
When the video is running, click the maximize button in the lower-right-hand corner to make it full screen.
Code for this tutorial:
App.java:
import world.Plant; /* * private --- only within same class * public --- from anywhere * protected -- same class, subclass, and same package * no modifier -- same package only */ public class App { public static void main(String[] args) { Plant plant = new Plant(); System.out.println(plant.name); System.out.println(plant.ID); // Won't work --- type is private //System.out.println(plant.type); // size is protected; App is not in the same package as Plant. // Won't work // System.out.println(plant.size); // Won't work; App and Plant in different packages, height has package-level visibility. //System.out.println(plant.height); } }
Grass.java:
import world.Plant; public class Grass extends Plant { public Grass() { // Won't work --- Grass not in same package as plant, even though it's a subclass // System.out.println(this.height); } }
Field.java:
package world; public class Field { private Plant plant = new Plant(); public Field() { // size is protected; Field is in the same package as Plant. System.out.println(plant.size); } }
Oak.java:
package world; public class Oak extends Plant { public Oak() { // Won't work -- type is private // type = "tree"; // This works --- size is protected, Oak is a subclass of plant. this.size = "large"; // No access specifier; works because Oak and Plant in same package this.height = 10; } }
Plant.java:
package world; class Something { } public class Plant { // Bad practice public String name; // Accepetable practice --- it's final. public final static int ID = 8; private String type; protected String size; int height; public Plant() { this.name = "Freddy"; this.type = "plant"; this.size = "medium"; this.height = 8; } } | https://caveofprogramming.com/java-video/java-for-complete-beginners-video-part-25-access-modifiers.html | CC-MAIN-2018-09 | refinedweb | 313 | 50.43 |
TelemetryDeck client for Vapor
Usage
Once you have added the package to your project, you must initialise the library. This is usually done in
configure.swift.
import TelemetryDeck app.telemetryDeck.initialise(appID: "<YOUR-APP-ID>")
Sending a Signal
There are two ways to send a signal. One method is from the “system”, which contains a static user identifier.
try await app.telemetryDeck.send("applicationStarted")
The second option is from a request, this will set the user identifier to be a hashed version of the request IP address.
try await request.telemetryDeck.send("homePage") // for example: app.get("home") { req async throws -> String in try await req.telemetryDeck.send("homePage") return "your page content" }
Properties
You can attach additional payload data with each signal by adding
additionalPayload to the send functions.
try await app.telemetryDeck.send("applicationStarted", additionalPayload: [ "host": "gcp" ])
You may also configure TelemetryDeck for Vapor with a dictionary of default properties which are sent with every signal.
app.telemetryDeck.defaultParameters["key"] = "value"
Sessions
With each signal, we send through a session identifier which is a unique UUID generated on initialisation. This is intended to be different for each running instance of your server, changing each time you reboot the server.
Test Mode
If you launch Vapor in a non-release environment, signals will be marked as being in test mode. In the Telemetry Viewer app, actvivate Test Mode to see those.
Signal Batching
This library does not currently support signal batching. This means that signals are sent to TelemetryDeck as you call the functions. In a future release, we may add the capability to batch signals in memory and post them at regular intervals. | https://iosexample.com/vapor-client-for-posting-signals-to-telemetrydeck-a-privacy-conscious-analytics-service-for-apps-and-websites/ | CC-MAIN-2022-33 | refinedweb | 275 | 50.23 |
Created on 2015-12-18 12:29 by serhiy.storchaka, last changed 2016-01-17 04:54 by terry.reedy. This issue is now closed.
When open the About IDLE dialog and press the README button on bottom line, I get the UnicodeDecodeError:
Exception in Tkinter callback
Traceback (most recent call last):
File "/home/serhiy/py/cpython/Lib/tkinter/__init__.py", line 1548, in __call__
return self.func(*args)
File "/home/serhiy/py/cpython/Lib/idlelib/aboutDialog.py", line 127, in ShowIDLEAbout
self.display_file_text('About - Readme', 'README.txt')
File "/home/serhiy/py/cpython/Lib/idlelib/aboutDialog.py", line 139, in display_file_text
textView.view_file(self, title, fn, encoding)
File "/home/serhiy/py/cpython/Lib/idlelib/textView.py", line 74, in view_file
contents = file.read()
File "/home/serhiy/py/cpython/Lib/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 72: invalid start byte
That is because IDLE opens the Lib/idlelib/README.txt file with default (locale) encoding, while it contains the RIGHT SINGLE QUOTATION MARK character encoded with the CP1252 encoding and non-decodable with UTF-8.
I think IDLE should open all distributed files with UTF-8 encoding. Lib/idlelib/CREDITS.txt and Lib/idlelib/README.txt should be recoded to UTF-8.
New changeset 11c789c034fe by Terry Jan Reedy in branch '2.7':
Issue #25905: Revert unwanted conversion of ' to ’ RIGHT SINGLE QUOTATION MARK.
New changeset 42963dd81600 by Terry Jan Reedy in branch '3.4':
Issue #25905: Revert unwanted conversion of ' to ’ RIGHT SINGLE QUOTATION MARK.
Strange and accidental. This is the one line I kept from the old version, before deleting the old and adding the new. I believe I edited either with IDLE or Notepad++, and I would be surprised if the latter, an editor for programmers, would turn ' into ’. It does not for .py and .rst files. README.txt should be Ascii-only.
Larry, I applied the README.txt reverse replacement to 3.4 in case you feel like cherry picking it into 3.4.4, but it is not a blocker. No NEWS entries would be needed for 3.4 as this would fix an unreleased reversion.
For CREDITS.txt, the only issue is 'Löwis' (ö has latin-1 code 246), which was changed from Loewis in 2003. If not changed back to the ascii form, what matters is that the encoding used for decoding from bytes to unicode matches the actual encoding. AFAIK, it currently does
def ShowIDLECredits(self): # aboutDialog.py, line 130
self.display_file_text('About - Credits', 'CREDITS.txt', 'iso-8859-1')
No encoding is given for README.txt, line 133, because none should be needed. I am going to leave this alone for now.
New changeset 21356a5b8a5e by Terry Jan Reedy in branch '2.7':
Issue #25905: Specify 'ascii' encoding for README.txt and NEWS.txt.
New changeset 59852a79b508 by Terry Jan Reedy in branch '3.5':
Issue #25905: Specify 'ascii' encoding for README.txt and NEWS.txt.
I re-encoded CREDITS to utf-8 and specified 'ascii' for the other so *I* will see an error if a non-ascii chars gets in the file again. Serhiy, I am confident that this will work on all OSes, but feel free to test AboutIDLE again sometime.
(Note to myself) To automate a test that the files will open, change
from idlelib import textView # to
from idlelib.textView import view_text, view_file
and change display... and show.. methods to module functions so view_file can be replaced and the show functions called without involving tkinter. This can be part of future refactoring in 3.5+. | https://bugs.python.org/issue25905 | CC-MAIN-2019-22 | refinedweb | 606 | 61.93 |
in reply to Re^2: Synchronisation between multiple scriptsin thread Synchronisation between multiple scripts
Does your advisary locking of a pid file scheme, handle recovery after a system crash?
If you review the mentioned thread, the first node by shmem details how the script should verify that the listed PID is actually running the proper script.
Polling directories is a silly way to do things.
How long do you wait after the filename appears, before you decide that the application writing that file has finished doing so?
How do you detect if the process writing the file has hung or crashed part way through writing it?
Update: Corrected "rather than copied" to "rather than written" in the last sentence.
Update 2: Corrected HTML formatting of whitespace before update 1.
It is a relatively non-controversial fact that most people's attempts
to implement robust & recoverable resource serialisation
through advisory file locking, will fail under a myriad
of exceptional failure scenarios.
The most difficult of these to handle is complete systems failure
at critical points in the handshaking. That is, when both the
resource controller and the resource requester terminate simultaneously
with no possibility for cleanup, back out or status logging.
And even when starting with an expertly prepared and tested
scheme of operations, the process of adaption of that scheme
to the natural variations in application requirements, creates
ample opportunities to introduce subtle but fatal errors.
Upon restart, the advisory locks are simply forgotten;
pid files may exist but the processes no longer do;
or worse, the pids have been reallocated to completely unrelated processes.
And the shared resource transaction can be in any state.
Using the OPs example of a file transfer, the file in question
may not yet exist in the application space;
may exist in a partial form in the application space;
may exist in a completed form in the application space;
It may exist in the controller space in any of those three forms.
That is, the name of the file may have been recorded within the
transfer processes namespace, but the handover of the file
may not yet have started;
may have started but not completed;
may have completed but not been cleaned up.
And if the handover has completed and been cleaned up (in the application space)
the transfer may not yet have started;
may have started, but not yet been completed;
may have completed, but not been cleaned up;
In the absence of persistent and atomic, bilateral status recording,
a complete systems failure can leave either end of the transaction
with no information; or partial and differing information.
I've yet to see a resource serialisation scheme, based around advisory file locking, that gets it right in all scenarios. And I once wasted nearly 3 months on a critical project waiting for the experts to do so.
1. Keep it simple
2. Just remember to pull out 3 in the morning
3. A good puzzle will wake me up
Many. I like to torture myself
0. Socks just get in the way
Results (283 votes). Check out past polls. | http://www.perlmonks.org/index.pl?node_id=736784 | CC-MAIN-2016-44 | refinedweb | 516 | 58.32 |
KEYNOTE(3) BSD Programmer's Manual KEYNOTE(3)
keynote - a trust-management system library
#include <sys/types.h> #include <regex.h> #include <keynote.h> struct; }; ac- tual length of the encoding stored in dst is returned. dst should be long enough to also contain the trailing string terminator. If srclen is not a multiple of 4, or re- turns -1 and sets keynote_errno to ERROR_SYNTAX, denoting either an in- valid); The length of the allocated buffer will be (2 * srclen + 1). On success, this function returns 0. On failure, it returns -1 and sets keynote_errno to ERROR_MEMORY if it failed to allocate enough memory, ERROR_SYNTAX if if it could not allo- cate enough memory, or ERROR_SYNTAX if dst was NULL, or the length of src is not even. kn_encode_key() ASCII-encodes a cryptographic key. The binary representa- tion allo- cated and should be freed after use. On failure, NULL is returned.
keynote.h libkeynote.a
keynote(1), keynote(4), keynote>
The return values of all the functions have been given along with the function description above.
None that we know of. If you find any, please report them to <keynote@research.att.com> MirOS BSD #10-current April 29, 1999. | http://www.mirbsd.org/htman/i386/man3/kn_remove_authorizer.htm | CC-MAIN-2015-35 | refinedweb | 200 | 67.55 |
1
2 3
4 5 6
7 8 9 10
please help me
Are you short of words or expressions or you can't type or the keyboard is not working or just not having enough time to properly ask your doubt's :icon_exclaim::icon_exclaim:
And you are thinking that we are having a lot of spare time to not only solve and answer your questions but also to understand the what you are asking for....
This is just not done...right ????
int main() {
printf("1\n2 3\n4 5 6\n7 8 9 10\nplease help me\n";
}
Edited 7 Years Ago
by griswolf: n/a
People around here get very angry when people start threads with posts like that. Try to be more expressive and also a little more polite (otherwise it can get a little nasty). People are happy to help but they don't want to feel used and abused. It is a great forum and some people really know their stuff. Plus we do want help but not fully do your homework, with no input or effort on your behalf.
On this occasion here is the solution to your problem.
#include <stdio.h>
int main() {
int num = 1, lineCount, i;
for(lineCount = 1; lineCount <= 4; lineCount++) {
for(i = 0; i < lineCount; i++) {
printf("%d ", num++);
}
printf("\n");
}
return 0;
}
Edited 7 Years Ago
by nateuni: n ... | https://www.daniweb.com/programming/software-development/threads/297027/nested-loop-print | CC-MAIN-2018-22 | refinedweb | 231 | 72.7 |
Agenda
See also: IRC log
<tlr> trackbot, start meeting
<trackbot> Date: 20 February 2013
<sidstamm> hi all, I'm double booked today and will be on IRC for now but try to dial in later
<npdoty> meeting: Tracking Protection Working Group teleconference
<npdoty> chair: peterswire
<Walter> :-)
<Walter> tlr: it has become self-aware?
<tlr> that isn't novel
<Walter> it still should be open sourced
<peterswire> 404 number is swire
<sidstamm> hi all… regrets for missing the beginning of the meeting. I'll be watching IRC for now but try to dial in later.
<peterswire> ok, i muted until we start. took care of background noise?
<Walter> peterswire: yes, that was helpful
<Walter> peterswire: if you can get a headset at the last minute...
<peterswire> the noise was the chair's effort to eat before the call; sorry on that
<npdoty> volunteer to scribe?
<Walter> sorry, it is bloody hard when you're on skype and not a native speaker
<npdoty> scribenick: moneill2
review Boston work plan
<vinay> zakim mute me
constructive meeting in boston now time for action items
<aleecia> Thanks Adrian, I'm aware. It's just good to have the agenda linked in the minutes properly. It was a hint. :-)
def of service provider 1st - do that later
market research is now 1st
<justin> Richard Weaver
<eberkower> ComScore = Richard Weaver
chris pedigo now on, so back to service provider
service provider works only for you i,e is an agent
controller and processor in US and in EU
<fielding>
chris pedigo worked on these issues before, peter has talked to chris about taking this on
<aleecia> (note we do not have liability for controllers due to their processors in the US, a rather important change. I repeat myself, but it appears to keep getting dropped as a rather important issue.)
<fielding> +1 for processors
<Walter> +1 too
<aleecia> -1
peter suggests using European data processor definition
<aleecia> suggests a legal basis we do not have
<dsinger> moving to a more general term might help the "processor for a third party getting consent" (minor) issue
<Walter> hm, good point, another question is how it meshes with the 1st and 3rd party issues
alleecia, EU has different legal regime than US
<rigo> Aleecia: data controller has no liability if the data processor does something wrong
<haakonfb> Agree with Aleecia's points
Peter, US does not have a def. of service provider
<Walter> rigo: that is not true everywhere in the EU, in .nl it is a classic principal-agent relationship
<aleecia> we rejected data processor explicitly, Rigo
susan israel, terms would be allocated by contract in US
<aleecia> and yes, it was long ago
susan, we should not make a block statrement
<justin> Not sure I agree with aleecia's point, but I could see objections if we picked the word "agent" for the specific reasons she articulates.
<rigo> aleecia, we agreed to name it service provider and in the definition we agreed to use the processor definition
dwainbewrg, shares aleecias concerns
dwainberg: blank slate bad idea
<aleecia> ah, I thought you were discussing terms not definitions, Rigo.
<rigo> we said "service provider" and David Singer had text
<kulick> did dwainberg say he believes blank slate WAS a bad idea?>
<amyc> I think he said the opposite
<kulick> i thot so, thx
<dwainberg> no,kulick, good idea
walter, davids concerns valid but do not share them, prefer to have conv. on email. Maybe agent better term
<kulick> ok, thx
<rigo> aleecia, we said "service provider" to avoid offending US feelings, remember? :)
peter: agency law much overlap
peter, chis has agreed to work on this.
<fielding> The term "service provider" is used in a hundred different contexts to mean a hundred different things; it is an awful choice for a defined term. In our context, it is normally used to refer to the either the entity providing user access to the Internet or the hosting provider for a site.
<aleecia> rigo, that's not the summary I would give. :-) But we are remembering the same conversations, including David Singer
<Walter> fielding: +1
<vinay> I'd like to work with chrispedigoopa on the definition
peter: anyone else work with chris?
<ChrisPedigoOPA> sorry, got dropped from the call
<ChrisPedigoOPA> let me know who wants to work with me
peter, chris - what time frame
<aleecia> we ran into issues with different legal regimes. The trick was to find something that works in all, without implying things untrue. We had this conversation even more strongly around using "first party" or not
<aleecia> Near as I can tell, we were at consensus to use "service provider" and we are undoing prior work.
chris, this is defining term right?
<fielding> Using the term "data processor" as it is defined by the EU does not import the EU laws -- it just makes it far easier to know who fits the definition and far less likely that our arbitrary redefinition won't be wrong.
chris, something by next week
<npdoty> ACTION: pedigo to work on updated "service provider"/"processor" definition (with vinay) [recorded in]
<trackbot> Created ACTION-368 - Work on updated "service provider"/"processor" definition (with vinay) [on Chris Pedigo - due 2013-02-27].
<aleecia> Roy, in general name space collision is a confusing thing
<aleecia> sure
<rigo> "Agent" would be also cool. And some of the trackers are then "secret agents"
<aleecia> rigo++
<Walter> :-)
nick, if we cant resolve now we should hae brief turn on email
<johnsimpson> are we trying to decide what to define or what are we doing?
<fielding> at the W3C, agent is already a defined term
<aleecia> Chris is defining a term we're not sure we should use :-)
<rigo> fielding: Party pooper
<rigo> :)
<johnsimpson> are we saying they are three different things?
what about processor?
<npdoty> peter is looking for volunteers to support: service provider, agent and processor/controller?
<ninjamarnau> I think Peter meant processor instead of controller
<aleecia> We might summarize existing work on the mailing list as well
peter, continue on list
<Walter> moneill2: that's what aleecia and dwainberg are uncomfortable with
<tlr> +1 to aleecia
peter, next item Market Research
<Walter> oh, drat, that was scribing, apologies
<aleecia> Rather than risk losing that to a blank slate approach
<npdoty> +1 to aleecia, tlr, if someone can summarize the past history on the list, that would be great
<johnsimpson> what is Chris defining?
peter, current definition too broad
<rigo> johnsimpson: processor
peter: industry say anything can be market research unless otherwise defined.
<aleecia> nick we should likely figure out who has the action here. The two of us or the editors would be good candidates. This is not an open week for me, so I'd rather either have two weeks or better yet find someone else to take it.
<johnsimpson> so are we saying that processer and service provider are the same thing?
peter, no consensus currently on definition
<aleecia> @johnsimpson we're waiting to see if Chris suggests that, we're not saying anything yet
peter, many say DNT: 1 means no tracking of any kind
peter, justin brookman has agreed to work on this with others. Action item?
<Richard_comScore> David and I are working on the MR definition
<rachel_thomas> DAA definition of market research isn't "unbounded." Here is the definition - specific computer or device. Thus,[CUT]
peter, david stark not on call
<Richard_comScore> We have scheduled a call with Justin to discuss further
<dsinger> I think it would help to understand what aspects of market research need personally identifiable data, and how that identifiable data can be narrowly scoped in both breadth of data and retention times
<aleecia> Is there someone in {Nick, David Singer, Heather, Justin} up for summarizing where we are on service providers to the mailing list, since this is not a great week for me?
<tlr> justin, were you trying to queue?
<susanisrael> I am also willing to help with the market research definition
<aleecia> walter: market research with DNT:1 makes it a farce, particularly in EU
<aleecia> walter: this was shot down in earlier F2F, in Oct, then long time of silence.
<justin_> I was on the queue for the previous discussion (service provider) but that moment has passed :) I'm sending my concerns to Chris and Vinay.
<hefferjr> I am also very interested in this topic, and would like to be involved.
<dsinger> to aleecia: I am not 100% sure I understand the current state myself; I think the first_party resource plays here, but exactly how I need to understand
<aleecia> … in favor of having this process so if someone wants to bring up a concept, come up with a proposal (missed rest)
walter, dnt:0 OK for permitted use for market research. Definately not for DNT:1 - would make this a farce, thought this had already been discussed, in favour someone needs to come up with concrete proposal
rachel_thomas: daa definition is very valid
<aleecia> @david, ok, here's where it's sold, here's where it's not in prior work is useful. If I take a first pass will you sanity check me? This will need 2 weeks on my side.
<fielding> IIUC, the "unlimited" refers to the scope and amount of data collected, not the purpose to which the data is used.
<vinay> Thanks justin_.
<justin_> "'market research' is . . . analysis of . . . consumer preferences and behaviors" (inter alia) . . . that's not a lot of bounds!
<rachel_thomas> justin, it's important to note the bounds on the definition - NO "sales, promotional, or marketing activities directed at a specific computer or device."
<vincent> "research about consumers, products, or services" seems quite broad to me
mikez: daa def. not unbounded, any permiotted use would be unlimited
<ninjamarnau> to me this definition sounds fairly unbounded. Why not use just anonymized data?
<susanisrael> moneill2, what I think Nick was trying to say is that it was Rachel, not me, speaking to defend the DAA definition
<rigo> I think the major issue is the "identified" vs "identifiable". So pseudonyms seems to be on one or the other side
<aleecia> ACTION: aleecia to summarize texts, agreements, and uncertain bits to data around service providers (ideally with dsinger and perhaps npdoty, if willing) [recorded in]
<trackbot> Created ACTION-369 - Summarize texts, agreements, and uncertain bits to data around service providers (ideally with dsinger and perhaps npdoty, if willing) [on Aleecia McDonald - due 2013-02-27].
<kulick> rachel_thomas, could you please provide a link to the published definition?
<aleecia> there's no way that's pending review :-)
<rachel_thomas> published DAA definition, see page 10:
mikez: market research necessary for internet economy, this issue is not closed, some discussion had been folded into other language, but need for market reseach remains strong
<kulick> thx
<vinay> Kulick -- has the overview + a link to the full text
<justin_> rachel_thomas, sure, but that's not really research! You could prohibit the teasing of otters too, but that wouldn't be a huge limitation :)
<Zakim> dsinger, you wanted to ask about identifiable data
<Walter> rachel_thomas: you're sidestepping that the collection of the data in the first place, regardless of its goal is hard to swallow, especially given a clear opting out signal
davidsinger, if data id unidentifiable then no longer in scope
<Walter> very valid question, if it is unidentifiable it is indeed out of scope anyway
<aleecia>
<rigo> support for David
dsinger, lets see proposal why identifiable data needed
<dsinger> Given that we consider un-identifiable data OK (out of scope) -- either de-identified or aggregate counts -- I think I need to understand why identifiable data is needed, and how a definition would scope what the data is, how long it will be kept, and how use
<rvaneijk> (... commuting with bad wifi)
peter, good suggestion from david
<aleecia> oops, wrong issue, sorry -
<rvaneijk> unlinked counts as well !
<rachel_thomas> q_
<aleecia> we were here:
peter, thought is there is a subset of market research where who need identifiers, this could narrow the universe
<npdoty> Kathy Joe from ESOMAR also presented this proposed permitted use:
<rigo> scribenick:rigo
<moneill2> rachel_thomas, not accurate to say self reg codes only followed by academics
<rachel_thomas> that's not an accurate description of how market research self-regulation works. market researchers within companies abide by those same standards across all industries.
<npdoty> proposed actio: weaver to propose narrower "market research" use (with David Stark, Justin, Susan, Ronan)
<hefferjr> hefferjr
<moneill2> peter, anyone else work on this?
<rachel_thomas> I'm happy to participate in that group as well, please.
<fielding> There are no bounds constrained by the DAA definition. Whether it makes sense to have a market research exception or not, we have to be realistic about the implications of data collection that has no limited purpose, no limited scope, and no inherent consent. Actual market research uses consent. This collection is just to select a sample of applicable users (a focus group), which doesn't justify an exception to DNT:1.
<scribe> scribenick: rigo
<dsinger> fielding++
<Walter> fielding: again, +1
<eberkower> Please add Elise Berkower to the list
<johnsimpson> Wasn't there already language proposed on this?
<eberkower> thank you
<moneill2> peter, david stark, richard, jbrookman, susan israel, rachel thoma, chris meija,
<tlr> peter: David Stark, Richard Weaver, Justin Brookman, Susan Israel, Rachel Thomas, Chris Mejia, Ronan Heffer, Elise Berkower to work on "market reasearch" proposal
<susanisrael> yes, I volunteered so that I can call upon the expertise of a colleague who could help
List: Chris Mejia + ?? from Nielssen
<npdoty> proposed actio: weaver to propose narrower "market research" use (with David Stark, Justin, Susan, Ronan, Rachel, Chris_M, EBerkower)
<aleecia> I am curious to know if any prior decisions are expected to carry over, and if so, how we are to know which ones.
<hefferjr> Ronan Heffernan and Elise Berkower are from Nielsen
<moneill2> tlr, thanks
<eberkower> Ronan Heffernan and Elise Berkower from Nielsen
<susanisrael> rigo, I think Ronan and Elise were from nielsen
PS: how is the difference between market research and not just gathering data
<moneill2> peter, lets get that in 2 weeks
PS: will follow up by email with the group
<johnsimpson> WHAT ABOUT THE TEXT THAT WAS ALREADY PROPOSED?????
PS: slightly change the agenda because of speaker available
<moneill2> peter, talk about security matters then return to de-id
<susanisrael> npdoty, I think 2 people are trying to scribe at the same time
<npdoty> ACTION: weaver to propose narrower "market research" use (with David Stark, Justin, Susan, Ronan, Rachel, Chris_M, EBerkower) [recorded in]
<trackbot> Created ACTION-370 - Propose narrower "market research" use (with David Stark, Justin, Susan, Ronan, Rachel, Chris_M, EBerkower) [on Richard Weaver - due 2013-02-27].
PS: Guest Speaker is John Callas, Security expert. CTO of PGP, later at Apple, security for OS, CTO of intrust, this year new venture
<moneill2> peter, introduces john callas
<scribe> scribenick:moneill2
<johnsimpson> What is the status of this text???
peter, permitted use is essential are, people disagree about duration
<johnsimpson> Issue 25
<johnsimpson> Aggregated data
<johnsimpson> 6.1.1.1 Short Term Collection and Use for market research
<johnsimpson> Note
<johnsimpson> Information may be collected and used for market research and research
<johnsimpson> analytics, so long as the information is only retained for the time
<johnsimpson> necessary to complete the research study. This is providing that the raw
<johnsimpson> information is not transmitted to a third party, the information is not used
<johnsimpson> to build a commercial profile about individual users or alter any
<johnsimpson> individual's user experience, and there is no return path to an individual.
petr, need sense of whats needed in real world
<johnsimpson> A key method for ensuring privacy while collecting and processing large
<johnsimpson> amounts of data is removing any link to a device identifier. Raw data for
<johnsimpson> market research may contain for example an IP address or a marker for a
<johnsimpson> cookie, which may be temporarily retained for sample and quality control as
<johnsimpson> well as auditing purposes. No individual can be identified in the subsequent
<johnsimpson> aggregated statistical report.
<aleecia> Nick - jsyk - updated action-369 (new on this call against me) for three weeks out, since I will not have time in the next two weeks. I still suggest someone else take this one.
<johnsimpson> did phone go dead?
peter, discussion with Rina Mears about auding, will come back in 3 weeks
<rachel_thomas> lost peter...?
<npdoty> aleecia, I don't feel particularly informed about the history of that issue, or would take it
<hefferjr> audio is still good for me
<johnsimpson> lost peter
peter, john callas?
<jon> I am here, too.
<johnsimpson> will call back in
<rachel_thomas> calling back in
<aleecia> thanks Nick, I appreciate that - just a busy time here
peter, john give us a sense of service attacks, length time needed to reatin datra
<susanisrael> *Nick, do you want me to scribe?
<susanisrael> +npdoty, ok, good
john callas, been on both sides, you need both marketing f=data and security data, they should be different,
<johnsimpson> zamik. mute me
<aleecia> confused. what time outs on data?
john callas, way to look at timeouts - time from incident also time you are doing investigation + time after to retain data
jon callas, when does timeout start
<aleecia> ah. speaker is assuming a fixed and short retention period. missed that.
<npdoty> aleecia, I believe Jon is referring to time-based retention limits
<aleecia> thanks nick
john callas, hard to de-identify ip address
peter, how long to people retain ip addresses
<aleecia> solving the problem -> dealing with security threats? or protecting privacy?
Jon Callas, we are more interested in solving problem, not go on for weeks or months, need to collarte them between attacks, how do you manage that?
<vincent> I'd say, it's the first
peter, clickfraud how to manage?
<ninjamarnau> data retention and data sharing are two issues. We should keep these seperate.
Jon Callas, something of a longer time period needed -
<dwainberg> there's impression fraud, as well
peter, 60,90 days, years?
Jon Callas, midpoint
Jon Callas, rule of thumb - bno standard
Jon Callas, depends
peter, how long to resolve incident
<peterswire> david -- I see you, and will look for a break
Jon Callas, cant resolve on same computer - need to do it on network, holding data that is active is reasonable
peter, how long second period
<rvaneijk> (... off to bike home, will try to catch the last part of the call)
<dwainberg> here's my question, if you want to pass it on: what about the problem of identifying and learning to detect problems. In the ad biz you may not understand there is a problem until retrospetive pattern analysis on months worth of data.
Jon Callas, 60-90 days a long period but always exceptions, but often just a few weeks
<aleecia> are we expecting retention limits for first parties as well?
john callas, you would keep summary for to help with next attack
<rigo> if an investigation is ongoing, nobody disputes that you could keep data, rather after end of incident and protocol chatter without default storage incident
Jon Callas, relatively long perios for some attacks, otherwise not needed
Jon Callas, need to separate security data from marketing data
peter, how to separate
Jon Callas, admin controls only
peter, logging., auditing
dwainberg, ad biz has problems other than clickfraud, need to do retrospective pattern analysis
dwainberg, hard to put timeframe on that
<fielding> I cannot underemphasize this … No changes will be made to security data collection or analysis based on the presence of DNT:1. Security is not subject to opt-out (not even in the EU). It is sufficient to ensure that such data is only retained when (and as long as) necessary for the security purpose and not used for any other purpose.
<rigo> but if the user is not tracked, the ad network gets less money, so no real incentive for click-fraud with DNT:1
<johnsimpson> Roy makes an interesting point in IRC
Jon Callas, needs for security to have much data
cookie UIDs or just IP addresses
<rigo> fielding++
?
<amyc> rigo, that is not correct
<aleecia> if your customers think they are overpaying, Rigo, they are less likely to use your business
<Brooks> there is also an aspect of seasonality to data. ESPN.com sees very different traffic behavior in March (march madness) than it will the other 11 months of the year
<vincent> for those interested, a pretty neat paper on various kind of frauds: conferences.sigcomm.org/imc/2011/docs/p279.pdf
dwainberg, some activity is just strange, not fraud but you cant pin it doen, bots, spiders
<aleecia> for seasonality, presumably espn.com has ample non-DNT:1 traffic to get a handle on that
dwainberg, have yet to identify some
<aleecia> (in response to Brooks)
peter, why not keep data for ever?
<hefferjr> but all of the fraudulent bots might turn-on DNT:1 to try to slip through undetected. only analyzing DNT:0 (or other non-DNT:1 traffic) could be very counter productive
Jon Callas, not forever - breach disclosures a problem, so data deleted when upgrades, new tech etc,
<justin_> john callas: risk of data breach can be a forcing function to limit retention. But many in the field believe that Big Data can solve all the problems. Also, the data is less valuable over time.
<Brooks> Aleecia, so if I want to behave badly, I just need to issue DNT:1?
Jon Callas, mobiles very common now
<hefferjr> +Brooks
Jon Callas, 5 yrs too long for mobile
<aleecia> it appears we are having different conversations, Brooks. If you are talking about security, that is a different set of issues.
peter, sub poena
<rachel_thomas> subpoena :)
<aleecia> it seemed you were talking about seasonality which does not seem like the sort of thing you need lots of DNT:1 data for
<justin_> john callas: having to deal with subpoenas/e-discovery is a cost. A deletion policy is one way to mitigate those costs (or aggregation/anonymization)
john callas, ediscovery need policy when to delet, deononymise data
<Walter> rigo: yes, I'm noticing it as well
Jon Callas, nothing is immune to ediscovery request
<justin_> john callas: Security logs are not immune from discovery requests.
<Brooks> not an easy place to have a discussion of the differences between "security" and "quality" and "fraud"
peter, tagging purposes of data - how does that work
<aleecia> fair enough. and my brain is in fog from being sick (again) so if I do not follow, odds are good it is at least primarily my failing
Jon Callas, simple admin controls can do that, we dont share security data for marketing purposes
peter, segregation in databases
Jon Callas, meningless these days - adminb controls enough
<dsinger> "Information may be collected, retained and used to the extent reasonably necessary for detecting security risks and fraudulent or malicious activity. This includes data reasonably necessary for enabling authentication/verification, detecting hostile and invalid transactions and attacks, providing fraud prevention, and maintaining system integrity. In this example specifically, this information may be used to alter the user's experience in order to reasonabl[CUT]
<dsinger> a service secure or prevent fraud. Graduated response is preferred when feasible.
<dsinger> There has been an unresolved discussion on whether "graduated response" should be in the normative text, defined, addressed through non-normative examples, or not included at all."
dsinger, already have definition - have you read it?
<aleecia> David, could you read it?
<aleecia> I think that might help the discussion.
<npdoty> great!
<aleecia> ooh, speaker reading on IRC, cool
Jon Callas, not yest - reading now - np problem with that,
<Zakim> dsinger, you wanted to ask about the text we have
Jon Callas, i am willing to accept that
dsinger, limoited purpose is key
<npdoty> I think we separately note in a section above "no secondary uses" and "data minimization"
<aleecia> Yes, that's a global for permitted uses
<fielding> Note that first party sites often use third parties to estimate security risk based on pattern recognition, which would fall under the general category of "sharing" for a limited purpose.
Jon Callas, logs kept 7-10 yrs would raise eyebroes but 60 dayta or so no problem with that
<justin_> fielding, wouldn't service provider/data processor exception apply in that case?
<dsinger> to fielding: but they do this under a contract, such that results on their data only come back to them? i.e. they are an 'agent'? or is the data merged into a pool that all get benefit from?
<fielding> justin_, no because they don't silo the data -- it is based on multiple site patters
<npdoty> justin, do we need to clarify in "No Secondary Uses" that data can't be re-used for a different purpose, even if that purpose is permitted?
chrism, new use case -c consumer protection taskforce - privy to top security experts - one case is threqt discovered last 6 mo
<justin_> fielding, Hrm. But can individual users or devices be correlated across those databases if they're really just pattern recognition evaluators?
chrism, prosecuter asked how long back attack was happening
<npdoty> justin, so that data retained for a long time for security can't be re-used later for some other purpose?
chrism, so far can go back 5 yrs, prosecuter wants it not only to determine harm but how to punish crims
<justin_> npdoty, Well, if there's an independent and separate exception . . . so what? What's the threat you're worried about?
chrism, over 5 yesrs - law enforcement needs historical info
<rigo> nick, strange, I'm locally muted
chrism, are you familiar?
Jon Callas, yes good to putting bad guys away
<peterswire> restitution
chrism, retribution also imp.
<fielding> justin_, I wouldn't say they are "just" using patterns (this is an extraordinarily NDA'd subject area) -- the purpose is definitely to distinguish bad individuals (or zombies) from good individuals and I am not completely familiar with the techniques used.
Jon Callas, payback imp - but data being held on innocents also important. needs balance
Jon Callas, privacy very important to people]
<npdoty> justin, using years of security logs for frequency capping, market research, anonymizing longitudinal data after years for other purposes...
chrism, some place reasonable - but hard to say where it is
chrism, balanvce - control rather retention
<fielding> … and unlike the ad case, first parties are typically looking for purchase fraud or ineligible buyers (like concert ticket vendors have to prevent market resellers from purchasing all tickets in the first 3 seconds they go on sale)
aleecia, happy with text applied to 3rd parties - is there a distinction betwwen clickfraud and viewfraud
<justin_> fielding, So are you proposing to add "share" to the security permitted use?
Jon Callas, no differenece from security pov, but clicks & views shouold not be kept forever
<Chris_IAB> respectfully, that's a personal opinion for John as a consumer.
<fielding> justin_, yes, though in very limited form "share for the exclusive purpose of security" or something
Jon Callas, retention limited but lock up bad guys
<fielding> … and under NDA
peter, john is committed to privacy and security so useful input,
Jon Callas, dnt important to eveybody security need not diminish privacy
<npdoty> justin, or a dis-incentive to developing any more privacy-preserving techniques for frequency capping, ad reporting, etc. if they can just re-use security data
peter, helpful some commentary on retention versus ?
peter, de-id issue
<Chris_IAB> security issue - retention vs. control
<aleecia> truncated uri does not have an issue, either, so far as I know
<aleecia> cannot understand Dan
cannot hear
<justin_> npdoty, Well, that presumes market research as a permitted use! Otherwise, hard to imagine a scenario where the data wasn't required for a while, and then suddenly became required . . .
<Chris_IAB> inaudible
<aleecia> better!
<peterswire> +1 on justin
<Chris_IAB> justin_ that's funny :)
<aleecia> <grin>
dn, have yet to sync up with ed, later this week
<npdoty> ACTION: auerbach to propose text on de-identification (with Ed) [recorded in]
peter, ed interested in tech steps to de-identify
<trackbot> Created ACTION-371 - Propose text on de-identification (with Ed) [on Dan Auerbach - due 2013-02-27].
peter, rob v eijk and shane wiley had interesting conv.
<npdoty> rvaneijk, are you back?
<rvaneijk> yep, but not on the phone..
<rigo> rvaneijk: can you come to the phoneconf?
<npdoty> rvaneijk, we were just trying to get an update on your conversations with Shane
<rvaneijk> no, Peter has my notes.
peter, any other items?
<Zakim> dsinger, you wanted to ask about de-id: people or the data?
dsinger, de-id means cant identify person
<johnsimpson> Was there an action item on market research?
dsinger, how dos shortening urls deidentify people
<npdoty> johnsimpson, we have an action item on Richard Weaver on that topic
<aleecia> action-370?
<trackbot> ACTION-370 -- Richard Weaver to propose narrower "market research" use (with David Stark, Justin, Susan, Ronan, Rachel, Chris_M, EBerkower) -- due 2013-02-27 -- OPEN
<trackbot>
<dsinger> ok, so you saying that even when de-identified, it's prudent to do data reduction as well?
peter, if you had smallish bucket then urls may idenytify smaller group and therefore uidentify person
peter, url reduction may ne enough
<aleecia> david++
dsinger, pattern of use if only hostnames
<fielding> sounds like a typical MIT student
<Chris_IAB> those aren't marketing collection categories
<tlr> "stem" = host name?
aleecia, you can fingerprint based on hostames (url stems)
<vincent> it's not enough but it may help, also depends if you have the timestamp
aleecia, needs to be kept as issue
<npdoty> one concern has been that the URL data might *itself* be identifying (even if it's not attached to a real-world device or cookie id)
aleecia, when combined with activity over time, dont know how much but we need to kepp it in mind
<Chris_IAB> aleecia, would that be akin to a "partial print"?
<vincent> interesting paper on that topic: "Why Johnny Can’t Browse in Peace: On the Uniqueness of Web Browsing History Patterns" ()
dwainberg, primary concerns is what people are reading online - this needs to be pursued
<dsinger> at the moment I am merely puzzled, neither opposing nor supporting, but wanting to understand what's being suggested
<aleecia> Roy - yes! at CMU we researched a hypothetical anthrax attack on the Super Bowl. The FBI must've learned that every two years, there was a week of activity with this homework assignment… it was one of those "why didn't I use Tor?" moments for me.
peter, thanks
<npdoty> thanks all
This is scribe.perl Revision: 1.137 of Date: 2012/09/20 20:19:01 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/dwainberg,/dwainberg:/ Succeeded: s/pete, agencie/peter: agency/ Succeeded: s/peter, /peter: / Succeeded: s/peter, industry/peter: industry/ Succeeded: s/susanisrael, daa/rachel_thomas: daa/ Succeeded: s/mikez, daa def/mikez: daa def/ Succeeded: s/mikez, market/mikez: market/ Succeeded: s/skope/scope/ Succeeded: s/without// Succeeded: s/supoena (cannot spell taht)/sub poena/ Succeeded: s/johncallas/Jon Callas/g Found ScribeNick: moneill2 Found ScribeNick: rigo Found ScribeNick: rigo Found ScribeNick: moneill2 Inferring Scribes: moneill2, rigo Scribes: moneill2, rigo ScribeNicks: moneill2, rigo Default? Chris_Mejia Agenda: Found Date: 20 Feb 2013 Guessing minutes URL: People with action items: aleecia auerbach pedigo weaver WARNING: Input appears to use implicit continuation lines. You may need the "-implicitContinuations" option.[End of scribe.perl diagnostic output] | http://www.w3.org/2013/02/20-dnt-minutes | CC-MAIN-2015-48 | refinedweb | 5,234 | 52.63 |
[Kevin] wanted a display where he could take a quick glance and get all the current environmental information he uses throughout the day. That information includes, of course, the time and date as well as weather information. We’re not just talking the current weather information but the forecast for the upcoming week as well as a map showing current weather patterns. To do this, [Kevin] came up with a unique system he’s calling the PiClock.
[Kevin] did some serious programming to get this clock project off of the ground. The weather data comes via the Weather Underground API and the map data from the Google Maps API. The main program is written in Python and will run on any OS running Python 2.7+ and PyQt4. If you’re interested in doing something similar, check out the source at github.
From the project’s name, it is no surprise that a Raspberry Pi is the brains here. A USB WiFi adapter allows access to the internet but an Ethernet connection would do just fine. Having the RaspPi hanging out with wires everywhere would be a little lazy, so [Kevin] opened up his 19″ LCD monitor and mounted the RaspPi inside the case. He tapped 5vdc off of the monitors power supply and used that to power the RaspPi, no external wall wart necessary! And if the PiClock’s background isn’t cool enough, some RGB LED strips were mounted to the back of the monitor to give an Ambilight effect.
48 thoughts on “PiClock – Time And Weather Information Overload”
Very nice. I must make one of these.
Clean, check. Useful, check. RGB LEDs, check. Meets all the requirements of an awesome project, congrats! Might make one too.
And not an arduino in sight… blessed be!
well a raspberry pi running python is hardly more creative than programming an arduino.
Maybe if the creator flipped the bits of a 68000 using only a jar of butterflies glinting sunlight off their wings, you’d be pleased :P
Actually achieving this with an Arduino would be impressive (not to mention impossible) :D
But I just don’t get the point of being “featured” here.
He took an off-the-shelf pc (raspi) and wrote a python script doing some Qt magic
LED?
This is awesome, exactly what I wanted for a project and I already finished everything but the software. Never had time to sit down and write it myself and I failed to find anything appropriate on the Internet. Ended up using XBMC with a custom plug in for now, but it’s really awkward.
Two things I’d like to change about this clock (or to be flexible rather) is to have a digital face instead of analog and somehow to be able to change the background image (my ultimate desire is to have Astronomy Picture Of the Day there).
So I guess I’m switching to this solution and will have to tweak it a bit.
Great job!
P.S. Tip: a great display for such projects is Motorola’s LapDock. If you disassemble it you’ll find a great LCD panel there with a compact HDMI controller.
It would be more useful with a HaD feed. ;)
I don’t see why he couldn’t do this with a 555 timer, a single resistor and some magic cat hair, to many components IMO
but honestly, pure awesome, love the effects :D
Anyone else think that this is reminiscent of Deus Ex: Human Revolution’s computer terminals?
Has anyone else tried this? I thought this would be a great addition to the office so I tossed one together. After following the directions I got it all built but I’m hitting a few snags.
1. The audio from NWS comes through great, but I’m getting what seems like a 4 Hz tick through the audio feed.
2. I have a key registered with WU but I am not getting any forecast. The Google side of the house works great as wel las the clock.
Any ideas?
I’ve been working with Chris to get things working, and he helped me uncover a few bugs as well.
I know it’s been almost a year since you’ve commented, but do you know if it’s possible to display tide information with the moon phases or in lieu of the moon phases? Thanks!
If its in the weather undergound api data, then its pretty straight forward… Just dig into the code and string together the data in place of where the moon data is put together.
I Replaced the weather Feed with a Local radio stations Stream the Station KLRC They will broadcast KNWA during Severe weather. May look into your favorite radio stations stream.
For this to work properly do I need a paid Weather Underground account? WU give me 500 request a day for free, but I see that I am making , on the order of 40 requests an hour. This seems to be the 4 radar displays updating about every 6 minutes. Any suggestions on a strategy on running this on a free WU account?
I’ve updated the PiClock to fix this problem. Pull a new update.
Fantastic! Worked first time thanks to the great installation guide you produced! Much better than all the other wall weather/time displays I’ve run on my Pi in the past!
I’d love to see traffic conditions on the first page too! Something similar to the maps shown at for example (that’s for Paris, but I’m sure Google Maps shows traffic data too). And a final cherry on the cake: an additional page allowing me to see realtime arrivals and departures for an airport (or airports) of my choice!
Thanks and keep up the great work! I’m looking forward to see how this evolves further!
Is there a way to use mpg123 to stream net radio in lieu of the NOAA stream?
I made it works great. Just wondering if anyone has put tide information on one yet and how to do it. Thanks!
Change request in getwx()
wxurl = Config.wuprefix + ApiKeys.wuapi + ‘/conditions/astronomy/hourly10day/forecast10day/tide/q/’
At the end of wxfinished()
add this:
s = ‘Low Tide:’;
f = wxdata[‘tide’][‘tideSummary’]
tidesize=len(f)
i=0
done=0
while ((i<=(tidesize-1)) and (done!=1)) :
f = wxdata['tide']['tideSummary'][i]
if f['data']['type'] == "Low Tide":
s += str(f['date']['hour'])+':'+str(f['date']['min'])+' '
done=1
i=i+1
s += 'High Tide:'
i=0
done=0
while ((i<=(tidesize-1)) and (done!=1)) :
f = wxdata['tide']['tideSummary'][i]
if f['data']['type'] == "High Tide":
s += str(f['date']['hour'])+':'+str(f['date']['min'])+' '
done=1
i=i+1
temp.setText(s)
print "done with the tide "+s
Nice! I still have this running daily in my home office. Love it.
Any further information you can provide? I’d love tide, but can’t get it working.
Hi, Does anyone know how to get the Maps to load in the background of the Radar? Mine are just gray boxes. I’ve tried everything including rebuilding. API keys are perfect no spaces.
The only time I had that problem was when my internet connection when to shit. Reach out to Kevin. He’s helped me a few times.
Hi I’ve got the same problem now. PiClock has been running for 2 years on autopilot. Weather radar always visible on top of google maps. now google maps is a gray square. updated the API key’s (key’s where empty, now my own keys are inserted, but no success). PiClock doesn not display any error message. Any help greatly appreciated.
Hi Everybody.. I ran into the same problem. Google Maps is nog a grey square. Google maps behinf the weather radar has been running fine for the last 2 years. Inserted the Google Maps API key (this was empty before) but nu succes
Please can you help me?? I get stuck here everytime, and i cant get any further.
i@raspberrypi:~/PiClock $ sh startup.sh
numid=2,iface=MIXER,name=’PCM Playback Switch’
; type=BOOLEAN,access=rw——,values=1
: values=on
pi@raspberrypi:~/PiClock $
The clock doesnt launch or anything.
Any help would be greatly appreciated, for i have spent hours on this.
There are several log files in PiClock/Clock named like PyQtPiClock.1.log (1 thru 7). Look at the one with the latest date/time. It should show an error message that will help track down the problem.
ok.. i have this error…
Traceback (most recent call last):
File “PyQtPiClock.py”, line 19, in
import ApiKeys
File “/home/pi/PiClock/Clock/ApiKeys.py”, line 3
wuapi = 44abd0dd321d7c6ea
^
SyntaxError: invalid syntax
Have you encountered this error before?
Thank-you for the reply :)
sorry.. this is the full error i am getting.
Traceback (most recent call last):
File “PyQtPiClock.py”, line 19, in
import ApiKeys
File “/home/pi/PiClock/Clock/ApiKeys.py”, line 3
wuapi = 44abd0dd321d7cXXX
^
SyntaxError: invalid syntax
You need quotes around the key
wuapi = ’44abd0dd321d7cXXX’
Doh!
Thank-you sir. Very much appreciate the help.
Works fine now.
Fun stuff! I got this up and running in about 20 minutes with no problems to mention. Since then I’ve spent several days modifying it. I’m now using a different set of icons/weather images. Rather being actual sized, they seem to be squished a bit. My images are the same sizes as the originals. Other than that minor annoyance, this works great!
Great! You might take a look at the code to see what size frame is created for the weather icons and set your size to that.
Thank you very much sir! I used the “Tick” weather icons… They look great now that the icons are sized properly. I have noticed one strange bit; the time does not increment in frame2. It only will show the time from when the program is initially run (the clock from the main page runs just fine however). Any solutions for this?
Additionally, thank you for continuing to support this, Many developers abandon their projects after posting. I was very surprised and grateful you are still on top of it!
I’ve just fixed the bug. Looks like its been there since day 1. Thanks!
To update, follow the update instructions on
Recently, on 2 separate installs (1 raspberry pi and 1 windows install), the top left weather icon has disappeared (wxicon I believe) no changes have been made, any thoughts?
My installation recently stopped working after months on autopilot. A peek in the logs show a series of
¨X Error: BadAccess (attempt to access private resource denied) 10
Extension: 130 (MIT-SHM)
Minor opcode: 1 (X_ShmAttach)
Resource id: 0x175¨
type errors. Any ideas? I miss my PiClock!
Reinstalled Raspbian (newest flavor), used a new WU key and still getting the black screen. Simply does not display anything.
SD chip went bad. Replaced and reloaded and all is well.
YAY… Holidays were very busy for me, sorry for the long delay. I’m glad you solved the problem, because.. with that error message I had no clue!
I set the clock to auto start via Autostart Method 1. The 15 second delay is not long enough for the wifi to connect before the clock starts. Question: where can I go to change the autostart to lets say 25 seconds?
In PiClock.desktop, change the number after -m to something else (in seconds)
For reference here’s what PiClock.desktop looks like:
Thank you…
Changed it to 30 seconds and it works perfectly.
Looking for some assistance in regard to the WU API. It is no longer free and I was curious to find out if another service was being used that did provide a free API. Thanks for any help | https://hackaday.com/2015/06/10/piclock-time-and-weather-information-overload/?replytocom=3329964 | CC-MAIN-2019-47 | refinedweb | 1,977 | 74.9 |
- 09 Oct, 2014 6 commits
plugins should fill vector with model data
thus it can be easily reuse (in [model] for instance)
also add a getter to retrieve them from model
- 30 Sep, 2014 1 commit
- 23 Sep, 2014 2 commits
- 22 Sep, 2014 22 commits
I have to add that to build videoVIDS
-add videoSGI -add videoDC1394 -add videoVIDS
fixes crashes...
it's now in a separate patch in examples/10.glsl/
(to prevent crashes)
so they don't crash when we load a shader before we have a gl-context
to map glsl-shaderIDs to t_floats
to shorten compile time for other GL-utils
- 21 Sep, 2014 9 commits
this time for real (hopefully)
so we can move the functions in Utils/GLUtil into this namespace.
so we can disable the printout of errors (and just report the error-number back)
it's already included in the header
so it's clearer, that the last number is really the glsl-program ID
rather than relying on someone else doing that for us. (using m_pd.h, as we have a dependecy on s_stuff.h as well, so we are alredy low-level) | https://git.iem.at/pd/Gem/-/commits/b2c3423af83e9bffecbddac9a414a0326474d014 | CC-MAIN-2022-05 | refinedweb | 193 | 58.25 |
Introduction to Exchange Web Services in Exchange 2007, Part 3
This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.
Topic Last Modified: 2007-07-23
By Michael Mainer, Programming Writer
This is the last of a three-part series that introduces Exchange Web Services in Microsoft Exchange Server 2007. In part one of this series, I explained how Web services technology and Exchange Web Services simplify and improve Exchange 2007 application development. In part two, I introduced the operations that you can perform by using Exchange 2007 and the Exchange Web Services API. In this third and final article, I will describe the use of autogenerated proxy objects in Exchange 2007 client application development.
What are proxy objects?
Essentially, proxy objects are programmable objects that act as an interface to a service; in this case, Exchange Web Services. The proxy objects provide access to all the possible types that are exposed by Exchange Web Services. They also provide the code that is used to form the Simple Object Access Protocol (SOAP) messages, send the messages to the computer that is running Microsoft Exchange, and receive the corresponding responses.
The proxy types that define the proxy objects are created by using the WSDL and schema files. The WSDL and schema files define the contract between the client and server; the proxy types are an abstraction of that contract. They handle all the dirty work that is required to create and send the Web service requests that conform to the contract in the WSDL and schema files.
The proxy objects that are created from the WSDL and schema files provide the following functionality:
- They serve as convenient containers for the information that describes the Microsoft Exchange data.
- They handle the XML serialization of the requests to be sent.
- They handle the XML deserialization of the responses returned from the server.
Where do proxy objects come from?
Proxy classes are generated by tools that are developed for use in specific development environments. These are generally referred to as proxy generators, and both Microsoft and third parties provide them. Microsoft Visual Studio 2005 provides a proxy generator via the Add Web Reference dialog box; the Microsoft .NET 2.0 Framework SDK includes the wsdl.exe proxy generator in the Bin directory. Both proxy generators provide the same functionality, with some minor differences. Because they both use the System.Xml.Schema namespace, you too can create a .NET proxy generator, if you are so inspired. You might, for example, need custom proxy classes, or you might have to modify the autogenerated classes to meet the business requirements of an application.
Note
The Exchange Server 2007 SDK proxy documentation is based on the object model generated by the .NET 2.0 Framework–provided wsdl.exe, version 2.0.50727.42.
So, proxy generators are used to create the proxy types based on the WSDL and schema files. The WSDL and schema files are located in the in the EWS virtual directory of the Microsoft Exchange server.
Why use proxy types?
The proxy types that are created by code generators such as wsdl.exe produce an object model that handles the supplied parameters and serializes information into an XML stream. This XML stream is sent to the server in a SOAP request, and then returned in a SOAP response. If proxy-generated code is not available or is not appropriate for the application, you can use the XML DOM to construct and parse the SOAP messages. Using the proxy classes is much easier than parsing the XML because all the object information is conveniently stored in the proxy objects. Essentially, the proxy objects hold the data that is used to communicate with the Web service. You do not have to worry about the serialization and parsing of the data that is transmitted between client and server. This leaves you more time to focus on the development of the business logic specific to your application.
Generally, the use of proxy types is based on the availability of the tools to generate them. In some cases, autogenerated proxies may not provide the best performance for an application. If you do use a proxy generator to develop an application, consider the business requirements and available tools to determine which proxy generator to use.
Proxy objects and Web service methods
The ExchangeServiceBinding proxy object encapsulates the Web methods on the Microsoft Exchange server that receive the requests and return the responses. The ExchangeServiceBinding class contains a set of methods that correspond to each Web service method that is implemented in Exchange Web Services. The ExchangeServiceBinding class is the worker class that performs the work of serializing and deserializing the SOAP messages that are sent between client and server. For more information about the ExchangeServiceBinding, see Setting Up the ExchangeServiceBinding Proxy Class.
Using proxy objects
The following workflow describes the use of the proxy objects in a client application:
- The client application instantiates an object that represents the request to be performed. This object is the container for all the parameters that are used to perform the operation. The CreateItemType is an example of such an object.
- The client application supplies the request container with all the parameters that are used to fulfill the request.
- The client application calls the method on the ExchangeServiceBinding that corresponds to the type of request to be sent.
- The ExchangeServiceBinding object serializes information in the request container into a SOAP XML message, sends the request via HTTP or HTTPS, and receives a response. The response is deserialized from the SOAP XML message into a response object.
- The client application uses the response data.
The proxy types that are created by proxy generators may contain artifacts that are difficult to use. Each proxy generator is unique. Proxy generators made by the same organization may produce different results. I suggest that you compare the outputs of two proxy generators to learn more about the object models that they produce. You might also encounter some issues when you use proxy objects to develop against Exchange Web Services.
Looking ahead…
The Microsoft Exchange Server 2007 SDKincludes some examples that show you how to use proxy classes that are created by using the Add Web Reference dialog in Visual Studio 2005. The SDK also includes information about why the proxy object model contains strange constructs. You can find relevant proxy-related information in the following topics:
- Creating an Exchange Web Services Client Application
- Creating a Proxy Reference by Using Visual Studio 2005
- Setting Up the ExchangeServiceBinding Proxy Class
- Validating X509 Certificates for SSL over HTTP
- Using the *Specified Properties
- Exchange Web Services Responses
- XML Schema Choice Element Proxy Artifacts
Also stay tuned for more information about new Exchange Web Services functionality in Exchange Server 2007 Service Pack 1 (SP1).
With the use of proxy types, programming with Web services has never been easier. So go out and seize the day, Microsoft Exchange programmers. Create that exciting new application that you’ve been thinking about. | https://docs.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2007/bb508825(v=exchg.80) | CC-MAIN-2019-18 | refinedweb | 1,193 | 53.61 |
ros::Time::isValid doesn't do what we think it does?
From the documentation (...), ros::Time::isValid returns "whether or not the current time is valid. Time is valid if it is non-zero".
However, a trivial example is enough to show that the implementation does not do this:
#include <ros/ros.h> int main(int argc, char** argv) { ros::init(argc, argv, "rostime_example"); ros::NodeHandle n; // default construct a time ros::Time t; ROS_WARN_STREAM("time value: " <<t.toSec()); ROS_WARN_STREAM("time valid: " <<t.isValid()); return 0; }
The output is:
ivaughn@ros-pc:~/test_ws$ rosrun rostime_example node [ WARN] [1561399516.961348750]: time value: 0 [ WARN] [1561399516.961420491]: time valid: 1
Any idea what's going on here? Is this just a bug in ROS 1, or am I misunderstanding how this function is expected to behave.
We're kind of curious, behavior that does something different when a timestamp is invalid is often safety-critical. Thanks! | https://answers.ros.org/question/326824/rostimeisvalid-doesnt-do-what-we-think-it-does/?answer=326825 | CC-MAIN-2019-47 | refinedweb | 154 | 68.97 |
Important: Please read the Qt Code of Conduct -
[SOLVED] change the Qstackedwidget page when the Qtreeview item is clicked
when the Qtreeview item is clicked on, i am trying to change the Qstackedwidget page. i need to get the int value for the row that the qtreeview item was clicked on. i could not find anything in the documents that would help. i know why i get the error message. i just don't know how to solve it.
i am getting the error: no matching function for call to 'QStackedWidget::setCurrentIndex(const QModelIndex&)'
candidates are: void QStackedWidget::setCurrentIndex(int)
below is the modified code from the qt examples. at line 52, i get the error
@#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTreeView>
#include <QStandardItemModel>
#include <QItemSelectionModel>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//ui- ui->treeView->setModel(standardModel); ui->treeView->expandAll(); //selection changes shall trigger a slot QItemSelectionModel *selectionModel= ui->treeView->selectionModel(); connect(selectionModel, SIGNAL(selectionChanged (const QItemSelection &, const QItemSelection &)), this, SLOT(selectionChangedSlot(const QItemSelection &, const QItemSelection &)));
}
void MainWindow::selectionChangedSlot(const QItemSelection & /newSelection/, const QItemSelection & /oldSelection/)
{
//get the text of the selected item
const QModelIndex index = ui->treeView->selectionModel()->currentIndex();
ui->stackedWidget->setCurrentIndex(index);
}
MainWindow::~MainWindow()
{
delete ui;
}@
The error seems really clear to me. You are trying to call QStackedWidget::setCurrentIndex() with a [[doc:QModelIndex]] instead of with an int. A QModelIndex is not the same as an int, and cannot be converted to it, so obviously your compiler complains.
The thing about trees is, that there is no clear way to say that any item really is on a given row. It is a nested list, where each node in the tree may be the parent of a new list, that starts its row counting again at 0. So, only you know which page you want to show for which selected item your tree.
A simple solution for your problem is to add some more information to the nodes in the tree themselves. You can add the corresponding page id as a separate data role to your QStandardItems. Then, when you want to respond to having one of these selected, you read back that piece of data, and use that to set the right page number. See the data() and setData() methods for both QStandardItem and QAbstractItemModel.
If you know for sure, that the tree view actually only contains a list and not a hierarchy of items, you can get the current row from the [[Doc:QModelIndex]]. I leave it to your exercise to click on the link and discover the method name :-)
The better approach is to store the stacked widget's page id using data() as suggested by Andre. This way you decouple the id from the order of the items (which may change if you sort for example!).
i am going to try with Andre approach. I am getting a compile error. could you tell me if this code will work once the header is modified...
error in mainwindow.h: error: 'QStandardItem::data' is not a type
mainwindow.h
@private slots:
const QVariant dataChanged(QStandardItem::data(int));@
mainwindow.cpp
@ connect(this, SIGNAL(itemChanged(const QStandardItem::data( int role))), this, SLOT(dataChanged(const QStandardItem::data( int role))));
}
void MainWindow::dataChanged(const QStandardItem::data(int role))
{
ui->stackedWidget->setCurrentIndex(role);
}
@
That's plain C++ errors, nothing Qt specific. The parameters of methods take class names, not method names with class specifiers as arguments. And the method declaration in the header file must match the definition in the .cpp file.
I can only guess what you want:
@
private slots:
void dataChanged(const QStandardItem *item);
// wherever that itemChanged signal may be declared....
//
connect(this, SIGNAL(itemChanged(QStandardItem *)), this, SLOT(dataChanged(QStandardItem *)));
void MainWindow::dataChanged(const QStandardItem *item)
{
int stackId = item->data(IdRole);
ui->stackedWidget->setCurrentIndex(stackId);
}
@
But before continuing with this project, I strongly recommend to read and understand a good introduction into C++ textbook or online resource. This all is very basic stuff and it seems you do not completely understand what the pieces are and how they play together. It will ease your further development experience dramatically.
Volker your code is giving the same error and mine. yes, i am already ready a c++ book.
error in mainwindow.h: error: ‘QStandardItem::data’ is not a type
mainwindow.h
I have decided to use the listwidget instead of the treewidget. the treewidget is a bit too complicated for me right now.
Volkers's code does not give the same error. Really, it doesn't.
You, on the other hand, also really need to read more about the syntax of the connect statement.
[quote author="kalster" date="1325990995"]Volker your code is giving the same error and mine. yes, i am already ready a c++ book.
error in mainwindow.h: error: ‘QStandardItem::data’ is not a type
mainwindow.h
[/quote]
You see the characters "QStandardItem::data" literally somewhere in the few lines I've posted? No? So what makes you think that this can be the cause of an error message then?
[quote author="kalster" date="1325990995"]
I have decided to use the listwidget instead of the treewidget. the treewidget is a bit too complicated for me right now.[/quote]
Do a search for "Tree" and replace it by "List" in your source code and you'll run into the very same troubles.
BTW: Why are you using a QTree widget together with a QStandardItem?
[quote author="Andre" date="1326016730"]Volkers's code does not give the same error. Really, it doesn't.
You, on the other hand, also really need to read more about the syntax of the connect statement. [/quote]
your correct Andre. Volkers code did not give the error that i thought. I apologize. I guess i got a bit confused in the code that i was modifying and thought it was volkers code. :)
i never had any problems with the connect statement until the treeview code which i basically gave up on.
[quote author="Volker" date="1326033677"]
You see the characters "QStandardItem::data" literally somewhere in the few lines I've posted? No? So what makes you think that this can be the cause of an error message then?
Do a search for "Tree" and replace it by "List" in your source code and you'll run into the very same troubles.
BTW: Why are you using a QTree widget together with a QStandardItem?[/quote]
your right volker. your code did not give the error message and I apologize. read what i said about that in my next post above.
I am not replacing the code. i am starting over with a listwidget code that i got the signal and slot to work. everything is up and running now and without any problems. lately, i never really had too many problems declaring code up until the treeview code that was a bit too complicated for me. nevertheless, I am still studying c++ so bare with me until i get it all figured out. | https://forum.qt.io/topic/12891/solved-change-the-qstackedwidget-page-when-the-qtreeview-item-is-clicked | CC-MAIN-2020-45 | refinedweb | 1,166 | 56.45 |
Welcome to part 17 of my Android Development Tutorial. This is part 2 of my Android Fragments Tutorial series. Part 1 is here and you should watch it before watching this video.
Fragments are often used so you can create completely different interfaces depending upon the screen real estate available. We’ll cover how to do that and we’ll also look at how we can get the fragments to communicate with each other and the main activity. The Whole package is available here Android Fragments.
If you like videos like this, it helps to tell Google+ with a click here
Code From the Video
lpsum.java
package com.example.android.fragments; // Contains the fake data to display for both headlines // and articles public class Ipsum { static String[] Headlines = { "Article One", "Article Two" }; static String[] Articles = { ." }; }
dimens.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="article_view_padding">16dp</dimen> <dimen name="article_view_text_size">18sp</dimen> </resources>
news_articles.xml
<?xml version="1.0" encoding="utf-8"?> <!-- This FrameLayout blocks off part of the screen and then puts a ListView and group of List Items representing each article. The size of the FrameLayout is the size of its largest child --> <FrameLayout xmlns:
article_view.xml
<?xml version="1.0" encoding="utf-8"?> <!-- Will hold the selected article text --> <TextView xmlns:
news_articles.xml (layout-large)
<?xml version="1.0" encoding="utf-8"?> <!-- Used in layout-large folder --> <LinearLayout xmlns: <fragment android: <fragment android: </LinearLayout>
HeadlinesFragment.java
package com.example.android.fragments; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; // A ListFragment is used to display a list of items public class HeadlinesFragment extends ListFragment { // Will monitor if a headline is clicked on OnHeadlineSelectedListener mCallback; // The container Activity must implement this interface so the // fragment can deliver messages public interface OnHeadlineSelectedListener { // This function is called when a list item is selected public void onArticleSelected(int position); } // Initializes the Fragment @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int layout = android.R.layout.simple_list_item_1; // A ListAdapter populates the ListView with data in ipsum arrays // An ArrayAdapter specifically deals with arrays // getActivity() gets an Intent to start a new activity // layout is the list items layout setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines)); } // Called when the Fragment is visible on the screen @Override public void onStart() { super.onStart(); // If we have both the article names and the article Fragments on the screen // at the same time we highlight the selected article // The getFragmentManager() returns the FragmentManager which allows us // to interact with Fragments associated with the current activity // getListView() gets a ListView // CHOICE_MODE_SINGLE allows up to one item to be in a chosen state in the list if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) { getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); } } // Called when a Fragment is attached to an Activity "); } } @Override public void onListItemClick(ListView l, View v, int position, long id) { // Notify the parent activity of selected item mCallback.onArticleSelected(position); // Set the item as checked to be highlighted when in two-pane layout getListView().setItemChecked(position, true); } }
ArticleFragment.java
package com.example.android.fragments; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; //To auto import unimplemented methods //Right Click class - Source - Override/Implement Methods //Check what to implement public class ArticleFragment extends Fragment { // Used to pass the current article selected between activities final static String ARG_POSITION = "position"; // Used to track the current article in this class int mCurrentPosition = -1; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // If activity recreated (such as from screen rotate), restore // the previous article selection set by onSaveInstanceState(). // This is primarily necessary when in the two-pane layout. if (savedInstanceState != null) { mCurrentPosition = savedInstanceState.getInt(ARG_POSITION); } // Inflate the layout for this fragment return inflater.inflate(R.layout.article_view, container, false); } @Override public void onStart() { super.onStart(); // During startup, check if there are arguments passed to the fragment. // onStart is a good place to do this because the layout has already been // applied to the fragment at this point so we can safely call the method // below that sets the article text. Bundle args = getArguments(); // Check if an article had been selected if (args != null) { // Set article based on argument passed in updateArticleView(args.getInt(ARG_POSITION)); } else if (mCurrentPosition != -1) { // Set article based on saved instance state defined during onCreateView updateArticleView(mCurrentPosition); } } // Put the text for the selected article in the article TextView public void updateArticleView(int position) { TextView article = (TextView) getActivity().findViewById(R.id.article); article.setText(Ipsum.Articles[position]); mCurrentPosition = position; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Save the current article selection in case we need to recreate the fragment outState.putInt(ARG_POSITION, mCurrentPosition); } }
MainActivity.java
/* * Copyright (C) 2012.android.fragments; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; // A fragment is a kind of sub-activity that you can add or // remove from other activities while the activity continues // to run. // We extend the FragmentActivity to be able to use Fragments // on platforms prior to Android 3.0 public class MainActivity extends FragmentActivity implements HeadlinesFragment.OnHeadlineSelectedListener { // Called when the activity is first created @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.news_articles); // Check whether the activity is using the layout version with // the fragment_container FrameLayout. If so, we must add the first fragment if (findViewById(R.id.fragment_container) != null) { // However, if we're being restored from a previous state, // then we don't need to do anything and should return or else // we could end up with overlapping fragments. if (savedInstanceState != null) { return; } // Create an instance of the Fragment that holds the titles // beginTransaction() is used to begin any edits of Fragments getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, firstFragment).commit(); } } // Required if the OnHeadlineSelectedListener interface is implemented // This method is called when a headline is clicked on public void onArticleSelected(int position) { // Capture the article fragment from the activity layout ArticleFragment articleFrag = (ArticleFragment) getSupportFragmentManager().findFragmentById(R.id.article_fragment); // If the article fragment is here we're in the two pane layout if (articleFrag != null) { // Get the ArticleFragment to update itself articleFrag.updateArticleView(position); } else { // If the fragment is not available, use the one pane layout and // swap between the article and headline fragments // Create fragment and give it an argument for the selected article ArticleFragment newFragment = new ArticleFragment(); // The Bundle contains information passed between activities Bundle args = new Bundle(); // Save the current article value args.putInt(ArticleFragment.ARG_POSITION, position); // Add the article value to the new Fragment newFragment.setArguments(args); // The FragmentTransaction adds, removes, replaces and // defines animations for Fragments // The FragmentManager provides methods for interacting // beginTransaction() is used to begin any edits of Fragments FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack so the user can navigate back transaction.replace(R.id.fragment_container, newFragment); // addToBackStack() causes the transaction to be remembered. // It will reverse this operation when it is later popped off // the stack. transaction.addToBackStack(null); // Schedules for the addition of the Fragment to occur transaction.commit(); } } }
Hey..
Thanks for tutorials. Can you please make one tutorial about AlarmManager and how to set multiple alarms?
I will definitely cover that. Thank you for the request 🙂
Hey…
what is the different btwn app made in JAVA and app made in JAVA EE ..
A Android Java app would be able to take advantage of all the specific Android tools. An app meant to be cross platform would work on more devices, but lose access to those tools specific to either Android or iOS
Master Derek, can you make an android tutorial about reading images? like inputing a string to match the name of the image and if he got the correct string or the name of the image, the user can guess another image again. I hope you understood what I typed, hehe, thanks a million if you’ll make a tutorial of my request, and even if you don’t, thanks for the great tuts 🙂
I have many apps coming out that will be like that. Thank you for the request 🙂
Hey..
Nw amazon has made one tool for developing android app using html5 ..
People say its better den any other tool and easy to make app..
is it true?????
I don’t know what that tool may be? What is it called
hi derek, i know you busy with c tutorials, but i was hoping if u could squeeze in a gesture tutorial for andriod.
thanks for everything.
sbo
Many more Android tutorials are coming. I’m working on the next one right now
why do we need this line of code in MainActivity.java
firstFragment.setArguments(getIntent().getExtras());
i didn’t get this point, since we are not using any intents here.
It grabs anything stored when we switched from one activity to another
but we are not using any passed arguments in the headlines fragment so whats the need to set the arguments
I wnt to know frm u derek..
That phone gap is much easier or directly frm eclipse its will be easier for us to develope android app..
Hi Derek,
Thanks for the awesome tutorials, are you going to be posting some more android stuff? I’m trying to figure out the process of an android app interacting with a restful service, will you be covering that?
You’re very welcome 🙂 Yes more Android tutorials are coming. I’ll get them out ASAP. I covered how to use the Yahoo restful service for XML and JSON early in the tutorial. I will cover how to create webservices soon.
My (humble) requests are
swipe
animations (simple game)
rotation handling
Thanks for all your wonderful material!
The next video will cover animation as well as touch. Thank you for the requests and you are very welcome 🙂
Hey …love the tutorials so helping me learn android …gat a sem project that i have to make a fashion app could you plse cover colour selection ..would be so helpfull thanks man
I’m going to spend more time on interface design soon. Sorry the videos are taking so long. I’m trying to make sure each one is good. I have been throwing a bunch of the videos out.
Master, I’m from Nicaragua and I do not know if you speak spanish but if you do let me know and if you do not, it is ok, Because I’m learning it, well I got a question in the tutorial number 3 I made and follow all the step for the app, but at the end of running the app to my device, which is a tablet mediapad 7 lite, an error appears like the app “crazytipcalc has stopped”, and the option ok to exit, I do not know was the problem is, and thank you for the tutorials is a such a wonderfull website
Thank you 🙂 I speak a little Spanish, but I use a translator if I need to.
As per your question, what errors are you getting in the LogCat panel in Eclipse? (Window -> Show View -> Other… -> Android -> LogCat)
谢谢你。
Thanks
歡迎您的光臨
Hello Derek, thank you so much for the amazing tutorials. Do u know how to make Dictionary app. Where people can type word like “computer’ and get the meaning/definition of computer. I would like to make English to my native language dictionary and it is very important. I have been following your tutorials hoping i would learn how to make dictionary app at least in the end. Could you please teach me how to do that? thank you very much.
I actually was going to make an app that would act as a universal translator. My approach was to build the translations using the Grammatical Framework.
The app quickly got out of control, teaching wise, so I had to drop the idea for a tutorial. You could definitely make a translation app this way though. I’d be very interested in what you come up with.
I hope that helps 🙂
Hello Derek,
Thanks for ur kind reply. Sadly i have very basic knowledge of programming. Could u point me to other source links if u know. I have all the list of 5000 words and meaning already in excel file. I need some way to extract this file when people make query in app form. Thanks you.
Hello Henry,
If you have the words translated you could just save them in table form in an SQLite database. SQLite is some what like a spreadsheet. I have a tutorial on SQLite. Then when they type in a word, you can find the proper word next to it in the chosen language and display it in a text box.
Stick with it. I’m sure you can do it.
Hello Derek,
Thank you very much. I will work on that. And thanks for all the great tutorials.
You’re very welcome 🙂
Salut Derek,
The first, I really love your videos. Thank you for your sharing!
And second, i have problem with this fragment tutorial. I try to code by myself or copy direct your source codes to my eclipse but it’s still not worked …!
The application force close when i try to open it
This is logcat error:
E/AndroidRuntime(2197): Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f030003
I think have some problem with onCreate method in MainActivity. But i can’t fix it. I tried clean project and then restart eclipse. I didn’t find any answer from google or stackoverflow also. Could you help me please ! Thanks again.
Hi Max,
I have the whole Android Package here. Try the code there. I think the problem may be that a lot of the auto-update things that work with my setup aren’t working for others. I use Eclipse Indigo for Java Developers with the Android plugin like I show in my Install Android Development Tools tutorial.
I hope that helps 🙂
Thank you so much ! it saved me a lot of times. I found out my problem. It’s typo name of xml layout so, the onCreate method cannot setContentView for the application. Oh brain …
That’s funny 🙂 I’m glad you figured it out. I’ve spent many hours pulling my hair out over typos.
Hi Derek,
Thank you for the wonderful tutorials and you are the best.
I am wondering if you have or will you be covering tabs in future. I have not covered all tutorials yet could you please let me know the number if you did.
Thank you very much,
Adam
Hi Adam,
I will definitely cover tabs. The current video since part 18 are going to be all about making interfaces.
Why do I keep getting this error very frequently?! “The specified activity does not exist! Getting the launcher activity.”
The codes are exactly the same.
Make sure you check the Deploy application checkbox in the Run/Debug Configuration screen, under the General tab.
But I would like to point out one thing I noticed. Now a days your video tutorials like this one is very very fast you use copy paste of code a lot and you are damm fast.
For instance I need to pause this video after each minute to write out the codes you have written.
of course you have provided the code along with comments but still I like to make programs along with live video tutorials so please if you can slow down, In this video you were really too fast and it was not at all enjoyable writing with you
Thnx for providing these awesome tutorials
I’m constantly working to find the perfect speed for the tutorials. Thank you for the input. I’ll try to improve.
Hey, Your tutorials study materials are awesome, I don’t have words to thank u. The content of your video tutorials are just amazzzing.
Hey Derek why not make a wonderful app, at the end of which there is also a walk through to upload it to google play store. ( Please do not choose google maps as the major app video tutorial – it sucks ).
Thnks anyway
Eventually I’m going to great apps to go along with the video tutorials. So for example if I do an algebra tutorial I will make an Algebra practice app. I plan to do this over and over again. That way I can teach how to make real world Android apps while I continue to explore new areas of knowledge. Everything will be free 🙂
Thank you for the kind words 🙂 I try to do my best.
First of all thanks for your tutorial.
To test this app on my Galaxy S4, I replaced layout-large by layout-land. But when I select an article in land layout, I have a NullPointerException in updateArticleView because article was not found.
Is it a little bug or is it because it has to be implemented another way when one uses layout-land ?
Thanks in advance for your answer.
Gilles
Paris
Sorry, but I’m not sure if I tested that or not. i need to make more videos on interface design.
I really wanna understand this tutorial. But everything seem not very easy to be understood for me. teacher Derek, can you tell me how to understand this source codes fully please? Thank you very much
Tell me what specifically is confusing and I’ll answer each question one by one.
Hello Derek, what is the preferable resolution for this lab. My first emulator is to small to have these landscape changes. Then I changed to a Nexus 10 with a 2560*1600 it’s so big that it only has the landscape. Thanks for very good tutorials.
Hello Ricky, I have my emulator settings on this page. I also cover how to install the newest Android tools here.
I’m trying to figure out fragments… and this example still leaves me with a question.
* When this app is started on a large device, the first entry to source code is to onAttach in HeadlinesFragment.java
* When this app is started on a small device, the first entry to source code is to onCreate in MainActity.java
Ok – I understand if the large layout is used, it calls fragments, and if the smaller layout is used, well, it isn’t used until MainActivity.java inflates it.
So, why/how does android know that if using the large xml, to call using the fragment lifecycle (which starts with onAttach in HeadlinesFragment.java), and if using the small device, to use the activity lifecycle (that starts with onCreate in MainActivity.java).
Thanks in advance for your help.
And by the way… FANTASTIC TUTORIALS!!!!!!!!!!!!
Thank you 🙂 The easiest thing to do is to watch my newest Android tutorials on Fragments. I covered them much better this time. I hope they help.
Ok… figured it out. My previous post isn’t exactly accurate… so this is what I found out.
When run on a large device, the order of what is run is:
* MainActivity.java, onCreate starts
when setContentView is executed, the following gets run:
* HeadlinesFragment.java, OnAttached gets called
* HeadlinesFragment.java, OnCreate gets called
* ArticleFragment.java, OnCreateView gets called
* MainActivity.java, onCreate ends
* HeadlinesFragment.java, onStart gets called
* ArticleFragment.java, onStart gets called
* Tablet screen now shows both fragments.
On the other hand, a much different path happens if a SMALL device screen is run:
* MainActivity.java, onCreate starts
* if statement starts FragmentManager and begins Fragment.add…
* MainActivity.java, onCreate ends
* HeadlinesFragment.java, onAttach is called
* HeadlinesFragment.java, onCreate is called
* HeadlinesFragment.java, onStart is called
* Phone screen now shows headlines fragment only.
So what it comes down to is: When setContentView is called, if the layout contains fragments (as in the large device), the fragments get started. If setContentView does not contain fragments (as in the small device), nothing was started, so the Activity needs to start the fragments it wants/needs.
I now see it’s obvious… now…
Again – FANTASTIC TUTORIALS!!!
Thanks – Daniel
Thank you for writing that out 🙂 I’m sure it will help others. I’m glad you are enjoying the videos. | https://www.newthinktank.com/2013/08/android-development-17/ | CC-MAIN-2018-30 | refinedweb | 3,397 | 57.47 |
This tutorial shows how to transform a traditional monolithic core banking application, which is implemented in Node.js, into a modern microservices architecture by using IBM Cloud Pak for Applications.
Cloud Pak for Applications speeds the development of applications that are built for Kubernetes by using agile DevOps processes. Running on Red Hat OpenShift, the Cloud Pak provides a hybrid, multicloud foundation that is built on open standards, enabling workloads and data to run anywhere. It integrates two main open source projects: Kabanero and Appsody.
This tutorial uses a sample monolithic banking application, which is illustrated in the following architecture diagram:
There are five tightly coupled services within this application:
- Admin login (
admin_login.ejs)
- Admin dashboard (
admin.ejs)
- User login (
user_login.ejs)
- User dashboard (
users.ejs)
- Not found (
notfound.ejs)
If too much workload or user traffic occurs on one service, then all of the other interconnected services can be affected. Or the complete project can go down, which is one of the major disadvantages of monolithic architectures.
To break down this monolithic application, you separate the admin services (
admin_login.ejs and
admin.ejs) and user services (
user_login.ejs and
users.ejs) into microservices so they can run independently. Both services have different functions, so the new application is able to scale them depending on the workload. The two new microservices are:
To do this, you put the admin services into one project and the user services into another, and then deploy them both to a central GitHub repo. Both have their own dependencies and run independently, as you can see in the following architecture diagram. (Don’t worry if this does not fully make sense to you right now. The tutorial steps explain it further.)
Prerequisites
To complete the steps in this tutorial, you need:
- Docker on your local computer.
- Visual Studio Code for local development.
- Access to a Red Hat OpenShift on IBM Cloud cluster with IBM Cloud Pak for Applications.
- A GitHub account and some knowledge of git commands.
Estimated time
After the prerequisites are installed, this tutorial will take about 90 minutes to complete the steps.
Steps
- Clone the GitHub repository
- Install Codewind in Visual Studio to create a microservice test and deploy to GitHub
- Create GitHub tokens
- Initialize Tekton and integrate with the central GitHub repository
- Verify that the microservices are up and running
Step 1. Clone the GitHub repository
- Open your terminal and change your directory by using the
cd downloadscommand. (Or any other directory in which you want to clone the project.)
- Run the command:
git clone.
Open the project in Visual Studio.
Step 2. Install Codewind in Visual Studio to create a microservice test and deploy to GitHub
What is Codewind and why does this tutorial use it?
In the present era, one of the biggest challenges for a developer is to build and deploy cloud-native applications. Many actions are required to build a perfect solution on the cloud and you need to build images, create containers, debug, analyze the different logs, assess performance metrics, and rebuild the containers with each code change. That’s why this tutorial uses Eclipse Codewind, an opensource project that helps you achieve all of the above actions quickly with ready-made, container-based project templates and can easily be integrated with your visual code integrated development environment (IDE). Learn more about Codewind.
Since you know which services will be converted into microservices, start by initializing Codewind in Visual Studio with the following tasks:
- Open Visual Studio.
- Select Extensions and search for Codewind.
- Select Install and kindly wait, since it will take some time to initialize.
- Once successfully installed, you will see the Codewind section.
- Select Codewind and start the local Codewind.
- Right-click local and select Create New Project.
- Select Kabanero Node.js Express simple template.
- Select the folder where you want to initialize the template and name it
micro-admin. (This step can take five to ten minutes to initalize.)
Once your template is initalized successfully, kindly open the folder where you created
micro-admin. You will see the newly created template.
Next, you will break down the monolithic application in three stages.
First, visit the folder where you cloned the monolithic application in Step 1. In that folder, open the
app.jsfile and copy the following lines:
const express = require("express") const path = require('path'); const app = express(); app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); app.use(express.static(path.join(__dirname, 'node_modules'))); app.use(express.static(path.join(__dirname, 'public'))); app.get("/", function(req,res){ res.render("admin_login"); }); app.get("/admin_login", function(req,res){ res.render("admin_login"); }); app.get("/admin_in", function(req,res){ var Name = req.query.name; var Password = req.query.pass; if (Password =="123") { console.log("Successfully logged in as admin"); res.render("admin"); } else{ res.render("notfound.ejs"); } }); module.exports.app = app;
Then, go to your new
micro-adminfolder and replace the
app.jsfile with the copied version.
Second, copy the complete public folder located within the folder where you cloned the monolithic application, and paste it into your new
micro-adminfolder.
Third, open the views folder located within the folder where you cloned the monolithic application, and copy only the
admin.ejs,
admin_login.ejs, and
notfound.ejsfiles. Paste those files into your new
micro-adminfolder.
Your structure should now look like the following:
Open your terminal inside Visual Studio and run the command
npm install ejs. This will install the Embedded JavaScript templating that you will use for front-end styling.
- Go to Codewind in Visual Studio and look for your project there, running as
micro-admin. Right-click it and select Open Application to open the page. From there, select enable project (if it is disabled) and then select build. Check Application Endpoint to see where your application is running.
To test your application, right-click
micro-admin, select Application Monitor, and hit the application two or three times to see the changes.
Run
appsody buildin your Visual Studio terminal. You don’t have to worry and spend your time on a deployment configuration file since Codewind will create it for you. You only need to focus on your application development.
After the above command executes successfully, you will see a new generated file called
app-deploy.yamlon the left hand side of your screen. This file will help you in a later step to deploy the application on Cloud Pak for Applications.
Note: If you do not have a namespace section, please add it as follows:
apiVersion: appsody.dev/v1beta1 kind: AppsodyApplication metadata: namespace: kabanero creationTimestamp: null labels: image.opencontainers.org/title: micro-admin stack.appsody.dev/id: nodejs-express stack.appsody.dev/version: 0.2.8 name: micro-admin ....
You successfully created the Admin microservice.
Go back to the beginning of this Step and repeat tasks 6 to 17 to create the second microservice, naming it
micro-user.
This time, your
app.jsfile will be for users, so copy the code below during task 10:
const express = require("express") const path = require('path'); const app = express(); app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); app.use(express.static(path.join(__dirname, 'node_modules'))); app.use(express.static(path.join(__dirname, 'public'))); app.get("/user_login", function(req,res){ res.render("user_login"); console.log("User login"); }); app.get("/user_in", function(req,res){ var Name = req.query.name; var Password = req.query.pass; if (Password =="123") { console.log("Successfully logged in as user"); res.render("users"); } else{ res.render("notfound.ejs"); } }); app.listen(3000 , function(){ console.log("App is running"); });
Also, after task 12, you should see a structure like this for your new
micro-userfolder:
Once you finish testing and creating the User microservice, individually upload both microservices to the central GitHub repository.
Note: If you have any difficulty executing this step to create both microservices, please check out the following sample repositories that were created using Codewind:
Step 3. Create GitHub tokens
Before you initialize Tekton, it is really important to create two GitHub tokens for your admin and user microservices:
- Open GitHub and log into your account.
- Click your profile photo to expand the account profile menu.
- Within the menu, click Settings > Developer settings > Personal access tokens.
- Click the Generate new token button.
- Give your first token a descriptive name by typing
tekton-app-userinto the Note field.
Select the scopes, or permissions, you’d like to grant this token. To use your token to access repositories from the command line, select the repo checkbox.
Click the Generate token button.
- Copy the token to your clipboard. It is important that you do this. For security reasons, after you navigate off the page, you will not be able to see the token again.
- To create your second token, click the Generate new token button again.
- Give your second token a descriptive name by typing
tekton-app-admininto the Note field.
- Select the scopes, or permissions, you’d like to grant this token. To use your token to access repositories from the command line, select the repo checkbox.
- Click the Generate token button.
Copy the second token to your clipboard. It is important that you do this for both tokens.
Once both tokens are created, you will see a page similar to the one below:
Step 4. Initialize Tekton and integrate with the central GitHub repository
What is Tekton and why does this tutorial use it?
Tekton is a powerful, yet flexible, Kubernetes-native open source framework for creating continuous integration and continuous delivery (CI/CD) systems. This tutorial uses Tekton because it is a built-in tool for IBM Cloud Pak for Applications that connects the GitHub central repository and a webhook that lifts and shifts application source code from your local development to the cloud. Learn more about Tekton.
To initialize Tekton, perform the following tasks:
- Open your Red Hat OpenShift web console.
- Once you are logged in successfully, select Kabanero from the My Project section.
- Select Cloud Pak for Applications from the menu.
You should see the following screen:
Click the Instance tab.
Within the Tools section, select Tekton. You should see the following screen:
Select Webhooks from the menu and proceed to create two webhooks for your microservices (
micro-adminand
micro-user).
For the first webhook, enter
w1-adminin the Name field, the Repository URL field, and
micro-token-1in the Access Token field.
Click Create.
For the second webhook, enter
w2-userin the Name field, the Repository URL field, and
micro-token-2in the Access Token field. Click Create.
Check that Tekton and GitHub are successfully connected by opening your two repositories. Go to the
micro-adminrepository and under settings, select Webhooks from the menu. If the pipeline is connected properly, you will see a link such as..(you may have different link). Follow the same procedure to check the
micro-userrepository.
Important: Do not worry if you get an error notice. This will resolve after the repositry code is updated.
Make some changes in the
micro-adminand
micro-userrepositories that were created in Step 2 to trigger your Tekton pipeline. First, open the
micro-adminrepository. Inside the views folder, open the
admin.ejsfile and make some changes, such as searching for
My Dashboardand capitalizing the text to be
MY DASHBOARD. After you are done, commit the file.
Perform the same type of procedure within the
micro-userrepository, making similar changes to some text within the
user.ejsfile. After you are done, commit the file.
Open your Tekton dashboard. Under the Tekton dropdown list, select PipelineRuns.
Wait until the rows under the Status column display
All tasks completed executing, which indicates you successfully integrated your central repo to your Tekton instance on IBM Cloud Pak for Applications.
Important: Perform the changes in each repository separately. For example, perform the changes in the User repository first and after it is successfully built and deployed, then update the Admin repository. Or vice versa.
For more details about Tekton, check out this great tutorial.
Step 5. Verify that the microservices are up and running
- Open the OpenShift dashboard.
- Select Applications from the menu.
- Select Routes and you should then see your two microservices up and running on the Routes page.
To run the application, click the links within the Hostname column.
Here is a sample screen capture of the user interface:
Here is a sample screen capture of the admin interface:
Conclusion
In this tutorial, you learned how to modernize a Node.js application, transforming it from a monolithic architecture into a microservices architecture using Cloud Pak for Applications. By independently running two projects containing related services, you can scale them depending on the workload. In addition, you can integrate as many microservices as you want without affecting or scaling down the complete project. | https://developer.ibm.com/depmodels/cloud/tutorials/modernize-a-monolithic-nodejs-application-into-a-microservices-architecture-using-ibm-cloud-pak-for-applications/ | CC-MAIN-2020-50 | refinedweb | 2,127 | 51.04 |
try the plugin or see an integration example have a look at the Felgo Plugin Demo app.
Please also have a look at our plugin example project on GitHub:.
The GoogleAnalytics item can be used like any other QML item. Add a single instance of the item to the root item of your QML files to call it from anywhere in your app.
import Felgo 3.0 import QtQuick 2.0 App { GoogleAnalytics { id: ga // Property tracking ID from Google Analytics Dashboard propertyId: "UA-32264673-5" onPluginLoaded: { ga.logEvent("App Action", "Started App") } } NavigationStack { Page { id: page title: "Google Analytics" AppButton { anchors.centerIn: parent text: "Push Page" onClicked: { ga.logEvent("User Action", "Clicked Push Page") page.navigationStack.push(subPage) } } }// Page } // NavigationStack Component { id: subPage Page { title: "Sub Page" onPushed: ga.log: "Website" property like described here. You later on need the generated tracking ID (UA-xxxxxxxx-y).
Note: It usually takes some time for new properties to set up before Google Analytics shows some tracking data.
Voted #1 for: | https://felgo.com/doc/plugin-googleanalytics/ | CC-MAIN-2019-47 | refinedweb | 169 | 52.56 |
CodePlexProject Hosting for Open Source Software
I am creating a very basic widget and using the LatestTwitter Widget as a template. My widget shows up under the Widget category of Modules.
When I enable it the constructor of my WidgetDriver is called, service is injected properly, etc. However, the Create method of the Migrations is never called.
Here is my create method.
public int Create()
{
//Creating table LatestTwitterWidgetRecord
SchemaBuilder.CreateTable("LatestTwitterRecord", table => table
.ContentPartRecord()
.Column("UserNameList", DbType.String)
.Column("NumberOfTweetsPerUser", DbType.Int32)
);
ContentDefinitionManager.AlterPartDefinition(typeof(LatestTwitterWidgetPart).Name,
builder => builder.Attachable());
ContentDefinitionManager.AlterTypeDefinition("LatestTwitterWidget", cfg => cfg
.WithPart("LatestTwitterWidgetPart")
.WithPart("WidgetPart")
.WithPart("CommonPart")
.WithSetting("StereoType",
"Widget"));
return 1;
}
Any ideas on things I can check?
As far as I can tell, all files are named properly and it's pretty much an exact replica of the TwitterWidget in the gallery (we are showing different stuff, not limiting to a single user, and a few other tidbits).
Thanks,
Will
It probably already ran. Try an UpdateFrom1.
One problem I've had when I copied migrations from another project is that I also copied the namespace and forgot to change it. So if it has the same namespace as another migration that already ran, Orchard will assume it's the same one and won't run it.
Check you changed the namespace to your own.
The namespace is correct. I suspect you are right with the fact that Create was already called.
So, a new question. How do I tell Orchard to pretend like that never happened for a specific module?
Where is the information about a modules version stored in Orchard? I've removed it as a dependency from the App_Data and completely removed the module directory and disabled the module from the asmin panel but Orchard apparently still recognizes the module
and the version.
I am writing the module and I want the Create step to be as clean as possible (I don't ever want to have to create a bunch of update steps for what is only a single update). I want a single UpdateFromX function for each version of the module I release.
Ideally I want a way to destroy all Orchard knowledge of this module/widget and have it call Create again, as many times as necessary for me to get it the way I want -- until Version 1 is release, then I'll want to do the same thing but rolling back only to
version 1.
When I move on to the next version (2) I will want a way to make orchard go back to thinking it's on version 1 each time I want to run/test my upgrade step.
At that point I think my only option would be to keep restoring the Orchard database from a point where ny module is at version 1?
Thanks,
Will
I've been deleting the whole database and starting from scratch a lot of the time. This also means you can test the installation and migration process properly from square 0 each time. I've been using Recipies to install all the modules features and populate
data. It also means by the time you go live with a site, you've already got a recipe containing exactly what you need for deployment. I know it's a bit laborious, but it's a pretty thorough process once you've got used to it.
The migration numbers specifically are held in the Orchard_Framework_DataMigrationRecord table so you can manually adjust in there if you need to.
Ok so you have to delete the entire record for it to run the Create script again.
Think it would be possible to allow a user to set the Version field in Orchard_Framework_DataMigrationRecord to 0 and have to cause the Create script to run again?
Currently, setting it to 0 seems to have no effect at all.
This would be beneficial since then, the Id I initially create the module under won't have to change, I can just keep resetting it until I am happy with the code.
Thanks,
Will
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://orchard.codeplex.com/discussions/255377 | CC-MAIN-2017-39 | refinedweb | 714 | 63.09 |
I've seem to be stuck. I come from a mostly POSIX background, & thrown into the deep-end on this one, so learning as I go along - so not sure if there's no solution, or if it's my own Dunning-Kruger at play.
Setup:
(Trying to keep as much of the back-end FLOSS, non-FLOSS only where can't escape)
- Running a CentOS (7) server
- Samba (4) Active Directory domain (Sernet repo) - replicated cluster
- W764-64 & W10p-64 testing VM's
- W10p-64 admin VM
- N windows desktops in several "departments"
So far it all looks OK: got basic, stable setup as per docs, pushed out some basic GPO's to network (eg. create a file in %TEMP%, or alike), so can confirm that basic GPO creation & permissions are OK.
gpupudate et al is all good.
What I now need to do is better target GPO's & test impact on smaller subset of desktops before deploying throughout the entire org.
What what I can gather (& this is where the limits of my w32-knowledge comes sharply into focus), this is achieved by creating & applying a WMI filter to said GPO.
From what I gather it seems to be a pretty vanilla SQL or SQL-like syntax, and the suggested manner of creating such statements is to use WMI Explorer to explore Namespaces & build said targeting queries. (quite nice actually)
Obviously the tool can poll localhost namespaces absolutely fine, but when I try to connect it to the DC's, I fail, as there is no WMI or RPC on a Linux/POSIX box to speak of (which seems obvious, but trying not to make too many assumptions).
This leaves me in a precarious position - I need to do what seems to be pretty normal sysadmin work, but Samba does not seem to support WMI (& the wiki seems to bear this out) which windows seems to rely heavily on & make extensive use of.
But I still need to find a good/stable way to take a more targeted & nuanced approach to deploying controls to a large number of hosts, and the assumed/suggested resources fall far short of the mark. | https://serverfault.com/questions/780423/targeted-gpo-deployments-from-samba-4-dc | CC-MAIN-2019-43 | refinedweb | 362 | 56.83 |
Various Multiple Choice Questions
Determine the payback period, discounted payback period, NPV, profitability index, IRR from sample #1 attached
Use the following data to for 1,2,3 4,5 below:
Undiscounted
Year Free cash flows
0 (350,000)
1 10,000
2 40,000
3 80,000
4 100,000
5 120,000
6 80,000
7 100,000
Required rate of return = 8%
1. The payback period is:
a. 4 years
b. 3 years
c. 6 years
d. 5 years
e. None is within 0.5 years of the correct answer. (Provide the answer)
2. The discounted payback period is closest to:
a. 4.5 years
b. 3.3 years
c. 6.6 years
d. 5.2 years
e. None is within 0.5 years of the correct answer. . (Provide the answer)
3. The net present value (rounded to the nearest dollar) is:
a. $360
b. $371,000
c. $280
d. $21,000
e. None is within $500 of the correct answer. (Provide the answer)
4. The profitability index is within .05 of:
a. 2.06
b. 2.20
c. 2.10
d. 0.25
e. None of the above is within .05 of the correct answer. (Provide the answer)
5. The internal rate of return (rounded to the nearest half percent) is:
a. 8.5%
b. 9.5%
c. 15 %
d. 5%
e. None is within 0.5% of the correct answer. (Provide the answer)
Sales price for next year, break even point from #2 attached
Use the following data to answer problems 24 and 25.
CD New is a direct marketer of popular music. Following is information about its
revenue and cost structure:
Selling Price $ 13.00 per CD
Variable Costs:
Manufacturing $ 3.00 per CD
Selling and Adminstrative $ 1.00 per CD
Fixed Costs
Production $ 1,000,000 per year
Selling and Administrative $ 3,000,000 per year
24
Assume that sales are expected to fall from 600,000 units this year to 500,000 units next
year. CD New would like to raise the price next year (from the current $13.00) to achieve
the same profits next year as they have this year. What would the sales price have to be
next year, to generate the same profits next year as this year?
Answer
a) Somewhere between $15.00 and $15.99
b) Somewhere between $14.00 and $14.99
c) Somewhere between $13.00 and $13.99
d) Somewhere between $16.00 and $16.99
e) None of the above (provide the answer)
25
In which range does the break-even point fall? (Use the original data.)
Answer
a.) Between 300,000 and 350,000 units
b) Between 350,001 and 400,000 units
c) Between 400,001 and 450,000 units
d) Between 450,001 and 500,000 units
e) None of the above (provide the answer)
Debt ratio, current ratio, fixed asset turnover from #3 attached
Use the information below, to answer questions7, 8 and 9:
Cash 12
Marketable securities 15
Accounts receivable 19
Inventory 14
Plant & equipment 18
Current liabilities 20
Total owners' equity 15
Sales 35
(All assets are listed)
7. Determine the debt ratio:
a. 35%
b. 26%
c. 38%
d. 15%
e. None of the above. (Provide the answer.)
8. Determine the current ratio:
a. 2.95
b. 3.00
c. 1.75
d. 2.00
e. None of the above. (Provide the answer.)
f.
9. Determine fixed asset turnover
a. 1.75
b. 2.45
c. 1.94
d. 3.00
e. None of the above (Provide the answer.)
Solution Preview
1. Payback period is the time taken to recover the intial investment. It is found by cumulating the cash flows till the sum is equal to the initial investment. The time period is the payback period. In this case the initial investment is 350,000 and the sum of cah flows till the year 5 equals to 350,000. The payback period is 5 years.
2. In discounted payback, we use the discounted cash flows. The cash flows are discounted using the discount rate given. Here it is 8%. We do the same procedure as above. We find the sum till year 6 is 312,646. We need 350,000. The difference is 37,354. In the year 7, the discounted cash flow is 58,349. We find ...
Solution Summary
The posting has various multiple choice questions relating to capital budgeting, break-even analysis and ratios | https://brainmass.com/business/capital-budgeting/various-multiple-choice-questions-53009 | CC-MAIN-2017-17 | refinedweb | 742 | 78.75 |
Hi, hopefully this is a simple question, but it's leaving me a little lost.
I have an existing SWF file which uses AS3/Flex and I'm migrating to Air. Now, I actually want to access the AS classes but don't need the presentation layer (we're doing that in Air/HTML). What's the best way to get this into an Air (HTML/Javascript) application?
I was thinking of creating a SWC from the classes, but am unsure how to do that. I'm already using the applicationupdater_ui.swf successfully, but trying the same thing (with a different namespace, but using <script src=> tags in HTML then air.ApplicationUpdaterUI object in Javascript) is saying the variable 'com' isn't available.
Any help appreciated.
Cheers
Robbie
You create a SWC for AIR using the acompc utility (compc should also work if there are no references to AIR-only APIs). You can't use the SWC directly. You have to "unzip" it (you can change the extension from .swc to .zip) and extract the Library.swf.
The error claiming the "com" variable is unavailable is a reference error. You have to provide the fully qualified package name for any classes referenced. However, the syntax for a package reference and a variable reference overlap, so if the package name can't be resolved, the error is reported as an undefined variable instead of an unknown package.
If you had a LibraryClass class defined in a utilities package, you would reference it as follows:
var libraryObject = new window.runtime.utilities.LibraryClass();
See. html.
Yeap, that was what I needed. I didn't help myself however, by trying to access embedded classes within the SWF.
All working now though, thanks. | https://forums.adobe.com/thread/420980 | CC-MAIN-2018-13 | refinedweb | 288 | 66.33 |
29 April 2009 18:01 [Source: ICIS news]
By Nigel Davis
LONDON (ICIS news)--The downturn has ripped through the chemicals sector, a point on which there is little doubt. But it is the breadth of the volume decline that is so noticeable and potentially damaging.
The diversity of the chemicals business is a strength – as well as a complication – when it comes to trying to get a handle on where the sector generally might be heading. But that diversity has offered little protection from the slump in global manufacturing in the fourth quarter of 2008 and, most noticeably, in the first quarter of 2009.
One can only hope that the first quarter of 2009 represents the nadir in terms of demand for most chemicals.
The downturn has been deep and wide. Specialties makers have suffered in businesses related to automobiles, construction and consumer electronics. The downturn in consumer goods has hit almost everyone.
The upstream slump is equally as dramatic. Take Shell, which charted on Wednesday a 22% fall in base chemicals volumes (that's olefins and aromatics) in the first quarter (compared with the first quarter of 2008), and a 20% fall in volumes of first-line derivatives.
Shell makes the sort of chemicals that feed other (chemicals) makers and more widely used products, such as solvents.
Go a step sideways, to a company like BP, and the picture is nigh on identical: a 26% fall in chemicals production in the first quarter. BP makes acetyls and the purified terephthalic acid that feeds into polyester manufacture.
Take a step further downstream and look at polycarbonate, polyurethanes and coatings, which are made by Bayer and are used in construction, furniture and other consumer applications.
The poor performance of Bayer MaterialScience in the first quarter was worse than the market expected and helped push the Bayer share price down. The fall in sales for Bayer MaterialScience was 38% when adjusted for portfolio changes and currency effects.
Bayer CEO Werner Wenning called the fall in volumes “steep”, adding that nearly all the subgroup businesses were hit in all regional markets. “This is an unprecedented development for Bayer,” he said.
Bayer's currency-adjusted polycarbonate sales were down 42% and adjusted polyurethane sales down 40%. Sales of speciality coatings and adhesives were down 37%.
Such lower demand levels have forced operating cutbacks at Bayer and across great swathes of the chemicals business. Some rates have begun to move back up, but the upward turn has been sporadic.
To press the point home further, the Netherlands-based life sciences and materials group DSM this week reported depressed materials sales as the global recession hit harder.
Almost half of the DSM businesses are heavily affected by the downturn even after its shift in recent years towards life sciences. The drop in group sales was 22%. And the company used that word again: “unprecedented”.
Performance materials sales volumes were down 33%. Polymer intermediates sales volumes were 43% lower.
The good news – there is a little – is that the demand slump appears to have ground to a halt in some markets.
“Although no improvement in demand in end-markets seems to be imminent, we are not at this point in time seeing a further deterioration either,” DSM CEO Feike Sijbesma said this week.
Bayer's CEO said on Wednesday that the downturn seems to be bottoming out. “The first signs of a modest recovery in demand are appearing,” Wenning said.
The signs of a bottom to this part of the down cycle are coming from ?xml:namespace>
Yet it is way too early to be overly optimistic for chemicals. Established producers – those who do not sit in close proximity to potentially fast-growing markets or on top of cost-advantaged feedstocks – are in a particularly difficult position.
This downturn has shown that a great many chemical products are interlinked, in that they serve markets important to the global manufacturing economy.
The drop in demand witnessed at the turn of the year was unprecedented. It was broadly based in product and geographic terms.
A return to growth cannot be achieved until important downstream industries and consuming markets for chemicals begin to recover. And that could take some | http://www.icis.com/Articles/2009/04/29/9211957/insight-recovery-from-unprecedented-downturn-will-take-time.html | CC-MAIN-2015-06 | refinedweb | 700 | 62.48 |
Angular has many Pipes built-in, but they only take us so far. Ideally we’d like to extend our applications by creating custom Pipes.
Custom Pipes (previously Filters in AngularJS) allow us to essentially create a pure function, which accepts an input and returns a different output via some form of transformation.
That’s the essence of a Pipe. And we see this already in Angular with things like the Date Pipe and friends.
Table of contents
A Custom Pipe in Angular
Pipe usage
Pipe class and decorator
Pipe and PipeTransform
Pipe Transform Value
Pipes with Arguments
There are various ways we can create Pipes, so let’s explore them a little further.
A Custom Pipe in Angular
The most basic pipe transforms a single value, into a new value. This value can be anything you like, a string, array, object, etc.
For the demonstration of this, we’ll be converting numeric filesizes into more human readable formats, such as “2.5MB” instead of something like “2120109”. But first, let’s start with the basics – how we’ll use the Pipe.
Pipe usage
Let’s assume an image was just uploaded via a drag and drop zone – and we’re getting some of the information from it. A simplified file object we’ll work with:
export class FileComponent {
file = { name: ‘logo.svg’, size: 2120109, type: ‘image/svg’ };
}
Properties name and type aren’t what we’re really interested in to learn about Pipes – however size is the one we’d like. Let’s put a quick example together for how we’ll define the usage of our pipe (which will convert numbers into filesizes):
<p>{{ file.size | filesize }}</p>
</div>
Pipe class and decorator
To create a Pipe definition, we need to first create a class (which would live in its own file). We’ll call this our FileSizePipe, as we are essentially transforming a numeric value into a string value that’s more human readable:
export class FileSizePipe {}
Now we’ve got this setup, we need to name our Pipe. In the above HTML, we did this:
<p>{{ file.size | filesize }}</p>
So, we need to name the pipe “filesize”. This is done via another TypeScript decorator, the @Pipe:
import { Pipe } from ‘@angular/core’;
@Pipe({ name: ‘filesize’ })
export class FileSizePipe {}
All we need to do is supply a name property that corresponds to our template code name as well (as you’d imagine).
Don’t forget to register the Pipe in your @NgModule as well, under declarations:
// …
import { FileSizePipe } from ‘./filesize.pipe’;
@NgModule({
declarations: [
//…
FileSizePipe,
],
})
export class AppModule {}
Pipes tend to act as more “utility” classes, so it’s likely you’ll want to register a Pipe inside a shared module. If you want to use your custom Pipe elsewhere, simply use exports: [YourPipe] on the @NgModule.
Pipe and PipeTransform
Once we’ve got our class setup, registered, and the @Pipe decorator added – the next step is implementing the PipeTransform interface:
import { Pipe, PipeTransform } from ‘@angular/core’;
@Pipe({ name: ‘filesize’ })
export class FileSizePipe implements PipeTransform {
transform() {}
}
This creates a required contract that our FileSizePipe must adhere to the following structure:
export interface PipeTransform {
transform(value: any, …args: any[]): any;
}
Which is why we added the transform() {} method to our class above.
Pipe Transform Value
As we’re using our Pipe via interpolation, this is the magic on how we’re given arguments in a Pipe.
{{ file.size | filesize }}
The file.size variable is passed straight through to our transform method, as the first argument.
We can call this our size and type it appropriately:
//…
export class FileSizePipe implements PipeTransform {
transform(size: number) {}
}
From here, we can implement the logic to convert the numeric value into a more readable format of megabytes.
//…
export class FileSizePipe implements PipeTransform {
transform(size: number): string {
return (size / (1024 * 1024)).toFixed(2) + ‘MB’;
}
}
We’re returning a type string as we’re appending ‘MB’ on the end. This will then give us:
<!– 2.02MB –>
{{ file.size | filesize }}
We can now demonstrate how to add your own custom arguments to custom Pipes.
Pipes with Arguments
So let’s assume that, for our use case, we want to allow us to specify the extension slightly differently than advertised.
Before we hit up the template, let’s just add the capability for an extension:
//…
export class FileSizePipe implements PipeTransform {
transform(size: number, extension: string = ‘MB’): string {
return (size / (1024 * 1024)).toFixed(2) + extension;
}
}
I’ve used a default parameter value instead of appending the ‘MB’ to the end of the string. This allows us to use the default ‘MB’, or override it when we use it. Which takes us to completing our next objective of passing an argument into our Pipe:
<!– 2.02megabyte –>
{{ file.size | filesize:’megabyte’ }}
And that’s all you need to supply an argument to your custom Pipe. Multiple arguments are simply separated by :, for example:
{{ value | pipe:arg1 }}
{{ value | pipe:arg1:arg2 }}
{{ value | pipe:arg1:arg3 }}
Don’t forget you can chain these pipes alongside others, like you would with dates and so forth.
Here’s the final assembled code:
import { Pipe, PipeTransform } from ‘@angular/core’;
@Pipe({ name: ‘filesize’ })
export class FileSizePipe implements PipeTransform {
transform(size: number, extension: string = ‘MB’) {
return (size / (1024 * 1024)).toFixed(2) + extension;
}
}
Want a challenge? Extend this custom Pipe that allows you to represent the Pipe in Gigabyte, Megabyte, and any other formats you might find useful. It’s always a good exercise to learn from a starting point!
Link: | https://jsobject.info/2018/01/14/step-by-step-custom-pipes-in-angular/ | CC-MAIN-2019-09 | refinedweb | 912 | 59.94 |
This is what I use:
Extern double PercentRisked=2
double LotsBuy()
{
double StopLossBuyCalc =(Ask-BuyStop+(Ask-Bid)+SLFromFractal*Point)*(1/Point);
double RiskPercent = (PercentRisked*0.01);
double DollarsPerLot,FirstDollarsPerLot,SecondDollarsPerLot,BuyLots;
DollarsPerLot = (MarketInfo(Symbol(),MODE_TICKVALUE)*10);
BuyLots = NormalizeDouble(((AccountBalance()* RiskPercent)/(StopLossBuyCalc*0.1)/DollarsPerLot),2);
return (BuyLots);
}
i have Ea i wrote a EA and would like to add script to it so that i can input a % of the balance to use in buying lots.
So $1000 could have a lot size of 0.1 and then increase it to 0.2 when the balance is $2000 and between those amounts? but i would like to be able to change the settings of the %.
i have tried to add some code but it didnt work. could some one who knows what they are doing help? | https://www.mql5.com/en/forum/123721 | CC-MAIN-2017-47 | refinedweb | 136 | 58.89 |
13 November 2008 20:29 [Source: ICIS news]
HOUSTON (ICIS news)--US exports of vinyl chloride monomer (VCM) in September totalled 48,969 tonnes, down more than 57% from 114,191 tonnes during the same month last year, the US International Trade Commission (ITC) said on Thursday.
From January through September, US VCM exports decreased 12% when compared with the same period in 2007.
?xml:namespace>
US Gulf export FOB (free on board) prices were $520-570/tonne (€416-456/tonne) on Thursday, according to data from global chemical market intelligence service ICIS pricing.
US VCM producers include Formosa Plastics, Oxy Vinyls, Oxy Mar,
($1 = €0.80)
For more | http://www.icis.com/Articles/2008/11/13/9171485/us-september-vcm-exports-drop-57.html | CC-MAIN-2013-48 | refinedweb | 109 | 59.84 |
Generator for random text that looks like Latin.
Project description
Python Lorem Package
Summary
Generator for random text that looks like Latin.
Simple Example
import lorem s = lorem.sentence() # 'Eius dolorem dolorem labore neque.' p = lorem.paragraph() t = lorem.text()
Complex Example
from lorem.text import TextLorem # separate words by '-' # sentence length should be between 2 and 3 # choose words from A, B, C and D lorem = TextLorem(wsep='-', srange=(2,3), words="A B C D".split()) s1 = lorem.sentence() # 'C-B.' s2 = lorem.sentence() # 'C-A-C.'
History
0.1.1 (2016-06-18)
- Update documentation
0.1.0 (2016-06-17)
- Minimum viable product
0.0.1 (2016-06-14)
- First release on PyPI.
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/lorem/ | CC-MAIN-2018-22 | refinedweb | 144 | 62.34 |
What This Book Covers.
Chapter 1 is an introduction to SOA. This chapter looks back at a landmark book on distributed architecture from the CORBA era: Client/Server Survival Guide by Orfali, Harkey, and Edwards. The architecture presented in this earlier work has much in common with contemporary SOA architecture, but it differs in one key respect: the CORBA-based architecture, an object-oriented approach, lacks the sense of process that is so prevalent in SOA.
We then examine the contemporary SOA stack (which we call the model stack), and map its layers to the product suites of the four major SOA vendors: IBM, Oracle, BEA, and TIBCO. We look, briefly, at examples of orchestration processes and ESB mediation flows on these platforms. These examples give us a sense of the style of programming on these platforms. In subsequent chapters, we take a deeper dive.
Chapter 2 presents an approach to documenting and diagramming process-oriented SOA architecture using ’4+1′, ARIS, SCA, UML, and BPMN. With this unusual concoction, we cover all of the important ‘views’ and draw box-and-arrow process diagrams that carefully link activities to data and services. In our scheme, labeling is an exact science. We discover why the expression
Account.getRecord(req.accountNum): acctRec is so much more useful than the casual Get Account Record.
Chapter 3 takes a closer look at the model stack and teaches, by example, how to separate a use case into BPM and SOA parts. We demonstrate two designs for credit card disputes processing: one in which a BPM process manages the end-to-end control flow and uses short-running SOA processes for integration, the other in which a long-running SOA process drives the end-to-end flow but delegates human tasks to BPM processes. This chapter will have you drawing circles in your sleep!
Chapter 4 begins by distinguishing between those oft-confused terms orchestration and choreography, and then presents an approach for modeling choreography, in BPMN and BPEL, as an invisible hub. The leading choreography standard, WS-CDL, is not known for its wealth of implementations; we build the choreography for electricity market enrollment in its leading tool, pi4SOA. The chapter concludes with tips on modeling orchestration; the discussion presents an algorithm for ‘dependable’ inbound event routing.
Chapter 5 classifies processes by duration, dividing them into three categories: shortrunning, midrunning, and long-running. Long-running processes need state, so we examine three data models to keep process state: those used in BEA Weblogic Integration and Oracle’s BPEL Process Manager, and our own custom model, which borrows ideas from these two. We then discuss how to build a long-running process out of several short-running processes (implemented in TIBCO’s BusinessWorks) tied together with state in our custom data model. We conclude by showing how short-running BPEL processes can be compiled for faster execution.
Chapter 6 observes that most processes today are modeled ‘naïvely’. Those who design them drag all of the boxes they require onto a canvas, connect them with arrows, and create a graph so meandering and expansive that it’s as difficult to navigate as the roads of an unfamiliar city. We propose a structured approach known as fl at form, which breaks the graph into simple pieces and assembles them in a controller loop. Flat processes are, by design, flat, and thus avoid the deep nesting characteristic of naïve processes. There are three variants of flat form: event-based, statebased, and flow-based. We build examples of each in BPEL.
Chapter 7 describes the change problem—the problem of changing the definition of a process that has live cases in production—and considers examples of changes (for example, adding an activity, removing an activity, changing the sequence of activities, and introducing parallelism) which cause trouble for existing cases. We also consider dynamic process styles that take the preventative approach to the change problem by attempting to be adaptable in the first place. Dynamic forms can be process-based, rule-based, or goal-based. We study examples of each.
Chapter 8 presents an approach for simulating BPEL processes using concepts from discrete event simulation and the Poisson process. Simulating a BPEL process is fundamentally more difficult than simulating a single-burst service. BPEL processes are long-running, have multiple bursts and both initial and intermediate events, frequently go to sleep for an interval of time, and, in many
implementations, queue inbound events rather than responding to them as they come. In this chapter, we build a simulator that supports this usage pattern, run a series of examples through it, and study the results. The salient conclusion is to keep bursts short!
Chapter 9 presents a formula for scoring SOA processes on complexity. We position complexity analysis as an important step in design oversight and governance. The approach we consider allows the governance team to rate each process as red, yellow, or green and to flag reds for rework. Intuitively, the ‘complexity’ of a process is the amount of branching or nesting in its graph. Flat form, introduced in Chapter 6, scores well on complexity because it avoids excessive branching. Naïve processes score poorly. Our scoring method is a variant of McCabe cyclomatic complexity.
Short and Long-Running Processes
As a process moves from activity to activity, it consumes time, and each activity adds to the overall duration. But different sorts of activities have different durations, and it’s not uncommon to observe a ten-step process that outpaces, say, a five-step one. It depends, of course, on what those activities are doing.
In SOA, process cycle times range from one second or less to one or more years! The latter sort need not have a large number of activities. The pyramids might have been built rock-by-rock over several decades, but protracted SOA processes typically span only a few dozen tasks, a handful of which consume almost the entire interval.
As we discuss in this chapter, most of that time is spent waiting. The disputes process introduced in Chapter 3 often requires several months to complete, because at various times it sits idle waiting for information from the customer, the merchant, or the back offi ce. Business processes crawl along at human speed, and, as we argued in Chapter 3, it often makes sense to let SOA manage the end-to-end fl ow.
It’s not easy to build an SOA process engine that can simultaneously blaze through a sub-second process but keep on top of a one that hasn’t moved in weeks. On the other hand, when a long-running process rouses, we expect the engine to race very quickly to the next milestone. The central argument of this chapter is that both long-running and short-running processes run in very quick bursts, but whereas a short-running process runs in a single burst, a long-running process might have several bursts, separated by long waits. To support long-running processes, the process engine needs a strategy to keep state.
In this chapter, we examine the fundamental differences between long-running and short-running processes. We discuss how to model state, and demonstrate how to build a long-running process as a combination of several short-running processes tied together by state. We also show how to compile short-running BPEL processes to improve the execution speed of a burst.
Process Duration—the Long and Short of It
SOA processes have the following types of activities:
- Tasks to extract, manipulate, or transform process data
- Scripts or inline code snippets
- Calls to systems and services, both synchronous and asynchronous
- Events, including timed events, callbacks, and unsolicited notifi cations from systems
The first three sorts of activities execute quickly, the first two in the order of milliseconds, the third often sub-second but seldom more than a few seconds (in the case of a synchronous call to a slow system). These activities are active: as the process navigates through them, it actively performs work, and in doing so ties up the process engine. Event times are generally much longer and more variable. Events come from other systems, so (with the exception of timed events) the process cannot control how quickly they arrive. The process passively waits for events, in effect going to sleep until they come.
An event can occur at the beginning of a process—indeed, every SOA process starts with an event—or in the middle. An event in the middle is called an intermediate event. The segment of a process between two events is called a burst. In the following figure, events are drawn as circles, activities as boxes, and bursts as bounding boxes that contain activities. Process (a), for example, starts with an event and is followed by two activities—Set Data and Sync Call—which together form a burst. Process (b) starts with an event, continues with a burst (consisting of the activities Set Data and Call System Async), proceeds to an intermediate event (Fast Response), and concludes with a burst containing the activity Sync Call. Process (c) has two intermediate events and three bursts, and (d) has a single intermediate event and two bursts.
Processes are classifi ed by duration as follows:
- Short-running: The process runs comparatively quickly, for not more than a few seconds. Most short-running processes run in single burst (as in process (a) in the fi gure), but some have intermediate events with fast arrival times—as in (b), where the intermediate event, a response to an asynchronous system call, arrives in about two seconds—and thus run in multiple bursts. TIBCO‘s BusinessWorks and the BPEL compiler described later in the chapter are optimized to run both single-burst and multiple-burst short-running processes. BEA’s Weblogic Integration can run single-burst, short-running processes with limited overhead, but, as discussed further next, treats cases like (b) as long-running.
- Long-running: The process has multiple bursts, and the waiting times of its intermediate events are longer than the process engine itself is expected to run before its next restart! In process (d), for example, the engine is restarted for maintenance while the process waits two days for a human action. The process survives the restart because its state is persisted. At the end of its fi rst burst (that is, after the Assign Work step), the engine writes the state to a database, recording the fact that the process is now waiting on an event for a human action. When the engine comes back up, it fetches the state from the database to remember where it left off. Most BPEL processes are longrunning. In Weblogic Integration, stateful processes can run for arbitrarily long durations.
- Mid-running: T he process has multiple bursts, but the waiting times of its intermediate events last no more than a few minutes, and do not need to be persisted. Stakeholders accept the risk that if the process engine goes down, in-fl ight processes are lost. Chordiant’s Foundation Server uses mid-running processes to orchestrate the interaction between agent and customer when the customer dials into a call center. The call is modeled as a conversation, somewhat like a sequence of questions and answers. A burst, in this design, processes the previous answer (for example, the Process Answer activity in (c)) and prepares the next question (Prepare Question). Intermediate events
(Get Answer) wait for the customer to answer. State is held in memory.
Stateful and Stateless Processes in BEA’s Weblogic Integration
I n Weblogic Integration, single-burst processes are stateless, but multiple-burst processes, even short-running ones, are stateful. Even if the wait between bursts is very small (one or two seconds perhaps), Weblogic Integration nonetheless persists process state to a database. The distinction is subtle, but Weblogic Integration provides visual clues to help us detect the difference. In the next fi gure, the process on the left is stateless. The process on the right is the same as that on the left except for the addition of an event step called Control Receive; the step, in effect, puts the process in a wait state until it receives a specifi c event. When this step is added, Weblogic Integration changes the appearance of its start step—Start—from a circle with a thin border to one with a thick border, indicating that the process has changed from being stateless to stateful.
Those who designed Weblogic Integration thought process state so important that they worked into their notation whether a process is stateful or stateless. We now study one of the most critical pieces of any process engine: how it keeps state.
How to Keep Long-Running State
In this section, we study the data models for long-running process state in two commercial process integration platforms: Oracle‘s BPEL Process Manager and BEA’s Weblogic Integration. We also develop our own model, a generalization of the Oracle and BEA approaches, which enables us to achieve the effect of a long-running SOA process from a group of short-running processes. We put this model to practical use later in this chapter, in the email money transfer example.
SOA process state models contain information about the following:
- Process metadata, including the types of processes currently deployed, their versions, and how their activities are assembled.
- Process instances, including status, start time and end time, and the position of the instance in a call graph (that is, parent/child relationships). Some models also track the status of individual activities.
- Pending events, and how to correlate them with process instances.
State in Oracle‘s BPEL Process Manager
The following figure shows the core tables in the Oracle BPEL model (version 10.1.2).
In this model process, metadata is held in two tables: Process_Default and Process_Revision. The former lists all deployed BPEL processes and their current revision numbers; the process_id field is not a technical key but the name of the process specified by the developer. The latter lists all of the revisions; for a given process, each revision has a distinct GUID, given by the field process_guid.
The seemingly-misnamed table Cube_Instance—actually, cube is synonymous with process in the internals of the product—has information about current and completed process instances. The instance has a unique key, given by cikey. From process_guid we can deduce, by joining with Process_Revision, the process type and revision of the instance. Other important information includes the instance creation date, its parent instance, and its current state. Possible states are active, aborted, stale, and completed, although the state fi eld uses numeric codes for these values.
The Work_Item table tracks the status of instance activities. Cikey indicates the instance to which the activity belongs. Within an instance the activity is identified by the combination of node_id, scope_id, and count_id. The fi rst two of these indicate the position of the activity in the process graph and the scope level to which it belongs; the label column is a friendlier alternative to these, assuming that the developer applied a useful label to the activity. Count_id is required in case the activity executes more than once. Work_Item has its own state fi eld (again numeric), which indicates whether the activity is completed or pending, was cancelled, or encountered an exception.
Dlv _Subscription records pending events and correlates them with instances. Conv_id is a conversation identifi er known to both the BPEL process and its partner service. To trigger the event, the partner service passes this identifi er as part of its message. The process matches it to a subscriber_id, which uniquely identifies the activity that is waiting on the event. Thus, when the event arrives, the process knows exactly from which point to continue. (Technically, subscriber_id is a delimited string, which encodes as part of its structure the values of cikey, node_id, scope_id, and count_id that point to a unique Work_Item record.) The partner also specifi es an operation name, which specifi es which type of event it is fi ring. If the process is waiting on several events in the same conversation (as part of an event pick, also known as a deferred choice), operation_name determines which path to follow. The combination of operation_name and conv_id points to a unique activity (that is, to a unique subscriber_id).
State in BEA’s Weblogic Integration
The following fi gure shows three important tables in the Weblogic Integration model:
WLI_Process_Def has metadata about types of deployed processes and their activities. The table has one row for each activity. Process_type is the human-readable name of a process. Activity_id is the numeric identifi er of an activity in the process, although user_node_name, the descriptive name provided by the developer is more intuitive.
Process instance information is held in WLI_Process_Instance_Info. Each instance has a unique numeric identifi er, given by process_instance. Process_type specifi es the process defi nition on which the instance is based. Process_status specifi es, in a numeric code, whether the instance is active, pending, or aborted. The table also tracks process start and end times, as well as time in excess of the SLA (sla_exceed_time). Through Weblogic Integration’s administration console, the administrator can confi gure an SLA on process cycle time.
In Weblogic Integration a process instance can receive intermediate events by several means. One of the most important of these is by listening for messages published by Weblogic Integration’s message broker system. The table WLI_Message_Broker_Dynamic keeps track of specifi c events waiting on broker messages. The column subscriber_instance is the process instance identifi er; it matches the process_instance value in WLI_Process_Instance_Info. Rule_name is, in effect, a pointer to the event in that instance. Filter_value is an XQuery expression that checks the content of the message to determine whether to accept the event. When a message arrives, the broker checks for any subscription events, and triggers those whose fi ltertest passes.
Our Own State Model
Our own model, shown in the next fi gure, follows a design approach similar to that of the Oracle and BEA models.
To begin, the model features a single metadata table, called ProcessStarter, which enumerates the types of processes deployed (processType) and specifi es for each the type of event that can start it (triggeringEventType). The table’s main purpose is to route start events: when an external event arrives, if ProcessStarter can map it to a process, then a new instance of that process is created from the event.
Several tables track the state of process instances. The Process table assigns a unique identifi er to each instance (procID), indicates its type (processType), locates it in a conversation (convID), and records its start time, end time, and status (pending, completed, or aborted). The ProcessVariable table persists process variables, ensuring that instance-specifi c data survives system restarts. A variable is identified by a name (name) that is unique within its level of scope (scope) in a process instance (procID). The ProcessAudit table keeps a chronological list of important occurrences in a process instance. It is tied to a specifi c instance (procID), and has both a timestamp and a text entry. The entry can optionally be associated with a specifi c process activity (activityID). Implementations can extend the model by providing a custom state table (such as the hypothetical MyAppState in the diagram) that associates application-specifi c fi elds (myState, in this example) with an instance.
Final ly, the PendingEvent table assists in correlating intermediate events. An event is identifi ed by the combination of its process instance (procID), its activity node in the process (activityID), and if it is part of a deferred choice, the identity of that choice (choiceActivityID). (If the event is not part of a choice, choiceActivityID is zero or null.) There are two types of events: timed events and events triggered by a message. If the event is a timed event, timeToFire specifi es the date and time (somewhere in the future) when the event should fi re. If the event is message-based, triggeringEventType indicates the type of message that triggers it. When the event is created, the Boolean fi eld isDone is set to false. When the event fi res, isDone is switched to true. If the event is part of a choice, isDone is set to true for all events in the choice, thereby ensuring that only one event is chosen.
The model assumes that all messages carry the following fi elds:
- Event Type
- Recipient Process Type
- Conversation ID
When a message arrives, the following logic determines how to route it:
- If there is an instance of the process in the conversation (that is, if there are rows in Process where processType and convID match the values from the message), check whether it has a pending event of the given event type (that is, check for rows in PendingEvent where procID matches the value from Process, isDone is false, and triggeringEventType matches the event type). If it does, fire the event. Otherwise, discard the event.
- If there is no instance of the process in the conversation, check whether the process can be started by this type of event. (That is, check for rows in ProcessStarter where processType and triggeringEventType match those from the message.) If so, instantiate the process. Otherwise, discard the event.
We put this model to use in the next section. Refer to the discussion of correlation in Chapter 4 for more details on this approach, especially the use of optimistic locking to prevent two simultaneous events from firing.
Combining Short-Running Processes with State in TIBCO‘s BusinessWorks
The next discussion covers the TIBCO implementation of the email transfer process.
Our Use Case—Sending Money by Email
With this model in place, we build a process that spans several days as a set of short-running processes, none of which lasts more than a few seconds. The use case we consider is email money transfer, introduced in our discussion of choreography in Chapter 4. In a transfer there are four main parties: the sender, the sender’s bank, the recipient, and the recipient’s bank. We build the process for the sender’s bank.
The following figure depicts the required fl ow of events:
When the bank receives the request to send funds from the sender (Sender’s Request), it validates the request (Validate Request), and rejects it if discovers a problem (Send Reject to Sender). If the request is valid, the bank informs the sender of its acceptance (Send Accept to Sender), notifi es the recipient by email (Send Email To Recipient), and sets aside funds from the sender’s account (Allocate Funds). The fi rst burst is complete, but several possible paths can follow:
- There is a time limit on the transfer, and if it expires the transfer is aborted.
- The sender may cancel the transfer.
- The sender’s bank may reject the recipient’s bank’s request to move the funds into the recipient’s account. The recipient may try again later.
- The sender’s bank may accept the recipient’s bank’s request to move the funds into the recipient’s account.
The control flow to support this logic is a deferred choice inside a loop. The loop runs for as long as the variable loopExit is false. The process initializes the value to false (Set loopExit=false) immediately before entering the loop. Paths 1, 2, and 4 set it to true (Set loopExit=true) when they complete, signaling that there is no further work to do and the loop need not make another iteration. Path 3 leaves the loopExit fl ag alone, keeping it as false, thus allowing another iteration (and another chance to complete the transfer). Each iteration is a burst.
There are three events in the deferred choice, one for expiry (path 1), one for cancellation (path 2), and one for the recipient’s bank transfer request (paths 3 and 4). The logic for cancellation and expiry (headed by the events Sender’s Cancellation and Expired respectively) is identical: the process sends a cancellation email to the recipient (Send Email Recipient), informs the sender that the transfer is aborted (Send Abort to Sender), and restores the funds to the sender’s account (Restore Funds). In the transfer request path (starting with the event Recipient Bank’s Transfer Request), the sender bank validates the transfer (Validate Transfer) and sends the outcome to the recipient’s bank (Send Reject to Recipient Bank or Send Accept to Recipient Bank). If validation passes, the process also notifi es the sender that the transfer is complete (Send Completion to Sender) and commits the funds it had earlier allocated (Commit Funds).
The sender’s bank’s process is long-running, typically spanning several days from start to fi nish. To build it using a short-running process engine, such as TIBCO‘s BusinessWorks, we need to break it into smaller processes: one to handle the sender’s request to send funds, one to handle the recipient’s bank’s request to complete the transfer, one to handle the sender’s cancellation, one to handle expiry, and one to manage the overall event routing. In dividing the process into pieces, we lose the loop and deferred choice, but we add housekeeping responsibility to each piece.
The Router Process
The next figure shows the BusinessWorks process to handle the overall routing.
When it receives an inbound message on a JMS queue in GetEvent, the router process checks the event type to determine to which BusinessWorks process to route the event. There are three event types:
- Request: Sent by the account holder (known as the sender). Because this request starts the process, it must not contain a conversation identifi er. If it does, the route process immediately logs the event as an error and discards it (Log Illegal Input). Otherwise, it queries the ProcessStarter table, in the step Check Starter Enabled, to verify that the email transfer process may be started by this type of event. (It checks that there is a record in the table that matches the given event type and process type.) If this check passes, the route process creates a unique conversation identifi er (Set Conv ID) and calls the request process to handle the event (Call Request Process).
- Transfer: Sent by the recipient bank. The route process checks that the message has a conversation identifi er. If it does, it calls the transfer process (Call Transfer Process) to handle the event. Otherwise, it logs the event and discards it (Log Illegal Input).
- Cancel: S ent by the sender or internally by the timer process (discussed further next). The route process checks that the message has a conversation identifi er. If it does, it calls the cancellation process (Call Cancel Process) to handle the event. Otherwise, it logs the event and discards it (Log Illegal Input).
The Request Process
The next figure shows the BusinessWorks process to handle the sender’s request to send funds:
The process begins by creating a unique process identifi er (Set Proc ID) and then validates the request (Validate Request). If the request is invalid, the process sends a rejection to the sender (Send Reject to Sender) and writes three records to the database:
- A record in the Process table (using Add Process Record Aborted) that sets the status of the instance to ABORTED. The process identifi er is the one created in Set Proc ID.
- A log of the validation failure (using Add Audit Invalid Req) in the ProcessAudit table.
- A copy of the inbound message in the ProcessVariable table, using Add Variable Request. The earlier step RequestAsString converts the message from XML to string form.
Thus, there is a record that the instance was aborted, an explanation in the audit trail why it failed, and a copy of its message data.
The happy path, in which the request passes validation, contains three steps that we described earlier: Send Email Recipient, Send Accept to Sender, and Allocate Funds. It also creates the following records in the database:
- A record in the Process table (using Add Process Record Pending) about the instance, with a status of PENDING and the identifier created in Set Proc ID.
- An indication that the validation passed (using Add Audit Valid Request) in the ProcessAudit table.
- A copy of the inbound message (using Add Variable Request 2) in the ProcessVariable table.
- Three PendingEvent records, for transfer, expiry, and cancel respectively (using the steps Add Transfer Event, Add Expiry Event, Add Cancel Event). The records share a common choiceActivityID, and for each the isDone fi eld is set to false.
- A record in the custom table EXState (using Add EXState), which extends the Process table with information specifi c to email transfers. The next figure shows the EXState table and its relationship to Process. The table adds one fi eld to the mix, numRejects, which is initialized here to zero and is incremented each time the sender’s bank rejects the recipient’s bank’s transfer request.
When the happy path completes, the PendingEvents table has, among its contents, three records similar to the following:
According to this information, process instance 123 has three pending events, whose activityIDs are Cancel, Expiry, and Transfer respectively. These events are set in a single deferred choice, whose choiceActivityID is 1. None of these events has occurred, indicated by isDone being false. The Cancel and Transfer events are triggered by the inbound events types EX.Cancel and EX.Transfer respectively. The Expiry event does not have a triggering event type, but has a timeToFire confi gured for December 13, 2008; Expiry is a timed event.
When one of these events arrives, it is processed only if the isDone fi eld is false; otherwise it is discarded. When it is processed, the isDone fl ag is set to true for all three events. Marking all three true in effect marks the whole deferred choice as complete, and prevents a second event from occurring.
The Transfer Process
The process that handles the recipient’s bank’s request for transfer is shown in the following figure.
The process begins immediately by querying the PendingEvent table to check that its event is still pending (FindEvent). If it has already been marked as completed, the process rejects the request (Send Reject to Recipient Bank Event Not Found) and quits. Assuming the event is permitted, the process marks the choice as completed (Remove Event) and validates the request (Validate). If validation passes, the process, as already discussed, sends an acceptance to the recipient’s bank (Send Accept Recipient Bank) and a completion notifi cation to the sender (Send Completion Sender), commits the funds (Commit Funds), and then performs the following table updates:
- In the Process table, it sets the instance status to COMPLETED (using Close Process).
- It adds an entry to the ProcessAudit table (using Add Audit), indicating that the transfer succeeded.
- It saves the transfer request message to the ProcessVariable table. If a previous version of the message is already there, the process overwrites it (Update Variable); otherwise, it inserts a new message (Insert Variable).
If validation fails, the process sends a rejection message to the recipient bank (Send Reject Recipient Bank) and makes four table updates:
- It restores the deferred choice (using Restore Event), setting isDone to false for each of the three events (Restore Event).
- It increments the numRejects fi eld in the EXState table (Add Reject).
- It adds an entry to the ProcessAudit table (using Add Audit), indicating that the transfer failed.
- It saves the transfer request message to the ProcessVariable table, using the same logic as above.
The successful validation path effectively terminates the larger process by removing all of its pending events. The failed validation path effectively loops back in the larger process to an earlier point, giving each of the events another chance to fire.
The Cancellation Process
The process to handle cancellation, shown in the next fi gure, starts out much the same way.
The process fi rst checks that the event is still pending (Find Event), and if so, disables the deferred choice (Remove Event). The process then notifi es the sender and the recipient of the cancellation (Send Recipient Email and Send Abort to Sender), restores the funds (Restore Funds), and update the tables as follows:
- It marks the status of the instance as ABORTED (Close Process).
- It adds an audit entry indicating cancellation (Add Audit).
- It saves the cancellation event to the ProcessVariable table (Save Variable).
The Expiration Process
The process to handle expired transfers, shown in the next fi gure, is somewhat different.
The expiration process is not designed to handle the expiry of a single transfer. Rather, it scans the PendingEvents table for all expired transfers (Get Expired Transfers), and fi res a cancellation event for each of them. The outer box labeled For Each Expired is a for loop that, for each record returned by the query, constructs a cancellation message (Create Cancellation Message) and launches a cancellation process (Launch Cancellation Process) to handle the message. It launches the process by sending a message on the JMS queue to which the routing process listens. The routing process, when it receives the event, routes it to the cancellation process. Thus, it is the cancellation process that will disable the deferred choice and abort the instance, not the timer process.
The timer process runs on a predefi ned schedule. The Poller step defines how often it runs (every fi fteen minutes, for example). The timer process is not designed to run at the very moment a particular transfer expires. BusinessWorks manages the schedule internally; the schedule is not configured in our process state model.</code>
A Note on Implementation
TIBCO‘s BusinessWorks is designed for performance, and admittedly our processes make database updates rather liberally. (The request process has seven updates in the happy path!) More effi cient alternatives are to fl atten the data model (so that there are fewer tables to update) or build stored procedures to bundle updates (resulting in less IO to the database server).
Another option is use TIBCO‘s proprietary checkpoint mechanism to serialize process state to the disk. The checkpoint feature is clumsy but is often an effi cient way to achieve the effect of long-running state in an engine that is designed for short-running processes. As a proprietary capability, it does not work as part of a generalized state model, which is why we did not demonstrate it here.
Fast Short-Running BPEL
We conclude with a discussion of compiled BPEL.
Uses of Short-Running Processes
Having developed an approach to keep SOA processes running for an arbitrarily long time, we now turn our attention to short-running processes and ask: how can fi gure, like the model stack we discussed in Chapters 1 and 3, fi gure fl ow of control specifi ed defi nition is coded in Java class form, rather than as an XML document. Compilation speeds the execution time of a burst.
- The process may defi ne fl ag to false (Set Loop Stop). The loop exits, and the process completes. While it waits for the producer events, the process also sets a timed event (too long) that fi res if neither event arrives in suffi cient. An se quence diagram in the following fi gure illustrates how this process runs on the short-running engine:
The process starts when client application sends a message intended to trigger the process’ start event. The Pro cessManager receives this event (either as a direct call or indirectly via an execution thread that monitors the shortrunning inbound queue) in its routeMessageEvent() method. It then checks with the process class—shown as Process in the fi gure, fi rst iteration of the while loop, in which it records in its data structures that it is now waiting for three pending events (Set Pending Events). Because one of these events is a timed event, it also registers that event with the TimeManager (addEvent()).The fi rst fi rst iteration of the loop. It now loops back, resets the pending events (Set Pending Events), and registers a new timed event (addEvent()). The second burst is complete.
Assuming the producer does not respond in suffi cient time, the timer expires, and the TimeManager which checks for expired events on its own thread notifi es the Process Manager (routeTimedEvent()). ProcessManager gives the event to the process (calling hasPendingEvent() to confi rm sta te information needed to tie all of this together is held in memory.
ProcessManager maintains a data structure called instanceList that, much like the Process table just described, keeps a list of process instances indexed by the combination of conversation identifi er</code> Com piledProcess class (the base class for compiled BPEL processes) keeps track of variables, current pending events, and permitted start events, holding in memory the same sort of data that is defi ned for the tables ProcessVariable, PendingEvent, and ProcessStarter. Here is an excerpt of the code:
public abstract class CompiledProcess { List pendingEvents = new ArrayList(); Map variables = new HashMap(); String pid; String convID; public abstract <b><i>BPEL</i></b>Graph. } } </code> fi le that is later compiled and loaded into the address space of the process engine. At runtime, the BPEL process runs at the speed of compiled Java. We thus save the performance-stultifying effect of runtime XML parsing and serialization that affl icts many process engines.
Here is a snippet of the Java source of the class for our sample short-running process:
public class SRProcess extends CompiledProcess { static <b><i>BPEL</i></b>Graph graph = null; static { graph = new <b><i>BPEL</i></b>Graph();><i>BPEL</i></b>Graph getGraph() { return graph; } } </code>
The class does nothing except build a graph representing its process defi nition. fi ll in the one missing ingredient: the actual process defi nition. Signifi cantly, it creates this defi nition fi gure> </code>
The surest way to learn the functionality of compiled processes and the short-running engine is to play with the accompanying compiler demo. See About the Examples for a download link.
Compiled Code—What Not To Do
A </code> effi ciently. Performance is the point, after all.
About the Examples
The source code for this chapter is available for download in the code bundle. Refer to the README fi le for information on how to set up and run the examples.
The example of email funds transfer, which demonstrates how to build a long-running process out of several short-running processes, uses TIBCO‘s BusinessWorks 5.6 and Enterprise Message Service 4.4, as well as an RDBMS. TIBCO products can be downloaded from. You must have an account to access this site. Once in, there are several installation programs to download; refer to our README fi le classifi ed‘s-fl ight‘s.
December 18, 2008
WebLogic | http://www.javabeat.net/2008/12/soa-process-architecture-modeling-and-simulation-in-bpel-tibcos-businessworks-and-beas-weblogic-integration/2/ | CC-MAIN-2013-20 | refinedweb | 6,492 | 59.53 |
Almost.
It’s a design paradigm that has worked well, but lately new technologies like touch screens and motion sensors (think the Wii) have challenged the notion of using a mouse, or even having a cursor on the screen at all..
Long before the focus on touch screens or the Wii, programs like the Opera web browser introduced the notion of mouse gestures. The concept was simple: instead of using the position of the cursor to determine what action to perform, the motion of the cursor itself would indicate an action. So by moving the cursor in a circular motion you would trigger a web browser to refresh. By moving it left you would go back in the page history, and by moving it right you would move forward.
For Flash developers there's a free mouse gesture library that enables this type of interaction with very little effort. To demonstrate how it's used, we'll create a simple video player that uses mouse gestures, rather than buttons, to modify the video playback.
Step 1: Mouse Gesture Library
Download Didier Brun's mouse gesture library here (), and extract it to a convenient location.
Step 2: New Application
Create a new Flex web application and add the mouse gesture library to the list of build paths. You can access the build path property by selecting Project > Properties > Flex Build Path within Flex Builder.
Step 3: FLV
You'll need an FLV video file to test the application with. The demo version of the IMToo FLV converter () will convert short videos from almost any format to FLV. If you don’t have a collection of FLV movies lying around, this tool is ideal for converting almost any free video you can download from the web. I have converted one of the demo videos that ships with Vista for this demo.
Step 4: Application Attributes
You will need to modify some of the attributes of the Application element, contained in the MXML file. Here we've specified the width, height, background color (backgroundGradientColors) and transparency (backgroundGradientAlphas). We've also set the appComplete function to be called in response to the applicationComplete event. This gives us an entry point in the application where the mouse gestures will be set up.
<mx:Application xmlns: </mx:Application>
Step 5: mx:VideoDisplay
Add the following mx:VideoDisplay element as a child of the mx:Application element.
<mx:VideoDisplay
The id attribute assigns a name to the VideoDisplay that we can reference from ActionScript.
The top, bottom, left and right properties define the position of the VideoDisplay.
The autoPlay attribute is set to false, which means the video will not start playing straight away.
The source attribute points to the location of the video file. If you have your own FLV video file, then you will need to modify this attribute to point to it.
The metadataReceived attribute points to a function that will be called once the details of the video have been loaded by the VideoDisplay. We use this to find out how long the video is, so we can modify the maximum value of the HSlider.
The playheadUpdate attribute points to a function that will be called as the video is played. This allows us to track the current position of the video file, and update the HSlider accordingly.
Step 6: mx:HSlider
Add the following mx:HSlider element as a child of the mx:Application Element
<mx:HSlider
The id attribute assigns a name to the VideoDisplay that we can reference from ActionScript.
The top, bottom, left and right properties define the position of the VideoDisplay.
The change attribute defines a function to be called when the user changes the sliders position.
Step 7: Interface
You should now have a GUI that looks like the one below.
Step 8: mx:Script
Add an mx:Script element as a child of mx:Application. This element will hold the ActionScript code for our application.
<mx:Script> <![CDATA[ // code goes here ]]> </mx:Script>
Step 9: Import Packages
We need to import a number of packages. This is done inside the mx:Script element. Three classes from the mx.events package, MetadataEvent, SliderEvent and VideoEvent , are used as the parameters in event listener functions. The com.foxaweb.ui.gesture package includes the classes from the mouse gesture library.
import mx.events.MetadataEvent; import mx.events.SliderEvent; import mx.events.VideoEvent; import com.foxaweb.ui.gesture.*;
Step 10: Define Constants
A number of constants are then defined. The VIDEO_STEP constant defines how much time the video's current position will be moved by when we step forward or backward. The other strings all define the names of actions that will be associated with mouse gestures. In general it is prudent to map strings to constants when they are used as an identification, as it allows the compiler to pick up misspellings like if (action == SETP_FORWARD), instead of running into issues at runtime with misspelled strings like if (action == "setp_forward").
private static const VIDEO_STEP:Number = 1; private static const PLAY:String = "play"; private static const STOP:String = "stop"; private static const PAUSE:String = "pause"; private static const STEP_FORWARD:String = "step_forward"; private static const STEP_BACKWARD:String = "step_backward";
Step 11: Define Variables
The last variable we need to define is a reference to a MouseGesture object. It's this object that implements the logic for the mouse gestures.
private var mg:MouseGesture = null;
Step 12: New Function
Add a new function called appComplete. This is the function we assigned to the applicationComplete attribute in the mx:Application element. It is here that we will initialise the mouse gestures.
private function appComplete():void { mg = new MouseGesture(this.stage); mg.addGesture(PLAY,"0"); mg.addGesture(STOP,"4"); mg.addGesture(PAUSE,"2"); mg.addGesture(STEP_FORWARD,"67012"); mg.addGesture(STEP_BACKWARD,"65432"); mg.addEventListener(GestureEvent.GESTURE_MATCH,matchHandler); }
Step 13: Mouse Gestures
First we create a new MouseGesture object. The MouseGesture constructor needs to be passed a reference to the stage in order to respond to mouse events.
mg = new MouseGesture(this.stage);
Next we define a number of mouse gestures. A mouse gesture is defined as a sequence of mouse movements, with numbers representing movement directions as per the image below. All mouse gestures start by clicking the left mouse button and end with the button being released.
For a simple gesture where the mouse is moved in a straight line we use a string with a single number in it. Here the "play" mouse gesture is defined as mouse movement in a single direction, right, which is represented by the numeral 0.
mg.addGesture(PLAY,"0");
Likewise the "stop" and "pause" mouse gestures are defined as mouse movements down and left.
mg.addGesture(STOP,"4"); mg.addGesture(PAUSE,"2");
The "step_forward" mouse gesture is more complex. It is defined as a half circle mouse movement, starting at the left and then moving over and to the right. The red arrow shows the start of the movement.
This movement is defined by the string "67012". You can see how this string is derived by matching the movement of the mouse with the numbers that are assigned to those movements. We start moving up (6), diagonally up and right (7), left (0), diagonally down and right (1) and then down (2).
mg.addGesture(STEP_FORWARD,"67012");
The "step_backward" is defined in the same way, only this time it is a half circle mouse movement, starting at the right and then moving over and to the left.
mg.addGesture(STEP_BACKWARD,"65432");
We then assign the matchHandler function to be called when a mouse gesture has been detected.
mg.addEventListener(GestureEvent.GESTURE_MATCH,matchHandler);
Step 14: The MatchHandler Function
The matchHandler function is called when a mouse gesture has been detected. The event parameter contains a property called datas, which will match one of the constants we assigned to the mouse events in the appComplete function. Depending on the mouse gesture that has been detected we perform certain actions on the VideoDisplay. The play, stop and pause actions are all quite straight forward. With the step_forward and step_backward actions we either increase or decrease the playheadTime property of the VideoDisplay, which has the effect of skipping forward or backward.
private function matchHandler(event:GestureEvent):void { switch (event.datas) { case PLAY: this.videoPlayer.play(); break; case STOP: this.videoPlayer.stop(); break; case PAUSE: this.videoPlayer.pause(); break; case STEP_FORWARD: var newFowardTime:Number = this.videoPlayer.playheadTime + VIDEO_STEP; while (newFowardTime > this.videoPlayer.totalTime) newFowardTime = this.videoPlayer.totalTime; this.videoPlayer.playheadTime = newFowardTime; break; case STEP_BACKWARD: var newBackwardTime:Number = this.videoPlayer.playheadTime - VIDEO_STEP; if (newBackwardTime < 0) newBackwardTime = 0; this.videoPlayer.playheadTime = newBackwardTime; break; } } }
Step 15: HSlider
This demo is all about modifying the video playback using mouse gestures, but for convenience a HSlider can also be used. The metadataReceived function is called once the VideoDisplay has loaded the meta data, which includes the total length of the video. In this function we set the maximum value of the slider to the total length of the video. We then enable the slider – until we know how long the video is the slider can’t be used to set the position.
private function metadataReceived(event:MetadataEvent):void { this.videoPosition.maximum = this.videoPlayer.totalTime; this.videoPosition.enabled = true; }
Step 16: playHeadUpdate Function
The position of the slider needs to be kept in sync with the current play back position of the video. The playHeadUpdate function is called at regular intervals by the VideoDisplay, and it is here that we set the value of the HSlider to the playheadTime of the VideoDisplay.
private function playHeadUpdate(event:VideoEvent):void { this.videoPosition.value = event.playheadTime; }
Step 17: videoPositionChanged Function
The slider can also be used to change the current play back position of the video. Here we do the reverse of the playHeadUpdate function, and set the playheadTime of the VideoDisplay to the value of the HSlider.
private function videoPositionChanged(event:SliderEvent):void { this.videoPlayer.playheadTime = this.videoPosition.value; }
Conclusion
When you load up the application you should see the video file. Because we set the autoPlay attribute of the VideoDisplay object to false, the video will be stopped, showing the first frame.
Click the left mouse button, move the mouse left and release the button, and the video should play. Click, move the mouse down, and release, and the video should pause. Click, move the mouse in a top half circle from left to right and release, and you should see the video skip a second ahead.
Another benefit of mouse gestures is that they remove the need for other UI controls, which can be a huge advantage when screen space is at a minimum (like banner ads). You could even use them for those "feed the monkey" or "do the most chin-ups" banner ad games.
Mouse gestures are very easy to implement in Flash, and they provide an intuitive way to interact with a PC. With only a few lines of code you can redefine how users interact with your application, and they free up the screen space that was reserved for more traditional UI components.
Thanks for reading, I hope you learned something!
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/control-a-flex-video-application-using-mouse-gestures--active-2130 | CC-MAIN-2018-05 | refinedweb | 1,875 | 63.29 |
Yeah that looks like memory corruption/bad pointers to me. I see you are using the ID as the index into the file.
Printable View
Yeah that looks like memory corruption/bad pointers to me. I see you are using the ID as the index into the file.
The templates are indeed better than the generic void*, but that's if the OP has learned to use them yet. I don't know.
Now that's even better!Now that's even better!Quote:
yes Next and Prev should be LINK*
hmmmm . ok.... o_0 I don't know WTF are you talking about but I need some help here. ^^
Well, let's think about it here.
First, your operator >> is not supposed to ask for data. That's your main program's doing. The object should just serialize itself. And it should probably do that in such a way that it writes a total of sizeof(yourobject) bytes so it seek alright.
You need to separate code for object and program.
Then you realize that IDs can be stored in any order, right? I can type in 1000 for the first, and then 10 for the second. The program would seek to 1000 * sizeof(myobject) and expect the data to be there, but it isn't.
What you need is an index. A map, perhaps. Map id to position in file.
Write that contents of the map to the file too when you close the program as an index, and load the index when the program starts.
Then the problem should be fixed.
:| The problem is that you are assuming I'm an expert. I"m just a newbie so what you just said right there doesn't make any sense to me whatsoever.
I think I was perfectly honest with you. Try to think into terms what happens if you enter 1000 for ID, for example. How will the program react? Use a debugger if you must. Se why you get what you get.
You need an index. Or you can simply make the ID automatic for every object. Or omit it completely.
Ah, it's your logic in circle's operator >> that's broken. Think about the method again and what it does, and why it can't possibly work the way you want it to.
Here's an output example:Here's an output example:Code:
ostream& operator <<(ostream& output, const Circle& aCircle)
{
output << aCircle._circleId << " " << aCircle._circleRadius;
return (output);
}
istream& operator >>(istream& input, Circle& aCircle)
{
int quantity;
cout << "\nHow many circles do you want to add ";
input >> quantity;
for (int i = 0; i < quantity; ++i)
{
aCircle._circleId = i;
input >> aCircle._circleRadius;
}
return (input);
}
I do not see where you "add" Circles.I do not see where you "add" Circles.Quote:
Like everyone said i let the loop generate the ids, but still not working
You always work with the same variable - overwriting it on each loop iteration
Right, let's try this again. Perhaps this time without flaming.
You still haven't thought about >> and its purpose enough. Moreover, you haven't thought about the implementation and what it does enough.
Consider this: a variable holds one item of data. (The data can be large and complex, depending on the type of the variable.) >> should fill one variable. Consider what data a single Circle object holds, and what your >> tries to do. | http://cboard.cprogramming.com/cplusplus-programming/98987-file-i-o-reading-random-access-file-2-print.html | CC-MAIN-2016-18 | refinedweb | 566 | 77.43 |
Introduction to Functional Programming
“One withstands the invasion of armies; one does not withstand the invasion of ideas.” - Victor Hugo
In recent times, functional programming has invaded codebases all around the world.
Look at the main programming languages. We wouldn’t be able to live without higher-order functions, those anonymous functions that new developers tend to extremely overuse, and other cutesy stuff.
This is not going to be a functional programming tutorial that will show how to use these features in JavaScript. You can find that on freeCodeCamp.
In what can only be described as “a crazy move that will decimate the view count of this article”, I’d rather talk about the paradigm from which these features have been captured from. Ready?
What is functional programming?
In short, functional programming is a catch-all term for a way of writing code that is focused on composing pure functions, actually using the innovations in type systems made in the last few decades, and overall being awesome.
So what’s the point? All of these things help to better understand what actually happens in our code.
And, once we do that, we gain:
- better maintainability for the codebase;
- more safe, reliable, composable code;
- the ability to manage complexity with abstractions that are borderline wizardry.
You’re a functional programmer, Harry.
As it is, functional programming is ideal for developing code for distributed systems and complex backends, but that isn’t all it can do. At Serokell, we use it for most of our industry projects. Whether you need frontend or backend, it doesn’t matter, there is an FP language for everything nowadays.
Now that you are stoked about learning more about functional programming and have already ordered your copies of Programming Haskell on Amazon, let’s delve deeper into the details.
From lambda calculus to lambda logo in 90 years
At the heart of functional programming is lambda calculus.
Introduced by the mathematician Alonzo Church in the 1930s, lambda calculus is just a way of expressing how we compute something. If you understand this one, you will gain a lot of intuition on how functional programming looks in practice.
There are only three elements in lambda calculus: variables, functions, and applying functions to variables. Here we have to think about function as a pure/mathematical function: a way of mapping members of a set of inputs to members of a set of outputs.
Even though it is a very simple tool, we can actually compose different functions and, in that way, encode any computation possible with a regular computer. (It would get unwieldy fast for anything non-trivial though, and that’s why we don’t program in it.)
To further illustrate the concept, I refer you to this video of an absolute madman implementing lambda calculus in Python.
In 1950-60s, people began to encode this notion into programming languages. A good example is LISP, a kind of functional language designed by John McCarthy that keeps the overall incomprehensibility of lambda calculus while actually enabling you to do some things.
Example implementation of A* search algorithm in Racket (a dialect of LISP).
#lang racket (require racket/set) (define (pq-inserts elems pq) (sort (append elems pq) (lambda (a b) ((first a) . < . (first b))))) (define (a-star estimate neighbors dist eps start) (define (go visited pq) (match pq [(list* (list estimation distance path) rest-pq) (let ((point (first path))) (if ((estimate point) . <= . eps) path (let* ( (near (filter (compose not (curry set-member? visited)) (neighbors point))) (paths (for/list ([pt near]) (let ((distance1 (+ distance (dist point pt)))) (list (+ distance1 (estimate pt)) distance1 (list* pt path)))))) (go (set-add visited point) (pq-inserts paths rest-pq)))) )] [else '()])) (define initial (list (list 0 0 (list start)))) (reverse (go (set) initial)))
But that was only the beginning. One thing led to another, and, as we introduced such languages as ML and Miranda, the numerous permutations explored adding readability and a great type system. As a result, the 1980s saw the arrival of something beautiful – Haskell, a programming language so great that it was destined to evade mainstream for the next 30 years.
The same A* algorithm in Haskell.
import qualified Data.Map as Map import qualified Data.Maybe as Maybe import qualified Data.Set as Set import qualified Data.List.NonEmpty as NE import Data.List.NonEmpty (NonEmpty (..), (<|)) {- | I use `Map.Map` as a priority queue, by popping element with a minimal key using `Map.minView`. -} aStar :: (Num d, Ord d, Ord a) => (a -> d) -- distance estimation -> (a -> [a]) -- neighbours retrieval -> (a -> a -> d) -- distance between 2 points -> d -- distance from end we should reach -> a -- starting point -> Maybe (NE.NonEmpty a) aStar estimate neighbors dist epsilon start = do NE.reverse <$> go Set.empty initialQueue where initialQueue = Map.singleton (cost start 0) (start :| [], 0) cost point traversed = estimate point + traversed go visited queue = do ((path @ (point :| _), distance), queue') <- Map.minView queue if estimate point <= epsilon then do return path else do let near = filter (`Set.notMember` visited) (neighbors point) batch = flip map near $ \point' -> let distance' = distance + dist point' point in (cost point' distance', (point' <| path, distance')) go (Set.insert point visited) (Map.fromList batch <> queue')
We’ll return to Haskell later.
What else?
Ok, I hope I gave the intuition about how pure functions and chaining pure functions would look. What else is there?
Immutability. This follows from pure functions. If the function has an input and gives an output, and doesn’t maintain any state, there can be no mutable data structures. Forget i++. This is for the better. Mutable data structures are a sword that looms over the developer’s head, waiting to fall at any moment.
Immutability also helps when the underlying code needs to be thread-safe and therefore is a huge boon in writing concurrent/parallel code.
All kinds of ways to handle functions. Anonymous functions, partially applied functions, and higher-order functions – these you can get in all modern programming languages. The main benefit is when we go higher up the abstraction ladder. We can introduce various kinds of design patterns such as functors, monads, and whatever-kinds-of-morphisms that we port right from category theory, one of the most powerful tools of mathematics, because… get it? Our code is a composition of mathematical functions.
There is a chance you stopped at immutability and thought: how can we accomplish anything without maintaining a global state? Isn’t it extremely awkward? Nope. We just pass the relevant state through the functions.
While it may seem unwieldy at first (and that is more because it is a new style of programming, not because of inherent complexity), functional programming abstractions help us to do it easily, For example, we can use special constructions such as state monad to pass state from function to function.
As you can see, functional programming concepts synergize well with each other. In the end, we have a self-consistent paradigm that is wonderful for anything where you would want to include an element of it.
Functional programming languages will make your business rich beyond belief
I’ve been holding back on the greatest thing, though.
Did you know that a lot of smart people are doing Haskell & Co nowadays? Functional programming is a great way to gather/meet unappreciated talent that hasn’t yet been devoured by the corporate clutches of FAANG.
We know this from experience. Our engineers are badass, and not only on our team page.
So if there is a project you want to kick off, and you want to kick it off with a team that will rock your socks off, I will list a few functional programming languages with which to attract next-level developers.
Haskell
Haskell was developed back in times far, far away when the FP community faced the situation of there being too many goddamn functional programming languages with similar properties. Turns out when you bring a lot of smart people together, something can happen. But more about that in our Haskell history post.
Since then, Haskell has established itself in certain fields, such as:
- Finance
- Biotech
- Blockchain
- Compilers & DSLs
Many large companies have projects of various sizes that use Haskell.
Haskell is a combination of various ideas that, brought together, have created a being of utter (expressive) power:
- Purity. There’s a clear boundary between pure code (composed of pure functions) and impure code (input/output).
- Static typing. Types are checked at compile-time, not at run-time. This prevents a lot of run-time crashes in exchange for having to actually deal with types, which some find difficult.
- Laziness. Expressions are evaluated only when the value of the expression is needed in contrast to strict evaluation where the expression is evaluated when it is bound to the variable.
- Immutability. The data structures are immutable.
It’s one of our favourite languages, and for a reason. Haskell, when used correctly, delivers. And what it delivers is precise and effective code that is easy to maintain.
Scala
Want to go functional, but would love to spoil it with a couple of classes here and there?
Scala is the right choice for that. For some reason favoured by people that wrote Apache Spark, it can be useful for big data processing, services, and other places where functional programming is amazing.
An additional bonus of Scala is that it compiles to JVM. If that is something you need as a manager to introduce functional programming to a Java codebase, go you!
Once you start writing purely functional Scala that does not interact with JVM, there are not a lot of reasons to just switch to Haskell though as the support is much better.
OCaml
If Haskell is a bit niche, OCaml is super niche with one of the main things holding it above water being local developer support in France.
But perhaps not anymore. For example, similarly to other programming languages listed, it has seen use in blockchain, particularly, Tezos. And they have their reasons.
OCaml is one of those languages that blurs the boundary between functional programming and object-oriented languages. Therefore, using OCaml over Haskell might be more intuitive for a newly functional programmer. OCaml is less obsessed with purity, and the people who write in it are a bit more practical: you might survive the attack of your fellow developers if you just try to wing it in OCaml.
Elixir
Did you know that the world’s best web framework is written in a functional programming language? Productive. Reliable. Fast. Yeah.
Elixir is a functional, general-purpose programming language that runs on BEAM, the Erlang VM. It is known for its role in creating low-latency and fault-tolerant distributed systems. Furthermore, it is great at creating stuff that scales according to the needs of the network. Elixir is extremely well used at companies like WhatsApp and Netflix that handle a lot of data and need to do it fast. You can’t miss this one if you are doing something similar.
Serokell for your projects
You know, I cannot end without a pitch. Functional programming is excellent for extensive systems and structures. However, not every business can devote enough resources to execute such complicated work. Serokell understands the struggle and aims to deliver the best service possible to ensure smooth and reliable programming projects for your company.
Our developer team provides development services in different languages. We not only write code but also carry out projects from their starting ideas to their last stages. This means that we can also do research, design, and other connected services for you. Although we offer a versatile coding language scope, I have to warn that we mainly use Haskell.
Visit our page and learn more about how you can make your projects at least ten times more amazing by using Serokell’s services. Thank you for reading.
| https://serokell.io/blog/introduction-to-functional-programming | CC-MAIN-2021-43 | refinedweb | 1,982 | 63.29 |
SYNOPSIS#define _XOPEN_SOURCE /* See feature_test_macros(7) */
#include <signal.h>
typedef void (*sighandler_t)(int);
sighandler_t bsd_signal(int signum, sighandler_t handler);
DESCRIPTIONThe VALUEThe bsd_signal() function returns the previous value of the signal handler, or SIG_ERR on error.
ATTRIBUTESFor an explanation of the terms used in this section, see attributes(7).
CONFORMING TO4.2BSD, POSIX.1-2001. POSIX.1-2008 removes the specification of bsd_signal(), recommending the use of sigaction(2) instead.
NOTESUse defined only if the _GNU_SOURCE feature test macro is defined.
COLOPHONThis page is part of release 4.06 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at | https://manpages.org/bsd_signal/3 | CC-MAIN-2022-21 | refinedweb | 114 | 50.33 |
.
All executable code must be inside a procedure. Use a Sub procedure when you do not need to return a value to the calling code. Use a Function procedure when you need to return a value.
You can use Sub only at module level. This means the declaration context for a sub procedure must be a class, structure, module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see Declaration Contexts and Default Access Levels.
Sub procedures default to public access. You can adjust their access levels with the access modifiers.
Rules
Implementation. If this procedure uses the Implements keyword, the containing class or structure must have an Implements statement immediately following its Class or Structure statement. The Implements statement must include each interface specified in implementslist. However, the name by which an interface defines the Sub (in definedname) does not have to be the same as the name of this procedure (in name).
Behavior
Returning from a Procedure. When the Sub procedure returns to the calling code, execution continues with the statement following the statement that called it.
The Exit Sub and Return statements cause an immediate exit from a Sub procedure. Any number of Exit Sub and Return statements can appear anywhere in the procedure, and you can mix Exit Sub and Return statements.
The following example shows a return from a Sub procedure.
Calling a Procedure. A Sub procedure, like a Function procedure, is a separate procedure that can take parameters and perform a series of statements. However, unlike a Function procedure, which returns a value, a Sub procedure cannot be used in an expression.
You call a Sub procedure by using the procedure name, followed by the argument list in parentheses, in a statement. You can omit the parentheses only if you are not supplying any arguments. However, your code is more readable if you always include the parentheses.
You can optionally use the Call statement to call a Sub procedure. This can improve the readability of your code.
Troubleshooting
Order of Execution. Visual Basic sometimes rearranges arithmetic expressions to increase internal efficiency. For that reason, if your argument list includes expressions that call other procedures, you cannot rely on them being called in any | http://msdn.microsoft.com/en-US/library/dz1z94ha(v=vs.80).aspx | CC-MAIN-2014-52 | refinedweb | 375 | 57.37 |
Sun released another early-access version of the JSR 14 “Generics for Java” implementation recently, and can be found at. (The main JDC page claims that the last release was 1.2, on March 21; that’s incorrect. If you click through the link to the URL above, it reads as 1.3, released on October 30.)
Using the 1.3 release is a bit awkward, since the release itself ships as two .jar files, one for the compiler and another for the java.util Collection classes (properly genericized). This means, unfortunately, that you’ll need to put the javac.jar compiler code somewhere in the bootclasspath of the javac.exe tool when you run it, and reference the collect.jar as part of the bootclasspath when you compile and run the resulting code. The 1.3 release ships with some UNIX and Win32 script/batch files to help ease this pain, but if you’re planning to do any serious work with the release, I’d suggest just writing your own quick-and-dirty JNI Invocation launcher to get all the options in the right place; details on how to do so can be found in a variety of different JNI books, as well as my own (now horribly outdated) Server-Based Java Programming. If I get around to it, I’ll write one myself and post it here.
One nice thing about the JSR EA implementation is that once you get past the compilation phase (and if you don’t use any of the generic collection classes in collect.jar), you can run the compiled code on preexisting VMs–there’s no structural changes to the code made when compiling generics into standard Java classes. So, for example, taking this code:
class Generic
{ T data; public Generic(T d) { data = d; } } public class GenTest { public static void main(String[] args) { Generic gs = new Generic ("Hello, world"); System.out.println(gs.data); } }
and compiling it in the genericized Javac (which I’ll call gjavac from here on out) yields “Generic.class” and “GenTest.class”.
One of the goals for the JSR 14 was “designed to be fully backwards compatible with the current language, making the transition from non-generic to generic programming very easy.” Part of this means that there can be no structural changes to the underlying JVM that will be used to execute the code. (This is in direct contrast to the Gyro release from Microsoft–it patches the CLR to recognize generic types within the runtime. This pretty accurately reflects the differences in philosophy between Sun and Microsoft–Sun believes in “one language”, and Microsoft believes in “multiple languages”.) Sure enough, if we disassemble the compiled Generic class, we see
Compiled from GenTest.java class Generic extends java.lang.Object { java.lang.Object data; public Generic(java.lang.Object); } Method Generic(java.lang.Object) 0 aload_0 1 invokespecial #1 <Method java.lang.Object()> 4 aload_0 5 aload_1 6 putfield #2 <Field java.lang.Object data> 9 return
As you can see, the underlying data type for “data”, which was represented in the source as the type variable “T”, is a java.lang.Object reference. Similarly, using the parameterized Generic behaves much as you’d expect (once again, consulting javap for a bytecode disassembly):
Compiled from GenTest.java public class GenTest extends java.lang.Object { public GenTest(); public static void main(java.lang.String[]); } Method GenTest() 0 aload_0 1 invokespecial #1 <Method java.lang.Object()> 4 return Method void main(java.lang.String[]) 0 new #2 <Class Generic> 3 dup 4 ldc #3 <String "Hello, world"> 6 invokespecial #4 <Method Generic(java.lang.Object)> 9 astore_1 10 getstatic #5 <Field java.io.PrintStream out> 13 aload_1 14 getfield #6 <Field java.lang.Object data> 17 checkcast #7 <Class java.lang.String> 20 invokevirtual #8 <Method void println(java.lang.String)> 23 return
The “smoking gun”, as it were, is on disassembly lines 14 and 17: the runtime will retrieve the data as an Object, then cast it down to a String (the parameterized type) at runtime. In short, the code is no different than if you’d written it “the long way” yourself–all the type-safety is being checked at compile-time, much as C++ does.
The key thing is to realize that, despite what my earlier post about JSR 14 may have implied, the generics-in-Java effort is not stalled or dead, and with any luck we’ll see a release before JDK 1.5 goes out the door. In the meantime, I encourage you to play with the early access release, and offer feedback to the JSR 14 team about what you think of it.
And so now the race continues. Which environment will be the first with generics, Java or .NET?
Compile time checking
You wrote:
"... all the type-safety is being checked at compile-time, much as C++ does."
I know what you really meant, but this might be mis-leading to others. Yes, both C++ and Generic Java compilers perform type checking at compile time. Unfortunately, due to Generic Java's use of type erasure, the resulting byte code still includes those type checks at run time - while C++ object code doesn't.
I will take this a step further and say that, generally speaking, C++'s template mechanism and Generic Java's type erasure hold little in common. One is a Turing complete language while the other is a type cast generating device.
God bless,
-Toby Reyelts
why are people considering the greaterthan/lessthan syntax?!?!
I know that C++ used that syntax, but does anybody remember the headaches that this syntax caused parsing the tools? And what about the fact that Java code is often embedded in markup languages? Why is something like this never considered:
List of (List of (HashMap of (String,Object)))
HashMap of (List of (String),Window)
instead of:
List
HashMap>
and this is why this syntax has so much danger
in terms of breaking existing parsers:
h;
%>
...
It is more difficult to tokenize the second syntax. Even C# is going to use the latter syntax in deference to the decision to use it in C++. I don't understand the reasoning behind it.
It does appear that C# may come in with generics second, but they will probably come in with fully supported generics first because they have few compatibility issues to wrestle with.
ex: instead of reflection giving you something useless like this:
List GraphAlgorithm.StronglyConnectedParts(Graph g)
it could give you:
List of (Graph of (Vertex,Edge)) GraphAlgorithm.StronglyConnectedParts(Graph g)
or
List of (WeightedVertex) GraphAlgorithm.GreedySearch(Graph of (WeightedVertex,Edge)) | http://www.oreillynet.com/onjava/blog/2002/11/the_race_moves_up_a_notch.html | crawl-002 | refinedweb | 1,108 | 64.71 |
public class review{ //method code public void start() { int a, b; a = 5; b = methodA(a); System.out.println(a + " " + b); } private int methodA(int a) { int b = 10; a = a + 5; return a + b; } //method end }
------------------------------------------------
i compile and run this code in dr.java compiler jdk 6.0_41
it can compile, but when i run it will display like thi
"Static Error: This class does not have a static void main method accepting String[]"
when i try to add
public static void main (String[]args){ //method code }
when i compile it will display
public void start() {
as an illegal start of expression.
it is something wrong with my dr.java compiler or i wrote wrong code?
hope anyone can help.
thanks in advanced | https://www.daniweb.com/programming/software-development/threads/452859/illegal-of-expression | CC-MAIN-2017-26 | refinedweb | 125 | 73.68 |
# Writing a laptop driver for fun and profit, or How to commit to kernel even if you're not that smart
Where it all began
------------------
Let’s start with our problem statement. We have 1 (one) laptop. A new, gamer laptop. With some RGB-backlight on its keyboard. It looks like this:

*Picture taken from lenovo.com*
There’s also a program installed on this laptop. That’s the thing that controls our backlight.
One problem – the program runs under Windows, and we want everything to work on our favourite Linux. Want LEDs to flash and those pretty colours to blink on and off and such. A natural question arises, can we do all that without reverse-engineering and writing our own drivers?
A natural answer arises, no. Let’s open IDA and get cracking.
### Step 1 – Digging in the code
There are three triggers that make the backlight glow. In order of ascending difficulty:
1. Big buff gamer program called Lenovo Nerve Center, which has a big buff setup menu just for this backlight.
2. Hotkey combination Fn+Space – possibly managed by the aforementioned program, too.
3. BIOS. While the laptop is loading, the backlight blinks red for a brief moment. Maybe we can use that?
I had to try all 3. But there was some success only along the first one, so let’s talk about the first one here.
We open the folder with our program:

Notice here! There’s a DLL with a very interesting name – LedSettingsPlugin.dll. Could it be...? Let’s open it in IDA Pro and see for ourselves.

Look at the right half of the screen here – so, so much debug information! Let’s use it. Some strings look like function names here. I wonder why…

Oh, these *are* function names. Convenient! Let’s call some things by their own names and then look at the function list again. To name things in IDA you can use the hotkey N, or just right-click the thing you want to name.

Looking at functions, we see something called Y720LedSetHelper::SetLEDStatusEx. Looks like what we need! It forms some kind of a string, and then gives it to something called CHidDevHelper::HidRequestsByPath. The interesting part we should be looking at is var\_38, lovingly highlighted by IDA.
Var\_34 is interesting, too. It goes right after var\_38 – in assembler traditions, variables are stored in reverse order under the RSP. Var\_34 in IDA is just the name of the constant – -34h.
Starting from var\_38, our program puts a zero, then style, colour, the number three and the block – part of the keyboard that will gain this colour. (Later on, the experiments will show that the number three is actually the brightness. Adding a control on that will make our driver even better than the official one!)
Now, let us take a deep dive into HidRequestsByPath and try to figure out what do we need to send and where.

Look, two functions. HidD\_GetFeature and HidD\_SetFeature.
They aren’t tracked in the file… but are very well tracked in the official Microsoft documentation — [here](https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/hidsdi/nf-hidsdi-hidd_setfeature) and [here](https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/hidsdi/nf-hidsdi-hidd_getfeature).
Well, we can pat ourselves on the back now. This is rock bottom, there’s nowhere to dig deeper. Linux has those two functions – we just go back, and call them with the same arguments. ...Right?
### Step 2 – launching the prototype...?
Not exactly. Let’s go back to Linux and open up lsusb. We’ll find our keyboard there, and we’ll send something to it.

Integrated Technology Express, Inc. is the most interesting one here. Let’s use the popular tool /dev/hidraw. We can find the proper one just by looking at the corresponding/sys/class/hidraw/hidraw\*/device/uevent.

This one. All the digits match — that means /dev/hidraw0 is our device. But let’s try to send something… and nothing happens! Why. At this point, burnout kicks in. Maybe it’s not for mere mortals, this reverse engineering thing?
But let’s keep trying. Were the author more good at this, he would have reversed Nerve Center some more and come up with h a solution… But we have no brain. Let’s reboot to Windows, there’s an idea.
There’s this thing in Windows – Device Manager, they call it. Has a lot of functions – but we’re interested in one. It allows you to disable devices. Simple and authorative.
So let’s just disable all the devices until our LED stops blinking!

This did it. If we peek at its Hardware ID – we’ll see what it is, that mysterious LED device.

Look – it’s him.

The device that has been pestering my dmesg for several years.
*[Why wasn’t it shown in lsusb? It’s not USB at all, of course! The backlight uses a protocol called I2C HID – it allows the manufacturer to ~~hide the device from evil DIY people’s hands~~ install HID gadgets onto the system bus of the computer itself.]*
### Sidestep 2.5 – let’s make a commit
This search for the correct device has been heavily abridged. In the original telling, I had to open my setup almost all the way to the kernel before I realised why nothing worked. Also, I did not enjoy this dmesg log showing itself to me every time I unlock my computer. Since we’re here – why not go and write a short commit?
We need to find two things – the place where I2C HID devices are handled, and the place where their quirks are stored. [Here.](https://github.com/torvalds/linux/blob/master/drivers/hid/i2c-hid/i2c-hid-core.c) Let’s not think too hard and look at the error: incomplete report. Let’s make it complete.

Add a new quirk, let’s call it I2C\_HID\_QUIRK\_BAD\_INPUT\_SIZE or something like that. To keep the theming.

Also let’s add our device to the list of quirked. What we’ve done so far:
1. Looked up “i2c hid linux kernel” in a search engine. Clicked the 4th result in DuckDuckGo.
2. Wrote three (!) words in English – BAD\_INPUT\_SIZE
3. Added one to BIT(4). Result – BIT(5).
4. Added a number to hid-ids.h – the ID of our device (not illustrated, but it’s similar in difficulty)
We’re programmers, let’s do some programming now.
See the line:
`ret_size = ihid->inbuf[0] | ihid->inbuf[1] << 8;`
And then it complains that ret\_size is not what it ones.
Whenever our quirk is active, let’s do this but backwards.

Send the patch to the mailing list… (test it beforehand!). To be honest, getting into that mailing list was trickier than the actual patch. It’s not simple by any means.

That’s it!
### Step 3 – driver!
At this point I remembered – I was trying to write a driver. Decided I won’t commit that to kernel yet – questions began arising, at this point you really have to think some. If anyone reading this is good at kernel and can consult me, I’d be glad to talk.
Let’s open python. (Used to be bash, but you change your mind very quickly with that sort of language). Let’s use the popular tool /dev/hidraw.
/dev/hidraw0, /dev/hidraw1 — how do those files work, anyways? For simple I/O you can use them as any other, and it seems that is would just work. And GetFeature and SetFeature – well, that’s a different story entirely.
StackOverflow (or someone else, I can’t remember) told me I would have to look into something called ioctl. It’s a special way of working with uncommon files like HID devices, terminals and similar disgusting things.
It seems simple on the surface – you give it an open file handle (not Python-level, OS-level! Read more on OS handles [here](https://en.wikipedia.org/wiki/File_descriptor) if you'd like to know.), some number and a buffer – and then it does something with that buffer and gives it back to you. I’m not trying to be witty here, it’s just that it’s almost fully implementation-dependent. Here’s an example: 0xC0114806. What’s that? That’s SetFeature. That’s also
`(6 << 29) | (ord('H') << 8) | (0x06 << 0) | (0x11 << 16).`
The first 6 means the file will be open both for reading and for writing. We only write, but the docs said 6 that means we put 6. Ord(‘H’) stands for HID. Sometimes it stands for other things, depending on the file. But now it’s HID.
0x06 is the command itself. Sixth command of HID is SetFeature, which we need. And the last part? The buffer’s size.
All that remains is putting it together into an ioctl call, and you get a driver. [It works.](https://gitlab.com/kryma/lenovo-y720-backlight-driver).
### Afterword from the author
Hope the article was an interesting read. Even a useful read, possibly. Some parts were omitted or shortened for brevity – a more observant reader might notice that the driver can read the keyboard’s current state, and the set\_status function has a second ioctl call that wasn’t even mentioned in the text. Hardware development and the Linux kernel are big things, and one tale won’t cover it all. And in the end of the day, maybe the article isn’t about this. Maybe it’s just about how doing something small and good, for open-source or for yourself, is not hard at all. You just need to find a week’s worth of free evenings, some tea and a wish to dig around in code. | https://habr.com/ru/post/484752/ | null | null | 1,864 | 68.87 |
Minchin.Releaser is a collection of tools designed to make releasing Python packages easier.
Project description
Tools to make releasing Python packages easier.
Minchin dot Releaser in currently set up as an invoke task. It is designed to provide a single command to make and publish a release of your Python package. An extra configuration file is an one-time set up requirement to be able to make use of this.
Once set up, Minchin dot Releaser, when run, will:
- check the configuration
- confirm all items in the project directory have been added to Git (i.e. that the repo is clean)
- check that your Readme will render on PyPI
- sort your import statements
- vendorize required packages
- run the test suite
- update the version number within your code
- add the release to your changelog
- build project documentation
- build your project as a Python distribution
- confirm your project can be installed from the local machine to the local machine
- confirm your project can be uploaded to the test PyPI server and then downloaded and installed from this server.
- confirm your project can be uploaded to the main PyPI server and then downloaded and installed from this server.
- create a Git tag for your release
- update your version number to a pre-release version
Minchin dot Releaser relies on features added in the more recent versions of Python, and thus is Python 3 only.
Assumptions
This package makes several assumptions. This is not the only way to do these things, but I have found these choices work well for my use-cases. If you have chosen a different way to set up your project, most of the applicable features will just not work, but the rest of Minchin dot Releaser should continue to work.
It is assumed:
- this is a Python project.
- your version is stored in one place in your project, as a string assigned to the variable __version__, that this is one line and there is nothing else on this line. If this is not the case, Minchin dot Releaser will be unable to determine your project’s version number and so won’t be much use to you. This is the project’s one hard requirement in how you organize your code.
- your version number is importable by Python at <some_module_name>.__version__.
- source control is done using Git. The Git functionality will be ignored if this is not the case.
Setting Up Your Project
Step 1. Install minchin.releaser.
The simplest way is to use pip:
pip install minchin.releaser
This will also install all the other packages minchin.releaser depends on.
You will also want to add minchin.releaser to the list of your project’s requirements.
Step 2. Create a tasks.py file.
This is where invoke determine was tasks are available to run. This file should be created in the root folder of your project. If you are not using invoke for other tasks, this file can be two lines:
import invoke from minchin.releaser import make_release
To confirm that this is working, go to the command line in the root folder of your project, and run:
invoke --list
which will now list make_release as an available task.
Step 3. Configure your project.
Project configuration is actually invoke configuration, so it is stored in the invoke.yaml folder in the project root (or anywhere else invoke can load configuration from) under the releaser key.
Available sub-keys:
- module_name
- (required) the name of your project. It is assumed that your project’s version number is importable at module_name.__version__ (see project assumptions).
- here
- (required) the base location to build your package from. To set to the current directory, set to .
- docs
- (required, but can be set to None) the base documentation directory. This is relative to here.
- test
- (required, but can be set to None) the base test directory. This is relative to here.
- source
- (required) the base directory of your Python source code. This is relative to here.
- changelog
- (required, but can be set to None) the location of your changelog file. This is relative to here.
- version
- (required) the location of where your version string is stored. This is relative to here.
- test_command
- (required, but can be set to None) command, run from the command line with the current directory set to here, to run your test suite.
- version_bump
- (optional) default level to bump your version. If set to none, this will be requested at runtime. Valid options include major, minor, bug, and none.
- extra_packages
- (optional) Used to install packages before installing your module from the server. Useful particularly for packages that need to be installed from cache (rather than re-downloaded and compiled each time) or for packages that are not available on the test PyPI server. Valid server keys are local, test, and pypi. Under the server key, create a list of the packages you want explicitly installed.
(verdorize keys are not listed here.)
Step 4. Set up Invoke command shell (Windows).
Minchin dot Releaser runs certain commands at the command line. Invoke, regardless of platform, tries to run these on /bin/bash which doesn’t exist in Windows and thus these commands fail.
To fix this, create a .invoke.yaml file in the root of your user directory (so the file is C:\Users\<your_username>\.invoke.yaml) and add:
run: shell: C:\Windows\system32\CMD.exe
Step 5. Set up twine configuration.
Create or modify $HOME/.pypirc to include the testpypi server:
[distutils] index-servers= pypi testpypi [testpypi] repository: username: your testpypi username
Warning
Do not store passwords in the .pypirc file. Storing passwords in plain text is never a good idea.
Minchin dot Releaser is automated, and so needs access to your password. This can be done using keyring. Keyring can be installed by pip and then passwords are added from the command-line.
$ pip install keyring $ keyring set your-username $ keyring set your-username
See Twine Keyring Support for more details.
Step 6. Register your package on PyPI.
(On the new infrastructure, this no longer needs to be done explicitly. Just upload your package.)
Step 7. Upload your package.
invoke make_release
And then work through the prompts. If this process breaks half-way through, you can re-start.
Credits
Inspired (in part) by
Sample invoke.yaml
releaser: module_name: minchin.releaser here: . docs: . test: None source: minchin changelog: changelog.rst version: minchin\releaser\constants.py test_command: "green -kq" version_bump: none extra_packages: test: - gitdb - invoke - isort - pkginfo - semantic_version - twine - wheel pypi: - invoke vendor_dest: minchin\releaser\_vendor vendor_packages: "minchin.text": src: ..\minchin.text\minchin dest: . requirements: ..\minchin.text\requirements.in vendor_override_src: vendor_src
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/minchin.releaser/ | CC-MAIN-2019-22 | refinedweb | 1,122 | 67.15 |
# Music on the Commodore PET and the Faulty Robots
After completion of the [System Beeps](https://shiru8bit.bandcamp.com/album/system-beeps), I wasn’t planning to make another stand alone album release with the pseudo polyphonic music, as I felt the topic had been explored enough. This, however, wouldn’t mean I couldn’t apply the experience and skills gained to make more utilitarian stuff, like an actual retro game OST or an old school demoscene project. Such an opportunity arose in Autumn 2020, as David Murray of [The 8-bit Guy Youtube channel](https://www.youtube.com/c/The8BitGuy) fame announced his new game to be in development, the *Attack of The PETSCII Robots* for Commodore PET and some other Commodore 8-bitters. As I previously worked with David on his previous big release, [Planet X3](https://www.the8bitguy.com/product/planet-x3-for-ms-dos-computers/) game for MS-DOS, and this was a perfect opportunity to satisfy my interest towards the pre-graphics era PCs as well as apply my vast experience both in the minimalistic computer music and 6502 assembly programming, I offered my services that had been accepted. Besides the sound code I also had hopes to participate as a music composer this time.
Unfortunately, this time the project didn’t went well on my side, and lots of issues of all kinds eventually turned it into a small scale development hell (you can learn more from a [series of posts](https://www.patreon.com/shiru8bit/posts?filters%5Btag%5D=pet%20robots) at my Patreon blog) The end result was that my code and sound effects were only used in the VIC-20 port, and music for other versions has been created by other people. However, I was left with the full working code of the sound system for PET, and a number of music sketches. It would be a pity to file it into the archive, PET projects aren’t a frequent thing these days, so another chance to use the stuff wouldn’t come any time soon. So I got the idea to develop my music sketches into full songs, and release it as an alternative OST, and having David’s approval it has been done and released in the Winter 2021 as [Faulty Robots](https://shiru8bit.bandcamp.com/album/faulty-robots), a small music album for PET that is available as a digital audio release and a runnable program for the actual PET computer.
You can hear and see the whole thing in the action in the video below. The following article tells the story full of epic wins over numerous difficulties on the thorny path to this weird music release.
### The Music
This time I decided that good things should come in a small package, thus I limited the ear torture session with just eight short songs. In fact, their length had been severely limited by the technical constraints described below. This resulted in a total play time of 13 minutes.
The core album concept is a deconstruction, an alternative perspective on the game’s contents, the hardship of the robots from the game story, as well as the development difficulties of the project itself. A word to describe it is minimalism. Highbrow aside, something is making beeps to some to love, and some to hate.
A few words about the creative process behind each of the songs, and how the entangled creative mess straightens up into the well ordered structure of the final release.
*Faulty Robots* — has been envisioned as the title screen song, the melody there is based on chanting the title. It was one of the first sketches, developed up to the second verse. It has got a bridge and the second verse in the finished version.
*Rusty Gears* — the first fully finished track that has been composed to test out and show up the sound system capabilities. David and I considered it to be difficult to follow and not really match the game stylistically, so we didn’t plan to include it into the game. Has been altered a bit for the album release.
*Conveyor Belt* — was planned to be a short loop on the level stats screen, when you beat or lose a level. For the album version I added the second verse with the arpeggio starting from the bridge and then running as a counterpoint to the main melody.
*Old Model* — has been created just about before it became clear that I won’t be making music for the game. So it was changed from an uneventful background music for the gameplay into a song with more melodic content.
*Crosswired* — the first proposal for the in-game music. It had to be arranged with lots of air, the pauses between the notes, so sound effects would cut through it easily, and it had to be as lengthy as possible considering the memory limitations, to not be much annoying after numerous repeated plays. I was afraid that it lacks melodic content too much, so it won’t be enough for a stand-alone music release, but in fact some album listeners highlighted this one as theirs favorite.
*Scraplord* — started its life as a riff to serve as a base for one of the in-game songs. It was pretty difficult to figure out how to turn it into a full blown song. Unlike most of the other songs that have been directly written down from the head into the tracker, I had to do this one by improvising on the keyboard, recording it in Reaper, then cutting the best parts together into a single melody.
*Bosstown Dynamics* — the very last track that has been composed specifically for the album, to make the eight songs total. The work on the melodic part wasn’t going smoothly again, so it also has been cut together from the best parts of improvised pieces. The title is a nod to the Corridor viral videos.
*Not Obsolete* — interestingly it started as the very first test of the sound engine, just a mere pattern with a few random notes. When I got the track counts up to six, I wanted to add two more to make it (binary) even. So I just added some waveform changes, and as it happens sometimes, it kinda developed its true shape hidden within, so I just had to carve it out, and it made a bit of a sad but affirmative finale. The title is a quote of the world’s most famous cyborg from an unnecessary follow-up.
As the songs were initially intended to be used in a game, they were all seamlessly looped. Once all tracks were done and the player shell programmed, I felt it needed a more definitive conclusion, so I added an extremely basic coda to each of the songs, basically just a couple notes here and there.
In conclusion, I personally like the end result more than the previous one, *System Beeps*. In both cases I was trying to move away from a much limited but kinda typical chiptune music into the aesthetics of old computers that make their beeping randomly, and that somehow develops into a defined melody. I think I was able to get closer to that feeling this time.
### History Reference
While the artsy creative portion of the album mostly appeals to the relatively small community of chiptune fans, the technical portion may have an interest for a wider group of the retro computing enthusiasts.
It should be noted that Commodore computers were mostly absent here, in Russia. Back in late 1980s when home computers started to be more affordable, they were mostly presented with obscure i8080-based Soviet stuff and ZX Spectrum clones, and US or Japanese made computers were a major rarity - if anything, that would be presented with Atari 8-bit and MSX families at best. Unlike the rest of the world, C64 and especially everything prior to it was virtually unknown, besides maybe brief mentions in the books. The situation only changed a bit in the late 90s when second hand Amigas became available, they got their following, but of course it lost the market to much more affordable IBM PC compatibles. So Commodore PET is a total obscurity here.
I don’t have to get into the PET history for the readers from the rest of the world, as it is more or less known there. I’ll just say that it is one of the earliest (1977) fully featured personal computers, complete with its own CPU, display, keyboard, and everything else, as well as one of the first successful mass market computers of this kind. It can barely be defined as a home computer, and it is certainly not designed for video games. It lacks any graphics capabilities, just 40x25 or 80x25 monochrome text mode with a fixed character set that features some pseudographic symbols. First models came without any sound capabilities at all, later ones got a simple speaker added to make system beeps. You likely won’t find a less suitable platform for a computer musician, yet it makes it the more appealing challenge to overcome.
Personal computers of such an early era, when the whole format of such devices has been just getting established, often have lots of personality, and PET is one of the most peculiar. It has a bright retro futuristic appearance, it features a very distinct pseudographic character set called PETSCII, it has an all rectangular keyboard that lacks the now obligatory top row with the numbers, and that offers only two keys to control the cursor movements. It hides even more funny quirks under the hood. Like, when BASIC’s PEEK can only read the RAM under 49152, because the BASIC ROM is located above, and presumably this limitation has been put to prevent users from reading the ROM contents. One of such special quirks of the system was the unusual approach to the sound hardware as well.
There are three common approaches to the sound hardware in the computers of the past.
The sound hardware of the most budget computers is often presented with just a single bit I/O line that is connected directly to the sound speaker. The CPU has to toggle this output bit on and off using carefully timed code to produce a tone of the desired frequency. This normally takes a major chunk of the CPU performance, if not the whole time, to produce the sound, and does not allow running anything else in the background while the sound is playing. In other words, if a game or a program needs to play a music or a sound effect, any screen activity should stop.
Home computers designed to run video games were using the opposite approach, employing relatively complex custom hardware such as sound chips that are specifically aimed to generate multichannel sound in the background. Having a dedicated sound chip allows it to play sounds without stopping the action, the CPU only needs to pass the sound parameters to the sound chip from time to time.
The business targeted machines, and PET can be seen as one of these, were using something in between of these two extremes. They often had a solution similar to the famous PC Speaker of the IBM PC/XT fame - a sound speaker driven by a programmable timer chip, such as the i8255. It can produce simple beeps without stopping the other activity, but the sound capabilities are normally limited to just a single channel of basic square wave.
### The Sound Customs
The early PET 30xx models lacked any sound capabilities, neither they had a dedicated sound hardware, nor a built-in speaker. The platform enthusiasts weren’t happy with this, so they came up with a very simple modification that allowed them to produce some sound. This modification has been adopted by Commodore, and implemented in the following, more widespread PET models 40xx and 80xx.
PET uses a MOS 6522 chip, also known as VIA (Versatile Interface Adapter) to communicate with the peripherals. It is a multi-function chip that provides a couple of parallel I/O ports and a very rudimentary serial I/O port. The serial port support is presented with a 8-bit shift register and two programmable timers. It was the software duty to utilize these resources to implement an actual serial interface protocol.
When the PET enthusiasts were adding the sound speaker to the early PET models, they went with quite an original route. One would expect they would use a PIO line, which is a common and simple solution. However, they used the CB2 line, that is the output of the shift register of the serial interface. One of the 6522 timers defines the shift frequency, so if you load the alternating bit pattern such as %11110000 there, you’ll get the square wave, leaving the CPU to do other things. This design kinda looks like the PC Speaker, however, it has more limitations, and an advantage in a way.
The main limitation is the frequency range. The counter of the timer that clocks the shift register is only 8-bit wide. The 6522 clock frequency of 500 kHz gets divided by the programmed 8-bit value (1..255), then by the number of the bits in the shift register, i.e. 8. With %11110000 loaded to the shift register the lowest available frequency would be 500000/8/255, which is about 245 Hz. The shift register could be loaded with %11001100 or %10101010 bit patterns even, however, that would only multiply the resulting frequency by 2 or 4. This means the lowest possible note you can get with the 6522 generated sound is somewhere near the B-3. That omits the whole bass range that is the staple of nearly all modern music, and the pitch of the higher notes gets far from the perfect tuning. This makes it very difficult to make any music that is pleasant for the ear.
The advantage of the MOS 6522 in sound generation is that the shift register can be loaded with any other bit pattern as well, which allows it to have a richer sound variety, not limited to just the classic 50% square wave. In addition, it can generate IRQs using the second, 16-bit timer, as well as at the end of a full shift cycle. The latter allows us to overcome the hardware limitations with software tricks.
During the commercial life of the PET, programming books weren’t going into deep details, mostly providing a table of the three octave range for the two 6522 registers that controls the shift register contents and the 8-bit timer divider. The insufficiency of the information on the serial interface part even has been explicitly acknowledged in one of editions of the original 6522 datasheet. There were a few exceptions, some books did mention the possibilities of improving the sound by using the IRQ to reload the shift register ever so often, or by c[onnecting an external DAC](https://archive.org/details/COMPUTEs_Programming_the_PET-CBM_1982_Small_Systems_Services/page/n301/mode/2up?view=theater) to the parallel port (much like the Covox). However, as the home computer market was progressing rapidly, and PET wasn’t a gaming or home machine to begin with, so there was not much support from the big software development companies, PET became an obsolete artifact way before these ideas were properly explored and used by the not so large community of the PET enthusiasts.
As the result, the better PET games and other software was sounding mostly like this:
Decades later, in the modern time the proposed techniques were explored and employed in the demoscene productions, and pretty amazing results have been achieved. Some are certainly much more impressive than my work that I’m describing here, however, they require nearly the whole CPU time and lots of RAM, which makes them not much applicable to the games. Here is an example:
### A Brief History of Failure
Getting started with the project I had a vague idea of the PET architecture, distorted with the previous experience with similar machines, such as Robotron 1715 (a i8080 based text only business machine) - I expected it to have the basic speaker controlled with one I/O line, and sound to be produced with a well timed code. So I envisioned the sound for the game much along the lines of ZX Spectrum 48K or Apple II games - software synthesized sound effects and music pieces that stops the action.
I have a vast background with lots of prior work of this kind that has been used in literally hundreds of retro games created in the past decade. So I expected that I could just adapt it to the PET, and the job would be done quickly and easily. However, soon it turned out that David’s vision is much different, he would like to have a solution much similar to the PC Speaker sound in MS-DOS games - a single channel sound produced by the 6522’s CB2 and played simultaneously with the gameplay, without interrupting it and without taking much CPU time.
The original plan was supposed to have versions of the sound code for Commodore VIC-20, Commodore 64, and eventually Commodore Plus/4. All of these have much more advanced and sound capabilities, full of pretty unique limitations that are only specific for a particular platform. The sound system had to be developed with all of this specific consideration and even it out somehow. The original plan also considered that the exact same sound data would be shared between all the platforms. The PET was considered the primary platform, setting the main limitations, while other versions for the rest of the platforms just had to recreate a similar sound, just with polyphony and minor improvements added on the top.
Another key requirement that affected the system design a lot was the need to save as much memory as possible, because it was severely limited in the VIC-20 version. Both the sound code, and the sound and music data had to be as compact as possible. This automatically would put the limitation on the code and music format complexity, further limiting its capabilities, and ultimately the complexity of the music arrangements. There was just 2.5K or RAM for the whole sound code, all sound effects, and a single reloadable music track. That’s about 2.5 times less than usual. This was the reason that support of the most advanced features of more capable platforms, such as SID waveforms and the filter, was not considered from the beginning - it would take a much more complex format and sound code that would take more RAM.
Yet another specific requirement was the black box style code integration. This means that the sound code wouldn’t be included as the assembly code source into the main program. It rather had to be a loadable separately compiled binary that would communicate with the game code through commands passed via assigned RAM location, rather than the usual jump table approach. This idea was kinda weird to be used in a single CPU architecture (it is a commonplace in multi CPU architectures such as Genesis and SNES), so it didn’t work well in the end.
In the middle of the development process a major priorities shift happened. It has been decided to exclude the music from the PET version altogether, because of the technical difficulties that arose during the development and slowed it down considerably, and because the built-in speaker is just too quiet. The VIC-20 version has been promoted as the primary one, which now would take a much different sound system design. The C64 version got the improved graphics and a totally different sound content with the SID music, up to the common C64 standards, being composed by Noelle using the player from goattracker.
This grand plan with many specific goals and changing priorities ultimately turned into a major failure on my end. Eventually the code that was meeting the requirements has been finished and debugged, a way to produce sound content has been created, all sound effects made, and some of the music has been sketched out, too. It all was working fine in separate test programs that were running in VICE and MAME emulators. However, these tests failed to run properly on David's side, both in the very same emulators and on the real hardware, for an unknown reason. It didn’t work being integrated into the actual game as well. All the deadlines were missed, so there was no time to figure out this mystery, and being put into an awkward position, David had to take a decision to release the first batch of the PET version copies without the sound at all, then implement his own sound code for the PET. As a result, the only version of the game that still featured some of my sound code, sound effects, and a test song, was the VIC-20 one.
### Pushing The Limits
The first issue to be solved was the issue with generating the low frequency sounds on the PET. David wouldn’t consider this a problem, but I was sure it is important. I just couldn’t imagine how it is possible to compose the high pitched in-game music without a bass section that wouldn’t get extremely annoying after a few seconds.
As 245 Hz is pretty low, I leaned towards this solution: sounds above 245 Hz would be generated via the regular 6522 means, and for sounds below I would run a software emulation of the 6522 shift register on the IRQ from the second, 16-bit timer. The worst case scenario would be 5 IRQs per TV frame, so it shouldn’t hit the CPU performance too much.
David didn’t like the idea much, as he was worrying it may hurt the performance and be a potential source of trouble in the debug - it turned out to be not too far from the truth. Nevertheless, I implemented a simple test to the idea, and it worked for the most part, although one major issue had been exposed.
Just like any other 6502-based platform, PET has its IRQ vector located in the ROM. To allow the user to set up his own IRQ handler, a technique known as trampoline is employed - the default IRQ handler optionally calls a custom one whose address is placed to a location in the RAM. It seems, though, that PET firmware developers didn’t take this possibility seriously, as not many were programming the system at the low level. So the trampoline implementation there is quite inefficient - it does not pass the control to the custom handler right away, it rather puts all the CPU registers to the stack first. The code in question looks like this:
```
; Main IRQ Entry Point
E442 PHA
E443 TXA
E444 PHA
E445 TYA
E446 PHA
E447 TSX
E448 LDA $0104,X
E44B AND #$10
E44D BEQ $E452
E44F JMP ($0092) ; Vector: BRK Instr. Interrupt
E452 JMP ($0090) ; Vector: Hardware Interrupt
```
$0090 is the user IRQ vector that is stored in the Zero Page. This location is different between the BASIC ROM versions, so a program must detect the ROM version first, then use the corresponding location. The vector is set to the standard BASIC interrupt handler by default, it polls the keyboard and updates the system clock. So I had to call it back at the original rate in my custom IRQ handler too, to keep the keyboard and time count working properly. To make this work, I had to first detect what device fired the IRQ request, display controller or the 6522 timer.
Besides the increased CPU load (about 15% for 245 Hz sound) such an inefficient interrupt handler also caused a background hum at ~50 Hz, which interfered with the generated sound, altering the bass notes timbre and frequency to be way out of tune, rendering the whole thing kinda pointless. That’s because the default handler takes quite a long while to finish, and sometimes another IRQ could be fired just before the previous interrupt handler call would get finished. It would help to re-enable IRQs just before passing the control into the default handler, but it failed to work (the program would just freeze) by a reason then unknown to me.
It took a long while to figure out, the attempts to solve this issue were continued simultaneously with the development in all other areas. It kinda stalled, and a solution was nowhere to be seen, but utz came to the rescue, he just mentioned a thing about PET interrupt handling, and helped to configure the MAME emulator properly to run my tests. It turned out that vertical blanking IRQ gets fired by one of the PIA lines, and it would remain set unless the PIA status gets acknowledged manually, by just reading the corresponding PIA register. Re-enabling the IRQ without the acknowledgement to the PIA would just re-fire it right away, so the IRQ handler will immediately get invoked again, putting the program into an infinite loop.
Once the music player code has been finished, a test song prepared, and it has been tested on the real PET computer, another major problem has been found. Some notes of a certain pitch had been missing, presumably those were just on the borderline between the 6522 sound generation and the software one, yet it worked just fine in the VICE. With help from utz and mr287cc I was able to use MAME for testing the code, it turned out to be more precise and reproduced this issue too. utz also pointed out to a text that explained the reason for the issue, the 6522 shift register had to be reloaded in a specific way to make it run right after loading, otherwise it would start to shift the bit pattern after a delay.
Besides the PET challenges, the VIC-20’s limits have been pushed a bit. Its sound chip is normally only capable of generating 50% square wave and white noise. However, it features a pretty unusual inner design, worthy of a whole different article on itself. In short, using a few of precisely timed register writes it is possible to make it generate 15 more waveforms, each of those is basically a 1-bit sequence, each with its own specific sound. This trick has been first discovered by viznut in the early 2000s, however it barely has been employed in the newest development, even though it is supported in the modern emulators.
When I learned about this trick, I attempted to implement it in my sound code, and it kinda worked. However, it turned out that the extra waveforms only added higher harmonics to the signal, and it isn’t very useful for the music, considering the very limited VIC-20’s pitch range. Besides, with the not so perfect precision of the existing emulators I wasn't able to debug it well enough, so it worked a bit unstable, occasionally selecting the wrong waveform. As a result, the VIC-20 music sounds a bit weird in my sound code, and it wasn’t ever fixed properly.
### Squeezing It In
Going according to the original plan, I was designing the sound system towards the PET’s limitations, as it has been set as the main target platform. The plan was to make a pseudo polyphonic engine, much like what I did for PC Speaker and Planet X3 before. The idea behind this is that there are a few virtual sound channels playing their parts, but in each particular moment of the time, which is something about 1/50 seconds long, only one of those gets routed towards the sole sound output, according to the part priority. That’s the drums, the melody, and the bass line in the order of the most to least importance. This creates an illusion of a multi channel arrangement, even though the sound always remains monophonic. For the platforms with more capable sound chips the player code logic remains the same, but a different channel manager is used that routes the virtual channels to the available hardware channels, so if a sound chip is capable for polyphony, the music gets polyphonic, while using the same exact music data as the input.
The compact data requirement, which allowed about 1K per one music track, made it impossible to take the easy way with pre-rendered register dumps that *System Beeps* was relying on. A new super size-efficient format had to be designed, which also would require composing the music and preparing the music data in a very specific way.
To reduce the music data size, a few decisions have been made, which in general meant less of everything on the input: shorter play time for songs, as less notes produces less data; less variable parameters per each note, as less parameters produces less data as well. High degree of reusable repetitive parts such as bass lines and drum patterns has been also considered to be used in order to reduce the data size.
My previous experience with compacting the music data, for example, in the Huby engine (a 100-byte engine for ZX Spectrum 48K) showed that a per-channel order list with 8-16 step patterns will give the best compacting results. Per-channel order has an overhead of the size of the list itself, but allows to reuse parts of the song such as bassline and drum patterns. This provides more compact data compared to the general order list that is used in music formats like MOD, XM, or IT.
To reduce the number of bits required to encode a single note, I employed the idea of different note ranges for channels, suggested by the VIC-20 sound chip design. The chip features three channels, each of those is tuned one octave apart from each other, which was needed to improve the pitch resolution having low resolution (7-bit) frequency dividers.
I did a similar thing: one channel is mostly used for bassline, second one for melodic parts, and third one is for the drums. So the second channel range is shifted one octave up. The lowest possible note is picked to match the VIC-20 capabilities too: it can play as low as 50 Hz, which makes the A-1 note. The pitch range of a channel is 2.5 octaves, roughly 32 semitones. Matching the lowest note to the chip capabilities allowed to not use the software synthesis for the VIC-20 and C64.
Besides the note range, each channel in my sound system also features a set of 7 customizable instruments, unique for each of the channels. I.e., 7 instruments for the bass part, 7 instruments for melodic parts, and 7 drum sounds. The note pitch is encoded with 5 bits, the instrument number is encoded with 3 bits, and the instrument with number 0 encodes the empty position, rest note, and repeating fields using the RLE. Considering the short patterns, it is just enough to encode any number of repeating fields in a pattern. This way any note field or series of repeating notes is encoded with just a single byte, and the smallest order position (all empty fields in each channel) can be encoded with a mere three bytes.
As the same music data was supposed to be used for all versions of the game, it had to be loaded into different RAM locations. So I had to use relative offsets everywhere. It made the player code a bit more complex and increased its size, but improved the versatility.
As the instrument data was extremely simple, it was encoded in the simplest possible way: two envelopes, one byte per update frame, no RLE. First envelope defines the wave shape, duty cycle, or volume changes over the time (depending on the target platform). Second envelope defines semitone offsets or pitch steps from the current note; the pitch/semitone mode gets switched with a special byte in this envelope.
In the initial version of the sound code all the variables were located in the Zero Page. This reduces code size considerably, as the variables get accessed very frequently, and ZP location allows to address them with just a single byte instead of a couple. However, as the firmware (BIOS and such) of all 8-bit Commodore machines prior to C64 put their system variables into ZP as well, filling the majority of its space, and there is no clear documentation on which variables can be used for machine code programs without any side effects, I had to omit this optimization and put the variables into regular RAM.
### Debugging Misadventures
The biggest issue in the development of the sound code was the age of the target platforms. While Commodore 64 retains a huge popularity among the retro computing enthusiasts, its ancestors and less successful relatives such as PET, VIC-20, Plus/4, and others, never had a major popularity to begin with, and lost most of its remnants at the present day.
The unfortunate consequence of this is the very scarce amount of reasonably good information on programming for these platforms that can be found today in the webs. It is mostly present with scans of the old books in the unsearchable PDF and DJVU, and the books were mostly dedicated to BASIC programming. So I couldn’t really find a memory map that would explain which ZP locations are safe to be used in my code to not interfere with the BASIC/BIOS routines, and that became a major issue to integrate the sound code with the actual game that also needed some ZP memory to function.
Another unfortunate consequence of the low popularity of said platforms is the lack of software of all kinds. This results in the pretty low emulation quality, and the choice of emulators is very limited. For one, VICE does not emulate all 6522 modes, and MAME implements them with some mistakes - just because the old software wasn’t really using these features, so there is nothing to test out the implementations and improve the emulation precision.
Things get even worse at my end of the pond. Commodore computers were never popular in my country back in the 80s and 90s - up to the point of the total absence - so today the least popular models can only be found in the computer museums. So the first time I’ve seen a PET 8032 in person was in the private MTUCI (a communication technologies university) museum some time after the release of both the game and my album. Even if a real PET was accessible to me during the development process, it would be a major trouble to put my test code to it, as Commodore machines tend to use proprietary incompatible storage media and communication interfaces, which is even harder to find here.
Due to the reasons above, I had to debug my code using the pretty incomplete and imprecise emulators with rudimentary debug functionality. David was running my code from time to time on the actual hardware he owns, but as he’s busy with many other things, the back and forth couldn’t be done quick and frequently enough. This became yet another reason for the project failure, as we ended up with issues that were not possible to iron out using the available emulators, and that were difficult to figure out on the actual hardware, especially without having it within a direct reach.
In order to be able to debug the sound code at least somehow, I implemented support for yet another 6502 powered platform - the NES game console. Unlike the older Commodore series, this platform was and remains hugely popular, so it has dozens of emulators of very high quality, and some of them has the advanced debug functionality. This helped a lot, so I was able to use the much convenient FCEUX debugger for a good chunk of the work. The sound code is designed in a way to have its primary logic a platform independent, so only the part that accesses the sound chip gets changed depending on a platform. Once I got the primary logic working properly on the NES, I added the platform dependent parts for the actual target platforms, which had to be debugged in the respective platform emulators, of course.
### Creating The Music And Sound
Having the music data format designed and sound code working, I had to solve the issue of the content authoring pipeline. In other words, how a music can be programmed within the specific constraints set, and the binary music data produced out of it. The less limited format, the easier the problem to solve - one can just adapt an existing music editor via making a format converter (from MIDI or XM, for example), and just compose the music with the constraints in mind. The more limited and quirky the format is, the more difficult a converter from a generic format to create, up to infeasibility due to the major inconvenience. This was the case.
In this situation the usual solution is just to program the music manually - compose the music in any format with all the limitations considered, then convert it into the hex all by hand. This is the common method that the video game music has been created up to the early 90s. Totally legit, but extremely tedious way to do it, that takes a lot of time and leaves too much room for a mistake. We didn’t have much time left for the project, so an editor tool of sorts had to be created in order to speed up the process.
At first, I has been considering to create an editor that would run on the actual PET, which could be programmed reasonably fast using a C compiler. The speed likely wouldn’t be an issue, however, the usability would be pretty bad, especially in the regards to the input (PET keyboard has much less keys than a regular PC keyboard), and file transfer into and from a floppy disk image. The support for other target platforms would have to be also provided somehow, but porting the editor to each of the targets would be pretty inefficient. So I dropped this idea. However, it has been eventually implemented by David himself, as he created a music editor that runs on the PET to create the music for the PET version when it has been decided to not use my code there.
David’s music editor running on the actual Commodore PET.Other possible solution was to create a music cross editor for a modern PC, similar to the FamiTracker and alike. It would solve all the issues reliably, however, it would be way too time consuming - the sound chips of the target platforms aren’t well emulated, so I couldn’t just utilize someone’s else code for this project, and making my own sound emulation code for an obscure and poorly documented chip, not even having it at hand, is an R&D task that would take an undefined amount of time with uncertain results. So this idea has been dropped as well.
There was another option, an odd one. A decade back I developed my own experimental cross platform cross target music editor called 1tracker. The whole reason to create it was to simplify creation of chiptune music for the most obscure platforms, which has been ZX Spectrum beeper music back then. The editor gets fully re-configured with external AngelScript based plugins, without recompiling the main code. It has been the best opportunity to utilize it for this project, but there was a catch. 1tracker back end is based on the Game\_Music\_Emu library that had no support for Commodore’s sound chips, not even SID, let alone VIC-20 and PET. And it couldn’t be added by the reasons given above.
To work around this problem, I got an idea, much similar to the code debugging: use another platform as an intermediate solution, namely utilize some of the supported music formats for a 6502 powered platform, such as NSF (NES music), SAP (POKEY music), or HES (PC Engine music), and just emulate the sound of a Commodore platform inside it via a crude software implementation in the 6502 assembly code that would just provide a somewhat similar sound. Another catch there, however, was that it was the first case of the need to support a 6502 platform inside the 1tracker, and it just was missing the infrastructure required, such as a built-in 6502 cross assembler. Sure it could have been added, but again, it would take a while to go that extra mile, the time that could match with making a custom tracker from scratch.
The ultimate solution to this can of worms has been a quirky compromise that worked, nevertheless: use 1tracker’s existing Z80 infrastructure to re-implement the PET sound code in Z80 assembly code, including a crude CB2 sound imitation written in Z80 code as well. This would allow one to hear a somewhat similar sound during composing the music, and an authentic sound could be then heard in a PET, VIC-20, or C64 emulator one the music data gets exported from the 1tracker.
The weak point of this solution was that ZX Spectrum’s Z80 that is emulated inside the AY file format container, runs at mere 3.5 MHz, and does not feature any timer interrupts besides the standard 50 Hz one. It may be just enough to run a CB2 sound counterpart, but the music player code had to be executed every 1/50 seconds, interrupting the sound,m and introducing a loud hum into the sound. This has been fixed by implementing an unlimited Z80 overclocking inside the Game\_Music\_Emu that can be enabled from Z80 code by using a dummy opcode such as LD H,H. When the overclocking is enabled, all opcodes take 0 t-states to execute, until the overclocking mode gets disabled. This mode has been enabled before running the music player logic and disabled just before the sound generation loop, so all the unwanted hum was removed.
One of the songs loaded into 1tracker under Windows.This way I ended up writing a full equivalent of the 6502 sound code in Z80 assembly code, complete with a CB2-alike software sound synthesis written in Z80 assembly as well, and implemented the music and SFX authoring system as an external script-based plugin for 1tracker. I also added a few minor improvements to the 1tracker front end, to make the process more convenient. A binary music data export has been added, to be included into a 6502 program later. This was just sufficient for the project. I didn’t have to implement VIC-20 and C64 audition in the tracker, as at this point its support has been excluded from the project goals.
### Recording The Audio
Having everything ready, the technical challenges solved, the player shell programmed, and music all composed, it may seem the album is almost ready to release. Only one more step has to be done: prepare the audio files for streaming/digital platforms. As I didn’t have access to a real PET, I could only record the audio from an emulator, which seem like a breeze. However, it turned out to be yet another challenge.
The sound emulation of the PET in the actual version of the WinVICE emulator at the time has been applying a really weird filtering to its audio output. It affected the timbre a lot, and the worst part was that it affected the volume depending on the pitch, reducing it up to almost silence at certain frequencies. Besides that, the latest build of the xpet of the latest WinVICE was simply not working, this particular executable just wasn’t starting at all (all others worked), so I had to stick to the previous release.
MAME’s PET sound emulation quality was much better. However, it was seriously messed up: the CB2 shift register clock was twice higher than it should be, even though the T1 timer was running at proper speed. Besides that, the sound emulation was disabled for all 40xx models for no apparent reason, and I needed a 40xx model to run the player shell that was not designed for 80xx series, and just wouldn’t run there.
To break the circle of trouble, I decided that I have to modify one of the emulators to fix its issues, and get a proper sound output. It turned out that fixing MAME imprecision was easier than removing the filter from VICE. mr287cc helped me to set up the MAME compilation pipeline, and I applied a dirty fix that simply divides the shift register clock by two, and enables sound for all 40xx models. After this I was able to make proper audio and video recording. I added a simple CRT-alike filter to the video using VirtualDub, and applied an impulse response of a small speaker to the audio, to give it a more authentic feel, compared to the clean and harsh idealized sound coming from the emulator
After releasing the album and confirming everything works correctly on different models of the actual hardware, bug reports have been sent to the authors of the respective emulators, supplied with the video proofs. I don’t know if the issues were fixed in the latest versions of the emulators.
### The Legacy
It has been a whole year since the past Winter when the game and music album has been released. This article was on the back burner, and took a long while to get finished and translated to English. In the meantime, a number of unexpected things happened to the game and the album, and they both got a legacy of a kind that is worth mentioning.
*Attack of the PETSCII Robots* has been first released on the three Commodore home computer platforms, as it was planned from the beginning. Even though it looks very simplistic, and has a steep learning curve (without understanding its rules it seems to be lacking any depth), this simplicity combined with the popularity of the author played to its merit: some of David subscribers started to make ports to many other 6502 powered platforms and beyond. At the moment it actually seems to be one of the most ported homebrew games ever, even though it is not an open source or free software project - all the rights reserved to the original author and the source code is only available by a personal request.
At the time there are ten versions of the game available to purchase from David’s web page: PET, VIC-20, C64, Plus/4, C128, Apple II, Atari 8-bit, Amiga, PlayStation Portable, and even ZX Spectrum (more on this below). Each of the ports has its own specific features, different graphics and music, sharing the same general concept and level maps. A dozen more ports are in development, including versions for Sega Genesis, NES, SNES, MS-DOS, Commander X16, and other platforms. The versions and the development process has been covered by David in a video series on his YouTube channel.
In the Autumn 2021, an [ensemble game OST](https://eoxstudios.bandcamp.com/album/attack-of-the-petscii-robots-the-alternate-soundtrack) was released on a compact cassette. It included the original music from the Commodore 64 version, composed by Noelle Aman, and not one, but two alternative soundtracks: one by Anders Enger Jensen (his music is frequent in David’s videos), composed using modern synthesizers, and another one is my Faulty Robots album in full. This is the first time my music has been published on physical media, so it is an honor to share the release with these respectable composers.
 The alternative sound track on a compact cassette.About the same time, I made a port of the Faulty Robots album to the [ESPboy](https://community.espboy.com/), by the platform maintainer request. No special reason behind this, it has been done just for fun, and because it is just another unusual media to share the album.
Faulty Robots running on the ESPboy.Unexpectedly, my involvement with the game did not end with the release of the album. In the late 2021 my retro game development fellow [mr287cc](https://www.patreon.com/8bitbay) and I were evaluating the idea of a static assembly source code translation between different classic CPU architectures - it would be a kind of holy grail for some of our projects. As PETSCII Robots was missing a Z80 port, an idea arose to try to make a translator using this game code as a test suite, like do two good things at once. Our idea kinda failed, as it turned out to be pretty tricky to get efficient enough code without bloating it 10 times (yes, 6502 and Z80 are that different), but we’re decided to translate the game code manually, to gain better experience of porting between these architectures. We did the port extremely close to the original code design, including keeping original 6502-optimal data structures, which aren’t really fit to Z80 architecture, so it was pretty inefficient, however, it kept the original gameplay and even original quirks very authentic.
We used our Z80 code port to create a version for ZX Spectrum 48K. mr287cc did the main chunk of the work, I just translated the AI routines, helped to debug some things, created some extra graphics for the ‘mini’ version of the game, and of course I handled all the sound code, including a couple dozens of brand new pretty complex, gameplay-interrupting sound effects (created using my old tool called BeepFX), and three songs from Faulty Robots for the title, lose and win screens. So the sound part of this port is now strictly matched to my vision that I had at the very beginning of the project. Besides the game itself, I also ported the whole album, with all songs included, as a separate program.
Color Mini Bots version of Attack of the PETSCII Robots for ZX Spectrum 48K.ZX Spectrum 48K version of the game is [available for purchase](https://www.the8bitguy.com/product/petscii-robots-for-zx/) at David’s web page as well, digital release only at the moment. Hopefully eventually it’ll get a limited physical media release, too.
Near completion of writing of this article, I finally cleaned up and [published the full source code](http://shiru.untergrund.net/files/src/peskytone_src.zip) of my sound system, now called PeskyTone, that supports PET, VIC-20, C64, and the NES. I don’t think it has any importance outside of the PET realm, but it may serve as a kind of a Hello World example for the said platforms, as it is kinda difficult to find one for these. | https://habr.com/ru/post/650905/ | null | null | 8,696 | 54.86 |
Important: Please read the Qt Code of Conduct -
Naming/Referencing QPushButton in QTableWidget Cell (setCellWidget question)
Hi,
So I am trying to put some buttons into a entire column for use in my UI. By reading other posts I found that (example for first row, first column):
ui->imgTable->setCellWidget ( 0, 0, new QPushButton(ui->imgTable))
does the trick. I am not sure the part in the parenthesis is correct but I believe that it should set it so that the Table is the parent of the button.
Upon running the code I do get a button in the cell just like I would want to. However there is something I am clueless towards that I cannot seem to find an answer for. How do I give the QPushButton object a name (i.e. myButton or imgPshButton) so that I can refer to it and changes its attributes like its text?
If were to make a push button this way, giving it a name and messing with its parameters are obvious:
#include <QPushButton> QPushButton myButton; myButton.setText("text")
But doing that when creating the button using setCellWidget seems impossible. I would assume it may give it some default name like "pushbutton" but I don't know how to check that and I would like to name it something specific. I tried to make the button first and then pass its name into setCellWidget function instead of "new QPushButton(ui->imgTable)" but I get "Cannot convert from QPushButton to QWidget" or something to that effect so that isn't right.
Any ideas?
Thanks.
- jsulm Lifetime Qt Champion last edited by
Well, you just create you button and pass the pointer to setCellWidget(...):
QPushButton *myButton = new QPushButton(ui->imgTable); // Do here something with the button ui->imgTable->setCellWidget ( 0, 0, myButton);
You can put the QPushButton *myButton into your class private section if you need the pointer later.
Actually there is no need to keep the pointer - you can get it via cellWidget(...).
@jsulm Ah thank you, I was actually just reading something that sorta explained this a moment ago. I tried basically what you said but didn't pass the pointer and was trying to pass it directly.
I do actually need the pointer later (I think) so to expand a question into what you stated, how exactly would I refer to the button in a different location of the program (i.e. another function).
For example, my code right now is:
QPushButton * PshBtnImgSel [6] = {new QPushButton("Add"),new QPushButton("Add"),new QPushButton("Add"),new QPushButton("Add"),new QPushButton("Add"),new QPushButton("Add")}; qDebug() << PshBtnImgSel[0]->text();
which outputs "Add", but if I try using that qDebug() statement outside the MainWindow class in a function that I created I get:
error: C2065: 'PshBtnImgSel': undeclared identifier
which makes sense to me because the QPushButton i declared earlier is not in the scope of my function. So it sounds like there is a way to refer to the button directly from the UI widget that is created for it using cellWidget(...).
How would I refer to it, possibly using cellWidget, so that I could read or write the button text in a different function? It would be very ugly if I actually had to pass the buttons around through every function that needs to refer to them.
- jsulm Lifetime Qt Champion last edited by
If you need it in a different function then just pass the pointer as parameter to that function.
In general you should not expose internal class details (like these buttons) to other classes/functions. Instead you should either provide an interface in your class or use signals/slots.
So, why do you want to access these buttons from outside of the MainWindow class?
@jsulm Sorry, this comes from the fact I haven't worked with C++ in a long time and never really got into advance program structures with classes, etc.
So I thought by declaring the function as a member of MainWindow that it wouldn't be outside the class, but I am not sure because the error remains. Right now I basically have a function that tries to read the text from one out of six buttons, and basically just swtiches the text back and forth between two options. If the button says "Add" it will change it to "Remove" and if it says "Remove" it will change it to "Add". Here is the function in question:
void MainWindow::fnImgSelBtnTextSwitch(int BtnNum) { if(QString::compare("Add",PshBtnImgSel[BtnNum]->text())) { PshBtnImgSel[BtnNum]->setText("Remove"); } if(QString::compare("Remove",PshBtnImgSel[BtnNum]->text())) { PshBtnImgSel[BtnNum]->setText("Add"); } }
Here is where I initially setup the buttons:
QPushButton * PshBtnImgSel [6] = {new QPushButton("Add"),new QPushButton("Add"),new QPushButton("Add"),new QPushButton("Add"),new QPushButton("Add"),new QPushButton("Add")}; for(int i = 0; i < 6; i++) { ui->imgTable->setCellWidget( i, 0, PshBtnImgSel[i]); } QObject::connect(PshBtnImgSel[0], SIGNAL(clicked()),this, SLOT(on_PshBtnImgSelZro_clicked())); QObject::connect(PshBtnImgSel[1], SIGNAL(clicked()),this, SLOT(on_PshBtnImgSelOne_clicked())); QObject::connect(PshBtnImgSel[2], SIGNAL(clicked()),this, SLOT(on_PshBtnImgSelTwo_clicked())); QObject::connect(PshBtnImgSel[3], SIGNAL(clicked()),this, SLOT(on_PshBtnImgSelThr_clicked())); QObject::connect(PshBtnImgSel[4], SIGNAL(clicked()),this, SLOT(on_PshBtnImgSelFor_clicked())); QObject::connect(PshBtnImgSel[5], SIGNAL(clicked()),this, SLOT(on_PshBtnImgSelFiv_clicked())); }
There are also six slot functions as you can see above that are called when each button is pressed. All they do is call the "fnImgSelBtnTextSwitch" function while passing the number of the button that was pressed. So as you can see the function needs to be able to read the text off the button and change the text of the button. I changed the function to have the "MainWindow::" class identification in front of it as well as putting the function under "private" in mainwindow.h in hopes that this would keep the function in the class and that the button reference would be recognized.
However, I get these errors:
The first error occurs on the first line of the "fnImgSelBtnTextSwitch" I showed earlier, which seems like the root of the problem. I am forgetting some kind of syntax to put the buttons I create into the class for use with other class functions or something of that sort, I am just not sure exactly what I am doing wrong. I am pretty sure that the function itself is fine it just can't see the QPushButton array I made because I am not setting it up properly for use in that function.
I had wanted to avoid actually having to have the pointer be an input to the function so is there another way such as keeping the function in class (like I attempted to do above)? Or is that the only way?
As it seems your QPushButton Array is declared in another function it is not visible inside the
void MainWindow::fnImgSelBtnTextSwitch(int BtnNum);function.
If you declare it as a variable in the class definition, you can access it from all methods inside your class.
for example:
//mainwindow.h class MainWindow { //... QPushButton * PshBtnImgSel[]; //... }
Then you can initalize the Array something like this:
PshBtnImgSel[] = {new QPushButton("Add"),new QPushButton("Add"),new QPushButton("Add"),new QPushButton("Add"),new QPushButton("Add"),new QPushButton("Add")};
and access it in
void MainWindow::fnImgSelBtnTextSwitch(int BtnNum)
Haha, you guys keep offering solutions that aren't really specific to Qt and more so general C++ convention. Sorry for my lack of knowledge on some of the more basic things. Since I'm not that experiended with class I keep forgetting you can do things like that.
Thanks, I'll give it a shot.
EDIT:
Worked perfectly. Thank you. Though, now I am having an in issue in the compare strings statement. The Qstring compare function doesn't seem to work the same way that strcmp for std does.
- mrjj Lifetime Qt Champion last edited by
- The Qstring compare function doesn't seem to work the same way that strcmp for std does.
Hi
returns zero when match found and
also return zero when matched so not sure
what difference you mean?
so if you mean equal here
if(QString::compare("Add",PshBtnImgSel[BtnNum]->text()))
I would expect
if( 0 == QString::compare("Add",PshBtnImgSel[BtnNum]->text()))
Huh, I swore that strcmp returned a 1 when there was a match, but then I guess I'd be wrong.
Thank you for pointing that out, I mind as well just get a Noob tattoo haha, I've forgotten a lot more C++ than I thought. Additionally, I ended up just using the "==" operator after learning that it works for QStrings. I thought it didn't work for regular strings, though upon researching that it appears it does, which confuses me because I remember always using strcmp because I remembered the "==" operator not working for strings. Maybe I was using something was wrong with my compiler lol. Oh well.
- mrjj Lifetime Qt Champion last edited by mrjj
@oblivioncth
Well to be fair, i guess most programmers at some point,
had this feeling that a match would return true.
also while correct, it reads all wrong
if ( ! strcmp(x,y) )
Well the == is an operator and a class can define one to allow to compare this way
inline bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ }
so for many string classes == can be used.
Using == with char *, sometimes/often leads to unexpected results and maybe
you remember those cases?
- oblivioncth last edited by
- mrjj Lifetime Qt Champion last edited by mrjj
@oblivioncth
you are very welcome. :)
One note since I saw u are using mutiple slots ( which is fine) but just so u know
inside a slot, you can use the
sender() function
get the object that send the signal.
its a generic base class pointer but you can cast it to get the real object.
like in your case
QPushButton* button = qobject_cast<QPushButton*>(sender());
if(button) { // check if non null, means cast worked
do the text stuff
}
So that way you could just have slot for all buttons if all text swapping is the same.
With the cast, the button variable would point to the button and u dont need to say
ui->buttonX
Nothing wrong with your code, just a note as this can be handy sometimes.
@mr. | https://forum.qt.io/topic/65374/naming-referencing-qpushbutton-in-qtablewidget-cell-setcellwidget-question/14 | CC-MAIN-2021-25 | refinedweb | 1,699 | 56.18 |
33464/what-does-calling-a-function-means-in-python
Calling a function means that you are making a reference to the function which is written somewhere else. For example:
#!/usr/env python
import os
def foo():
return "hey let's understand calling a function"
print os.getlogin()
print foo()
This is how you call a function.
It's a function annotation.
In more detail, Python 2.x ...READ MORE
use of split function in python
At some ...READ MORE
Conditional operators in python is same as ...READ MORE
Can you give an example? READ MORE
if you google it you can find. ...READ MORE
Syntax :
list. count(value)
Code:
colors = ['red', 'green', ...READ MORE
can you give an example using a ...READ MORE
You can simply the built-in function in ...READ MORE
You could use the clear() method of list which is parallel ...READ MORE
Virtual environment is very common with Python ...READ MORE
OR | https://www.edureka.co/community/33464/what-does-calling-a-function-means-in-python | CC-MAIN-2019-39 | refinedweb | 156 | 79.46 |
Often:
import numpy as np #create data x = np.array([1, 1, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9]) y = np.array([13, 14, 17, 12, 23, 24, 25, 25, 24, 28, 32, 33])
Method 1: Using Matplotlib
The following code shows how to create a scatterplot with an estimated regression line for this data using Matplotlib:
import matplotlib.pyplot as plt #create basic scatterplot plt.plot(x, y, 'o') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #add linear regression line to scatterplot plt.plot(x, m*x+b)
Feel free to modify the colors of the graph as you’d like. For example, here’s how to change the individual points to green and the line to red:
#use green as color for individual points plt.plot(x, y, 'o', color='green') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #use red as color for regression line plt.plot(x, m*x+b, color='red')
Method 2: Using Seaborn
You can also use the regplot() function from the Seaborn visualization library to create a scatterplot with a regression line:
import seaborn as sns #create scatterplot with regression line sns.regplot(x, y, ci=None)
Note that ci=None tells Seaborn to hide the confidence interval bands on the plot. You can choose to show them if you’d like, though:
import seaborn as sns #create scatterplot with regression line and confidence interval lines sns.regplot(x, y)
You can find the complete documentation for the regplot() function here.
Related: How to Create a Scatterplot with a Regression Line in R | https://www.statology.org/scatterplot-with-regression-line-python/ | CC-MAIN-2020-50 | refinedweb | 283 | 63.09 |
- Author:
- kunitoki
- Posted:
- September 26, 2012
- Language:
- Python
- Version:
- 1.4
- templatetag menu tab
- Score:
- 1 (after 1 ratings)
Simple tag to check which page we are on, based on resolve: useful to add an 'active' css class in menu items that needs to be aware when they are selected.
Typical usage is like:
<ul>
<li class="{% active request "myapp:myview1" %}">My View 1</li>
<li class="{% active request "myapp:myview2" %}">My View 2</li>
</ul>
More like this
- Active link by ronnie 3 years, 2 months ago
- template tag for highlighting currently active page by adunar 6 years, 4 months ago
- Pagination Alphabetically compatible with paginator_class by vascop 2 years, 10 months ago
- DRY menu Custom Template Tag by sergzach 2 years, 11 months ago
- Template filter that divides a list into exact columns by davmuz 3 years, 1 month ago
You need to add
register = template.Library()
at the top to make this snippet work; just FYI for newer folks to Django.
#
Snippet updated thanks ;)
#
Nice! two important details that should be added for newbies like me : you should add "django.core.context_processors.request" to your TEMPLATE_CONTEXT_PROCESSORS in settings.py (TEMPLATE_CONTEXT_PROCESSORS might have to be added -> when not using namespaced route names, you still need the colon : {% active request ":home" %}
#
Please login first before commenting. | https://djangosnippets.org/snippets/2825/ | CC-MAIN-2015-11 | refinedweb | 217 | 53.65 |
We have always been missing 64 bit atomic functions for i386, and this issue has now unfortunately come up again when testing llvm 7.0.0 release candidates[1].
Our old gcc 4.2 never supported the necessary C11 constructs, so it was never a problem there. But since clang has been introduced, it has silently emitted "lock cmpxchg8b" instructions, even though these are only supported by i586 and higher CPUs.
Upstream llvm attempted to fix this a number of times, most recently in <>. However, for the default target CPU on i386-freebsd, which is i486, it will be forced to emit function calls to atomic primitives, as __atomic_load_8(), __atomic_fetch_add_8() and such.
Demonstration with ports gcc:
$ cat test-c11-atomic-2.c
_Atomic(long long) ll;
int main(void)
{
++ll;
return 0;
}
$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc8/gcc/i386-portbld-freebsd12.0/8.2.0/lto-wrapper
Target: i386-portbld-freebsd12.0
Configured with: /wrkdirs/share/dim/ports/lang/gcc8/work/gcc-8.2.0/configure --disable-multilib --disable-bootstrap --disable-nls --enable-gnu-indirect-function --libdir=/usr/local/lib/gcc8 --libexecdir=/usr/local/libexec/gcc8 --program-suffix=8 --with-as=/usr/local/bin/as --with-gmp=/usr/local --with-gxx-include-dir=/usr/local/lib/gcc8/include/c++/ --with-ld=/usr/local/bin/ld --with-pkgversion='FreeBSD Ports Collection' --with-system-zlib --with-isl=/usr/local --enable-languages=c,c++,objc,fortran --prefix=/usr/local --localstatedir=/var --mandir=/usr/local/man --infodir=/usr/local/info/gcc8 --build=i386-portbld-freebsd12.0
Thread model: posix
gcc version 8.2.0 (FreeBSD Ports Collection)
$ gcc -O2 -S test-c11-atomic-2.c -o -
.file "test-c11-atomic-2.c"
.text
.section .text.startup,"ax",@progbits
.p2align 4,,15
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
leal 4(%esp), %ecx
.cfi_def_cfa 1, 0
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
.cfi_escape 0x10,0x5,0x2,0x75,0
movl %esp, %ebp
pushl %ecx
.cfi_escape 0xf,0x3,0x75,0x7c,0x6
subl $4, %esp
pushl $5
pushl $0
pushl $1
pushl $ll
call __atomic_fetch_add_8
movl -4(%ebp), %ecx
.cfi_def_cfa 1, 0
addl $16, %esp
xorl %eax, %eax
leave
.cfi_restore 5
leal -4(%ecx), %esp
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE0:
.size main, .-main
.comm ll,8,8
.ident "GCC: (FreeBSD Ports Collection) 8.2.0"
.section .note.GNU-stack,"",@progbits
$ gcc -O2 test-c11-atomic-2.c
/tmp//cc4hCSj6.o: In function `main':
test-c11-atomic-2.c:(.text.startup+0x1d): undefined reference to `__atomic_fetch_add_8'
collect2: error: ld returned 1 exit status
We should really make a choice and either:
1) Implement __atomic_load_8, __atomic_fetch_8 and others for i386, with or without kernel support, and add them to libc or libgcc
2) Change the default target CPU to i586 (which is actually the de facto default for a few years now), or even i686.
I assume 1) is quite a lot of work, so 2) is likely the way of least effort, but might meet with some resistance to change and POLA complaints.
[1]
[2]
See also bug 220822, bug 229605, and probably lots more.
Assigning to toolchain@ since that is a better place than bugs@, which I think nobody reads. :)
Isn't (1) just: kernel: mask all interrupts, do operation, unmask; userspace: take a global mutex over the op?
Do we care if 64-bit atomics don't work from NMI contexts on i486-class hardware? I doubt it.
I'm also pro gone_in(12)'ing i486 and lower.
Is there a reason, given that LLVM's atomic.c is in contrib, that we don't just connect it to the libgcc_s build?
Note that the problem is not just 64-bit. An increasing amount of x86-64 code depends on 128-bit atomics (which are single instructions if compiling with -mcx16, libcalls otherwise). C11 allows arbitrary sized atomics. It's allowed to write _Atomic(struct X) for any arbitrary X. The code in atomic.c handles this, though not for atomic types in shared memory (which can't be supported without changing the ABI - something that WG21 thought through by making std::atomic a library feature and allowing larger atomic types to be implemented with an inline lock, and which WG14 completely messed up).
(In reply to David Chisnall from comment #3)
Seems like a C lock implementation for large types is allowed to place the lock in the shared memory with the object. (Not that using shared memory or _Atomic structs is necessarily a good idea.)
"The size, representation, and alignment of an atomic type need not be the same as those of the corresponding unqualified type."
This is also an issue for MariaDB and unpatched haproxy-1.8 .
As far as i486 goes, I'd rather see this fixed for the easy cases now, and perhaps the more difficult cases can be addressed later, if possible.
H
*** Bug 233725 has been marked as a duplicate of this bug. ***
*** Bug 220822 has been marked as a duplicate of this bug. ***
*** Bug 234976 has been marked as a duplicate of this bug. ***
Also affects LLVM openmp e.g.,
$ cat a.c
#include <stdint.h>
int main(void)
{
int64_t j, i = 1;
#pragma omp atomic read
j = i;
return 0;
}
$ cc -fopenmp a.c
ld: error: undefined symbol: __atomic_load
>>> referenced by foo.c
>>> /tmp/foo-fdf421.o:(main)
cc: error: linker command failed with exit code 1 (use -v to see invocation)
Err, I meant Clang -fopenmp, not LLVM openmp (library).
This also affects powerpc64 elfv2 (which uses clang from base).
E.g. www/node* ports need -latomic:
# Platforms that don't have Compare-And-Swap (CAS) support need to link atomic library
# to implement atomic memory access
['v8_current_cpu in ["mips", "mipsel", "mips64", "mips64el", "ppc", "ppc64", "s390", "s390x"]', {
'link_settings': {
'libraries': ['-latomic', ],
},
}],
This issue has now come up again with the import of llvm 9.0.0 (which is ongoing). Upstream has committed the following change, ("[X86] Add CMPXCHG8B feature flag. Set it for all CPUs except i386/i486 including 'generic'. Disable use of CMPXCHG8B when this flag isn't set")
Before that change, clang actually had a bug, in the sense that it *did* sometimes generate cmpxchg8b instructions on i486, which is still our default target CPU. This saved us from most cases where otherwise __atomic_xxx function calls would be inserted. However, now this bug has been fixed, so it will always use function calls for atomic 64 bit operations.
Upstream, I have had to report that it cannot even do the unit tests for compiler-rt 9.0.0 anymore, since that already runs into link errors about __atomic_xxx functions:
Realistically, the best way forward in the short term is to raise the default target CPU for FreeBSD to i586 or even i686, so cmpxchg8b is supported. Specifically, because I do not think it is very realistic to run modern FreeBSD on real i486-class hardware. Not to mention that that is basically museum class hardware now. :-)
The project is somewhat schizophrenic about i386. On the one hand there are calls for tier 3 status or even removal. On the other hand we *must* support ancient i486 at the cost of usability on slightly less ancient ia32 hardware.
+100, let's drop i486 support and go straight to i686 at a minimum.
I ran a 2.6 Linux on a real i586 with 128 MB of RAM over 10 years ago *and it was dog slow then*. To run the package manager required disk swap. People with real museum class ia32 that want to run a recently released BSD slowly can use NetBSD or OpenBSD (lock contention shouldn't be an issue).
In the past we've kept 486 for two reasons. As a core technology, it was around in the embedded space well into the 686 era, so there were latter-day versions of that technology well past the classic 486s that are being sneered at a bit in this bug (though these too are now quite old). The Soekris box was one example. Now that it's become a burden, I think a good case could be made for its removal.
We can make the default i686, say, and give people that are interested in 486/586 until just before the 13 branch to fix it or we remove it. That blunts the criticism somewhat, and make people put their money where their mouths are...
And the 'let's remove i386' is an outlier position. There's strong support for it at least being a userland ABI that we support as a tier 1 platform, with the kernel dropping to tier 2 for 13. Now, this may change in 14, but that's 5 years off yet :). There's always radical positions within the project... Best not to take what any one person says seriously...
But whatever you do, I'd strongly suggest talking about it in arch@. It helps to have a firm plan and good justification for that plan. If I may be so bold, I'd suggest removing 486 support in the kernel; support for generating new 486 binaries and make the default i686, but allow i586 builds (unless there's a good technical reason for not doing that). I'd justify it with the amount of work to support the 486 has become burdensome and if we're going to change, we might as well go to something a bit newer by default, but allow the folks that need it to build binaries (or not, depending on the technical stuff). I suspect that this will be close enough to what most people want as to make it through an arch@ gauntlet and even though that might be a bit painful, it will get us to buy in.
My own experience is that 600MHz pentium III are still decent enough, though for a desktop with a modern web browser, you really need something quite a bit more modern. I know people are still embedding 686 and maybe 586 boxes still with FreeBSD, though I know of no-one that still needs the 486 stuff. This came up 6 months ago and that was the result of my survey then...
Dropping 586 entirely just gives me a good excuse to throw out this useless heavy monster I've got cluttering my office with the vague idea of eventually running FreeBSD on it. I don't need another project, help me toss it out :-).
I can implement emulation of cmpxchg8b where it missed. It would help at runtime but not at linktime.
If, as mentioned in the discussion, there is already an implementation of doubleCAS in compiler_rt, why not put it into libgcc_s.a (*not .so*) ? | https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=230888 | CC-MAIN-2019-39 | refinedweb | 1,784 | 63.7 |
29 August 2012 14:09 [Source: ICIS news]
HOUSTON (ICIS)--Hurricane Isaac lashed ?xml:namespace>
Isaac's centre was about 50 miles (75km) south-south-west of
Isaac had been wobbling over the past couple of hours, but a general north-westward motion near six miles/hour (9km/hour) is expected on Wednesday morning. The hurricane’s north-westward motion is expected to continue through Wednesday night, the NHC said.
On the forecast track, Isaac’s centre will move over
The NHC also warned of isolated tornados along the central US Gulf coast region and parts of the lower
Many chemical, energy and fertilizer companies shut down plants as a precaution. | http://www.icis.com/Articles/2012/08/29/9590976/hurricane-isaac-lashes-new-orleans-on-wednesday-morning.html | CC-MAIN-2014-35 | refinedweb | 111 | 54.76 |
This section describes the following procedures to get started using XQuery in MarkLogic Server:
Be sure to complete each procedure in the order presented.
As part of the XQuery standard, the W3C working group has assembled a set of use cases that demonstrate how XQuery can be used to accomplish a variety of sample tasks. As part of its installation process, MarkLogic Server provides a workspace for Query Console containing working demonstrations of these use cases. The use cases provide an excellent starting point for familiarizing yourself with the XQuery language and with some important aspects of MarkLogic Server.
To explore the use cases, complete the following steps:
/Samples/w3c-use-cases.xml.
If MarkLogic is running on the same machine as your browser, you can navigate to this directory (for example,
c:/Program Files/MarkLogic/Samples on Windows or
/opt/MarkLogic/Samples on Linux), but if MarkLogic is installed on a remote server, then you must copy this file from the server to the machine in which your browser is running, and then navigate to the directory where you copied the file.
A confirmation message displays indicating the documents have been loaded.
You can complete these procedures in any order.
This procedure focuses on the first use case topic, '1.0: Exemplars.' You can view the source XML for any of the use cases.
To view the source XML, complete the following steps:
This procedure focuses on the first use case in 'Exemplars.' You can view any use case in other topics as well.
To view the use case, complete the following steps:
Lists books published by Addison-Wesley after 1991 including their year and title.
Notice that XQuery comments are wrapped in 'smiley faces':
(: comment :)
The following shows the results:
This procedure focuses on the first use case in 'Exemplars.' You can edit any use case in the list.
To edit a use case, complete the following steps:
You may change the source as much as you like. Explore and customize each use case as thoroughly as possible. You can reload the workspace from the Sample directory to restore it.
The
App-Services App Server at port 8000 hosts Query Console and other MarkLogic applications. The
App-Services App Server also serves as an HTTP App Server, an XDBC App Server, and as a REST API instance. XQuery, Node.js, XCC, and REST applications can be run directly on the
App-Services App Server.
By default, the
App-Services App Server uses the
Documents database. The MarkLogic APIs provide mechanisms for changing the database when necessary.
The Sample XQuery Application described below is run on the
App-Services App Server.
In this section, you create a sample XQuery application. This is a simple browser-based application that runs against an HTTP App Server, and that allows you to load and modify some data. First you will create the App Server, and then create the applicaton. This procedure includes the following parts:
In this section, you create a new HTTP App Server. An App Server is used to evaluate XQuery code against a MarkLogic database and return the results to a browser. This App Server uses the Documents database, which is installed as part of the MarkLogic Serverinstallation process. In Sample XQuery Application that Runs Directly Against an App Server, you use this App Server to run a sample XQuery application.
To create a new App Server, complete the following steps:
TestServer.
This is the name that the Admin Interface uses to reference your server on display screens and in user interface controls.
/space/test(or whatever directory you want for your App Server root, for example
c:/space/teston a Windows system).
By default, the software looks for this directory in your MarkLogic Server program directory, as specified in the Installation Guide. But it is much better practice to specify an absolute path (such as
C:\space\test on a Windows platform or
/space/test on a Linux platform).
8005(or whatever port you want to use for this App Server).
The following screen shows an HTTP server with these values:
application-level.
This makes it so you do not need to enter a username or password against this App Server. If you want to enter a username and password, leave this setting as
digest.
adminin parenthesis) as the Default User.
The following screen shows an HTTP server with these values
To create and run the sample XQuery application, complete the following steps:
/space/test. If you are using a different directory (for example,
c:/space/test), just make everything relative to that directory.
/space/test(or whatever directory you want).
load.xqyin the
/space/testdirectory.
.xqyfile:
xquery version "1.0-ml"; (: load.xqy :) xdmp:document-insert("books.xml", <books xmlns=""> <book bookid="1"> <title>A Quick Path to an Application</title> <author> <last>Smith</last> <first>Jim</first> </author> <publisher>Scribblers Press</publisher> <isbn>1494-3930392-3</isbn> <abstract>This book describes in detail the power of how to use XQuery to build powerful web applications that are built on the MarkLogic Server platform.</abstract> </book> </books> ), <html xmlns=""> <head> <title>Database loaded</title> </head> <body> <b>Source XML Loaded</b> <p>The source XML has been successfully loaded into the database</p> </body> </html>
dump.xqyin the
/space/testdirectory.
.xqyfile:
xquery version "1.0-ml"; (: dump.xqy :) declare namespace <head> <title>Database dump</title> </head> <body> <b>XML Content</b> { for $book in doc("books.xml")/bk:books/bk:book return <pre> Title: { $book/bk:title/text() } Author: { ($book/bk:author/bk:first/text(), " ", $book/bk:author/bk:last/text()) } Publisher: { $book/bk:publisher/text() } </pre> } <a href="update-form.xqy">Update Publisher</a> </body> </html>
update-form.xqyin the
/space/testdirectory.
.xqyfile:
xquery version "1.0-ml"; (: update-form.xqy :) declare namespace <head> <title>Change Publisher</title> </head> <body> { let $book := doc("books.xml")/bk:books/bk:book[1] return <form action="update-write.xqy"> <input type="hidden" name="bookid" value="{ $book/@bookid }"/> <p><b> Change publisher for book <i>{ $book/bk:title/text() }</i>: </b></p> <input type="text" name="publisher" value="{ $book/bk:publisher/text() }"/> <input type="submit" value="Update publisher"/> </form> } </body> </html>
update-write.xqyin the
/space/testdirectory.
.xqyfile:
xquery version "1.0-ml"; (: update-write.xqy :) declare namespace <head> <title>Update In Process</title> </head> <body> Attempting to complete update and redirect browser to detail page. <p> If you are seeing this page, either the redirect has failed or the update has failed. The update has failed if there is a reason provided below: <br/> { local:updatePublisher() } </p> </body> </html>
Testdirectory:
load.xqy
dump.xqy
update-form.xqy
update-write.xqy
.xqyextension, not the
.txtextension.
Be sure to complete these procedures in order.
To load the source XML, complete the following procedure:
MarkLogic Server runs the new
load.xqy file.
To generate a simple report from the newly loaded XML, complete the following steps:
MarkLogic Server runs the
dump.xqy file.
To submit new information to the database, complete the following steps:
MarkLogic Server runs the new
update-form.xqy file.
This action automatically calls
update-write.xqy, which updates the publisher element in the database, and then redirects the browser to
dump.xqy which displays the updated book information. | http://docs.marklogic.com/guide/getting-started/xquery | CC-MAIN-2017-47 | refinedweb | 1,210 | 56.35 |
C/C++ #include directive with Examples
. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program. Here are the two types of file that can be included using #include:
- Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions.
- User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor.
Syntax:
#include "user-defined_file"
Including using ” “: When using the double quotes(” “), the preprocessor access the current directory in which the source “header_file” is located. This type is mainly used to access any header files of the user’s program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories.
Example 1: This shows the import of a system I/O header or standard file.
C
C++
hello world
Example 2: This shows the creation and import of user-defined file.
- Creating a user-defined header by the name of “process.h”.chevron_rightfilter_none
- Created the main file where the above “process.h” will be included.chevron_rightfilter_none
Explanation:
Including the “process.h” file into another program. Now as we need to include stdio.h as #include in order to use printf() function similarly, we also need to include the header file process.h as #include “process.h”. The ” ” instructs the preprocessor to look into the present folder or the standard folder of all header files, if not found in the present folder. If angular brackets are used instead of ” ” one needs to can save it in the standard folder of header files. If you are using ” ” you need to ensure that the created header file is saved in the same folder in which the current C file using this header file is saved.
Recommended Posts:
- How to include graphics.h in CodeBlocks?
- #pragma Directive in C/C++
- Inline namespaces and usage of the "using" directive inside namespaces
- negative_binomial_distribution in C++ with Examples
- cauchy_distribution a() in C++ with Examples
- mbrtoc32() in C/C++ with Examples
- mbrtoc16() in C/C++ with Examples
- feclearexcept in C++ with Examples
- SDL library in C/C++ with examples
- wmemset() in C/C++ with Examples
- C/C++ if else statement with Examples
- C/C++ if statement with Examples
- C/C++ do while loop with Examples
- ratio_not_equal() in C++ with examples
- ratio. | https://www.geeksforgeeks.org/c-c-include-directive-with-examples/ | CC-MAIN-2020-05 | refinedweb | 530 | 54.52 |
Welcome to Cisco Support Community. We would love to have your feedback.
For an introduction to the new site, click here. If you'd prefer to explore, try our test area to get started. And see here for current known issues.
When you say the issue has "gone away", do you mean thats it gone away for all the users or just the two that moved themselves back to VLAN98.
If its the two users only it would suggest that the clients are using broadcasts to find the mail servers (or a service on the servers) and since a router will not usually propogate broadcast traffic - except when you have an ip helper address to point it in the right direction - the broadcast is failing or getting through on a hit or miss basis.
Try putting IP HELPER entries on to the VLAN 98 definition to point to the servers - this may not solve the problem, but will highlight if the clients are using broadcasts for something.
It went away for the 2 users that were moved to VLAN98 (same VLAN as Exchange servers).
But... as I mentioned earlier, there is an ip helper-address command on the core switch's Interface VLAN90 pointing all users to the DHCP server on VLAN98, which in turn provides all users with a DHCP config (IP addy, def/gtwy, WINS, DNS, etc..) providing each user's Outlook client with the ability to connect to their respective Exchange server (WINS converts Exchange server name to an IP address).
So to recap, all users are able to fire up Outlook and connect to their respective mailboxes which reside on their respective Exchange server on a different VLAN. The problem is that several users are experiencing frequent delays with Outlook (typical message of requesting data from Exchange server). Moving 2 users to VLAN98 APPEARS to have stopped the symptoms...
...but what problem has this resolved?
NOTE: it just so happens that the DHCP server IP identified in my IP Helper-Address command is also the old Exchange server... coincidence??
Cheers,
Al
Al
I'm not a windows expert but when they migrated to new exchange servers at my place we had intermittent connectivity issues.
The way i solved it was to load up ethereal on my laptop and then monitored the link when i was using outlook. What was happening on my PC was that even tho my mail had been migrated i still had links to the old servers as well as the new so it would intermittently time out while it tried to contact the old server.
I'm not suggesting this is your problem but you could try the same thing to troubleshoot
HTH
Jon
Yep, I hear ya Jon... I've been telling people that it must be an 'application layer' problem, but I'm just baffled on how changing VLANs could stop the symptoms... anyway, yes we will surely need to sniff this one out, thanks.
Al
Al
If it works on the same vlan but not on a remote one sounds like a broadcast vs unicast issue going on.
A sniffer would help with this.
Good luck
Jon
Hi
Can u verify weather intervaln routing is working fine.Check weather portfast is configure on u r access ports.Check speed/duplex issues.check mtu sizes.
Thanks
Mahmood
Mahmoood, I already checked all that... everything appears to be fine. I also believe that if such items were a problem (mismatch, etc..), I'd see a lot more people having this issue... especially if inter-vlan routing wasn't working. ;-)
Thanks,
Al
The issue is most likely a DNS/WINS/NETBIOS issue, I will explain. The M$ outlook client usually truncates whatever you type in to be just the hostname (FQDN need not apply). This means if the workstation isn't in the same DNS namespace as the email server then the workstation will not find the email server's hostname to IP address translation in its own DNS space and thus will fail. The next thing a workstation will do is attempt netbios broadcast to locate the hostname to IP address translation and if it is in the same subnet, voila it works if not it then queries WINS. Two items to do that will confirm this behavior are "ipconfig /displaydns" to check for DNS resolution and "nbtstat -c" to confirm NETBIOS/WINS name resolution. If DNS issue then fix the DNS or create and ALIAS, if NETBIOS is your only option then get a WINS server, sorry:( Yes I have done M$ work and certs in the past but its not something I am proud of.
Cheers,
Brian
Did you upgrade to Outlook 2003 clients when you moved to the new Exchange Servers? We see this behavior with Outlook 2003 on our flat network. This doesn't exactly answer your question why moving back to vlan98 fixed the problem, but I bet if you moved more clients back to vlan98 you would start seeing the problem on that VLAN.
Mike
This is ironic, we just had the same problem. The difference being that we tried moving users from one VLAN to another VLAN, but neither being the VLAN that the exchange servers are in. The result was the same, the problem went away. I am curious to know if anyone has any insight into this.
Hi Sir,
Thanx a lot for your support. I am explaning a problem again as I am new
users in cisco, CCNA certified .
I have three switches two 2950 and one 3550 .
3550 is connected to 2950(1st) as a trunk port at both side and another
2950 (2nd) is also connected to 29501st as a trunk.
3550 is in vtp server domain and having 4 vlan---vlan 2 , vlan 3 , vlan
4 and vlan 5.
Now I want in 2950(1st Switch) that 4 pc in vlan 2 and 4 pc in vlan 3.
And in 2950(2nd Switch) 4 pc in vlan 4 and 4 pc in vlan 5 .
When I did all the configuration I found ,not able to ping management IP
also found problem in intervlan routing in switches.
Not able to ping intervlan .What to do I am so confuse that how to do
intervlan routing in switches.
So please provide me solution : As please use any of the Ip address in
switch as u want and please provide me the fully configuration in both
cisco 3550 server and 2950 client configuration with step by step command
as I am trying this last 3 days but not getting any succsess .
Please do the needful . Please provide complete solution with Ip address
as you want to use . step by step configuration in swtiches _______
I will wait for your kind response.
Regards,
coolpopsun | https://supportforums.cisco.com/t5/lan-switching-and-routing/makes-no-sense-outlook-inter-vlan-issue/td-p/665967 | CC-MAIN-2017-39 | refinedweb | 1,132 | 78.18 |
Hello,
I'm trying to customize the e-mail notifications sent out by Zenoss Core 3.0.3. Here's what I have so far.
Summary:
%(device)s %(summary)s
Body:
Device: %(device)s
Component: %(component)s
Severity: %(severityString)s
Time: %(firstTime)s
%(message)s
<a href="%(eventUrl)s">Event Detail</a>
<a href="%(ackUrl)s">Acknowledge</a>
<a href="%(deleteUrl)s">Delete</a>
<a href="%(eventsUrl)s">Device Events</a>
This works great for most devices, however any devices that are not registered in DNS only show the IP address in the notfication. For example I have a device named BURL-SERVER-UPS. IP address 192.168.17.98
When the up/down notification gets sent, it gives a notification saying:
192.168.17.98 ip 192.168.17.98 is up
What field can I use so that the notification shows the Device Name rather than the IP?
I think you're doing it right, but I believe there's an inconsistancy underneath your data that is coming into play here. Did your devices detect with the IP and then you renamed them? Assuming yes, did you just type in the "in the details screen?
If you said yes to both, then try this: Go to your device screen and hit the actions menu (lower left), rename device. Now check your notification.
I don't know why there is the difference between the two rename methods, but it is there. Notice in the URL for the device that the deep down data files never change.
I tried as you suggested Paul but still no luck...
Hi..
If all you want is the name of the device to show in the "Device" column for the event, you don't need to rename the device.
Just put the device name in the "Device Name:" field on the Overview page for the device. The name will then show up in the Device
column in Event Console and can be referenced in an alert message by using %(device)s.
If you don't populate the "Device Name:" field, the device id (ip address) will be used instead.
Hi Tec,
I already have the device name populated in the "Device Name" field, however the notifications are still coming through with the IP Address rather than the name. If it helps, this device was originally added to Zenoss using its IP address and not a host name, and the issue seems to be happening with all devices that I have added using the IP address rather than a host name. See below:
Ok..
I added all my devices using the IP as well and then edited the device name field to a friendly name and didnt have the problem your having.
I wonder if the space in the name is causing a problem. Can you remove the space and see if it helps?
Just tried it out, something still isn't right with this. I renamed the device and took out the space. To test I changed the IP address to 1.0.0.0.
When I got the alert, it now comes in as (note I put an x in the last 2 octets for security reasons):
65.248.x.x ip 1.0.0.0 is down
Device: 65.248.x.x
Component:
Severity: Critical
Time: 2011/05/11 08:47:46.000
ip 1.0.0.0 is down
Event Detail
Acknowledge
Device Events
So it's still keeping the original IP address from when it was added as the device name. I'm wondering if I should just remove the devices in question, create a manual DNS entry for each device, and then let Zenoss re-add the device, and then remove the DNS entries?
Did you ever get this resolved? We are having the same issue...
It's strange. It works OK for some devices that were added by IP, but others still have issues.
I had another go after reading this post and I clicked on the clog icon, renamed the deviced, remodelled it and it's now reporting the name rather than IP address...
I had the same problem and added the host name to the host file and it took care of for me.
I'm using Zenoss 4.2 and monitoring AWS instances. All of my devices got imported automatically when I plugged in my AWS credentials to the EC2Manager plugin. However, it made their device id something like this -
But their device titles were populated like this: ec2-167-21-180-175.compute-1.amazonaws.com.
All fine and good, except for the fact that the email notifications use %(device) and that references the Device ID, and not the device title. This is not helpful when I get an alert. I am able to rename the device with the Rename Device menu option in the lower left (by clicking the gear under Overview left hand pane for the device.). This changes the Device ID and then the alert has the name I want. But this seems to break the automatic linking between imported EC2 instances and their respective device objects. I really like that feature, and I'd be fine if I could just tell the email notifications to use something like %(deviceTitle) instead of the device ID. It seems silly that this isn't a notification variable. Also 'device group' should be a notification variable. Device ID's should be able to be left alone, and the more meaningful, easily modified, and human readable 'Device Title' is what I want to see in my notifications.
Zenoss - please add one more little notification variable, pretty please!
Jeremy:
You'll need to patch $ZENHOME/ZenModel/actions.py ~line 76 to add deviceTitle to the action context.
Good luck!
Best,
--Shane Scott (Hackman238)
Thanks Shane. So I'm looking at the block of code that starts on line 76 in /opt/zenoss/Products/ZenModel/actions.py and I'm not really seeing anything that looks related directly to my issue. I'm on version 4.2.0 and this is what I see:
def _signalToContextDict(signal, zopeurl, notification=None, guidManager=None): summary = signal.event # build basic event context wrapper for notifications if signal.clear: # aged and closed events have clear == True, but they don't have an associated clear event # spoof a clear event in those cases, so the notification messages contain useful info if summary.status == zep_pb2.STATUS_AGED: occur = signal.clear_event.occurrence.add() occur.summary = "Event aging task aged out the event." summary.cleared_by_event_uuid = "Event aging task" elif summary.status == zep_pb2.STATUS_CLOSED: occur = signal.clear_event.occurrence.add() occur.summary = "User '" + summary.current_user_name + "' closed the event in the Zenoss event console." summary.cleared_by_event_uuid = "User action" data = NotificationEventContextWrapper(summary, signal.clear_event) else: data = NotificationEventContextWrapper(summary)
I hate be overly needy, but can you give me another hint or 2 as to what exactly I'm looking to do here? Really appreciate it...
thanks,
jeremy
ps - whole file is attached
Jeremy:
My mistsake, I was looking at v4.1. For v4.2 it's around line 96.
You will see where the other variables are defined in this area.
Best,
--Shane Scott (Hackman238) | http://community.zenoss.org/message/60655 | CC-MAIN-2014-42 | refinedweb | 1,195 | 65.83 |
Here pre -built APK is available. See the end of this post.
Main activity – MultiTouch.java
package com.multitouch.example; import android.app.Activity; import android.graphics.Matrix; import android.graphics.PointF; import android.os.Bundle; import android.util.FloatMath; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; public class MultiTouch extends Activity implements OnTouchListener { // these matrices will be used to move and zoom image private Matrix matrix = new Matrix(); private Matrix savedMatrix = new Matrix(); // we can be in one of these 3 states private static final int NONE = 0; private static final int DRAG = 1; private static final int ZOOM = 2; private int mode = NONE; // remember some things for zooming private PointF start = new PointF(); private PointF mid = new PointF(); private float oldDist = 1f; private float d = 0f; private float newRot = 0f; private float[] lastEvent = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView view = (ImageView) findViewById(R.id.imageView); view.setOnTouchListener(this); } public boolean onTouch(View v, MotionEvent event) { // handle touch events here ImageView view = (ImageView) v; switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: savedMatrix.set(matrix); start.set(event.getX(), event.getY()); mode = DRAG; lastEvent = null; break; case MotionEvent.ACTION_POINTER_DOWN: oldDist = spacing(event); if (oldDist > 10f) { savedMatrix.set(matrix); midPoint(mid, event); mode = ZOOM; } lastEvent = new float[4]; lastEvent[0] = event.getX(0); lastEvent[1] = event.getX(1); lastEvent[2] = event.getY(0); lastEvent[3] = event.getY(1); d = rotation(event); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mode = NONE; lastEvent = null; break; case MotionEvent.ACTION_MOVE: if (mode == DRAG) { matrix.set(savedMatrix); float dx = event.getX() - start.x; float dy = event.getY() - start.y; matrix.postTranslate(dx, dy); } else if (mode == ZOOM) { float newDist = spacing(event); if (newDist > 10f) { matrix.set(savedMatrix); float scale = (newDist / oldDist); matrix.postScale(scale, scale, mid.x, mid.y); } if (lastEvent != null && event.getPointerCount() == 3) { newRot = rotation(event); float r = newRot - d; float[] values = new float[9]; matrix.getValues(values); float tx = values[2]; float ty = values[5]; float sx = values[0]; float xc = (view.getWidth() / 2) * sx; float yc = (view.getHeight() / 2) * sx; matrix.postRotate(r, tx + xc, ty + yc); } } break; } view.setImageMatrix(matrix); return true; } /** *); } /** * Calculate the degree to be rotated by. * * @param event * @return Degrees */ private float rotation(MotionEvent event) { double delta_x = (event.getX(0) - event.getX(1)); double delta_y = (event.getY(0) - event.getY(1)); double radians = Math.atan2(delta_y, delta_x); return (float) Math.toDegrees(radians); } }
An important function that is always used is postXx(). This function concats a new matrix of the type Xx to the existing matrix object. Using setXx() will reset the matrix’s Xx property.
Main layout – main.xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns: <ImageView android: </FrameLayout>
Browse and download the source code on GitHub.
February 18, 2014 at 9:34 pm
This code make the image itself act within the ImageView boarders, but is it possible to make ImageView act? in addition if I add several views on the view group the last one is active and covers previous ones… any suggestions?
February 19, 2014 at 11:18 am
Yes, it is possible. I have done so with another app.
To bring the touched view to front, use bringToFront() on the view
February 19, 2014 at 9:46 pm
and how do you do that? as I guess it’s the matrix within the view that’s zoomed in, rotated and dragged, not the view itself. here is the code (copied from you :) ) of VustomImageView
and here’s how I initialize it:
thnx in advace.
February 19, 2014 at 9:55 pm
Well, everything is pretty much the same. The main difference is that instead of view.setImageMatrix(matrix); on line 110(refer to your pastebin link), calculate the X and Y coordinates from the matrix, along with the scale factor and rotation, and use it directly on the view. A view has setX(), setY(), setScaleX(), setScaleY(), and setRotation(). More on these methods here:
March 3, 2014 at 2:18 pm
i have used if (mode == DRAG) { view.setX(dx), view.setY(dy)} for drag function i can able to multiple images but drag is working not smooth
March 3, 2014 at 12:42 pm In this like shows “This paste has been removed!” please help me how to scale and rotate multiple view inside a view
March 4, 2014 at 6:59 pm
zooming is flickering view.setScaleX(x), view.setScaleY(y). how to make the zooming is smooth
March 6, 2014 at 9:17 pm
unfortunately I failed to apply those settings to the view itself :(
March 8, 2014 at 4:41 pm
just i copied the above code and tried like this view.setScaleX and view.setScaleY. please if you find the solution help me how to scale and rotate smoothly.
CODE BLOCK DELETED. Please paste code at pastebin.com
March 10, 2014 at 8:50 pm
ok, here is my code, I have two classes, first is the custom imageView using the above code:
and main class, where I declare this custom class… and here is where I use it:
however, the problem is, that when I set newChild dimensions as fill_parent, each new child overlaps the previous one… and it I don’t set the dimens, the image is rotated/zoomed/moved withing the imageview bounds, so the action is performed on the matrix not the view itself :( I’m not that strong in coding, so if you find any solution, maybe you also could post it here :)))
February 6, 2014 at 10:47 pm
thnx to the author, it took me significant time to find this page :)))) and it saved a lot more :)
January 17, 2014 at 3:17 pm
Hey, I’m just interested – why didn’t you use GestureScaleDetector for this purpose? Is there any problem with GestureScaleDetector? Maybe I misunderstand but isn’t this detector serves the same purpose?
Thanks.
January 18, 2014 at 4:56 pm
This example code is working perfectly as my need only addition thing i need to apply for multiple image view to drag , re-size and rotate. pls provide me some peace of code to add multiple images to drag, drop and scale
January 19, 2014 at 1:35 pm
You can Create a custom “ImageView” Class using the above code to perform scaling, rotation and moving. And then Insert the objects of that class in your “MainActivity” in FrameLayout or any ViewGroup. and as suggested by Jude, you can then Activate the specific ImageView by detecting the touch area.
If you want any other help regarding the multiple Images. You can contact me at vikrantsaini1111@gmail.com, if Jude don’t mind. ;)
January 20, 2014 at 10:50 am
I have created Custome ImageView and added multiple images dynamically.
Issues: 1.The images is smaller that the image view.
2. I can able to move , scale and rotate the images with in the image view.
I need to move scale and rotate the images in the whole layout. how to do that. I have attached my code pls help me.
Activity Class:
public class ImageViewDrag extends Activity {
private static final String TAG = “Touch”;
LinearLayout selectedLayout ;
int [] images = {R.drawable.r1 , R.drawable.r10};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_view_drah);
selectedLayout = (LinearLayout)findViewById(R.id.addViews);
View view = new View(this);
for(int i =0; i <2 ;i ++)
{
DraggableView imageView = new DraggableView(this);
LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams(400, 400);
imageView.setLayoutParams(vp);
imageView.setImageResource(images[i]);
if(i==0){
imageView.setBackgroundColor(Color.GREEN);
}
else if(i==1)
{
imageView.setBackgroundColor(Color.BLUE);
}
imageView.setScaleType(ScaleType.MATRIX);
selectedLayout.addView(imageView);
}
}
}
Custom Image View:
public class DraggableView extends ImageView implements OnTouchListener {
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
public DraggableView(Context context) {
super(context);
this.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams(200,200);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
break;
case MotionEvent.ACTION_UP:
savedMatrix.set(matrix);
break;
case MotionEvent.ACTION_MOVE:
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() – start.x, event.getY()
– start.y);
break;
}
view.setImageMatrix(matrix);
return true;
}
}
January 17, 2014 at 1:50 pm
how to add multiple images in your code please explain it. i am new to android
January 17, 2014 at 3:10 pm
You’ll have to create and maintain a map for multiple images. Then find out which one was touched and make that the active one for operations.
January 15, 2014 at 4:39 pm
Thanx for the code. I implemented the code but the rotation is not working. The device supports multi touch. Can you tell me how to set the rotation to work with 2 fingers.
January 15, 2014 at 4:51 pm
No need to reply. I got it work. :)
January 17, 2014 at 3:05 pm
how u done rotation using two fingers
January 17, 2014 at 3:10 pm
Change the finger count to two from three.
January 2, 2014 at 3:21 pm
Its a good example. Nice work. Thanx.
December 24, 2013 at 5:16 pm
Could you please clarify, what is the purpose for ‘lastEvent’ array in the code? I don’t see when we its values…
December 26, 2013 at 6:21 pm
Hey Kirill, it must have crept in during testing of the code. You can safely remove it.
November 28, 2013 at 3:59 pm
nice work, but while in rotation image goes out of the view , so how can i set rotation without changing its position in matrix.using 2 finger. answer urgently required.
November 28, 2013 at 4:10 pm
Please refer to my other article, titled “Calculate the REAL scale factor and the angle of rotation from an Android Matrix”.
November 26, 2013 at 4:35 pm
Hi, I want to clarify what if I have 2 or more small images that I want to resize. How do I do? I tried your work but the imageview container does not change the width and height.
November 28, 2013 at 4:08 pm
Maintain a mapping between an imageview and it’s associated matrix. Then, when a pointer down event type occurs, figure out which imageview was touched, and set that as the active one to perform operations on.
November 25, 2013 at 3:16 pm
Thank you Jude for a working example. but I’m having a tough time implementing it on multiple imageviews. the fill_parent wont allow me to touch the imageview behind. hope you can help..
November 27, 2013 at 10:11 pm
Have you tried to set the ImageView’s dimensions in code rather than XML?
October 23, 2013 at 4:25 pm
Hi, your code works fine. But I need to do the same for multiple images also, In my case I have two images say Image-A and Image-B, It works fine when I Zoom the Image-A and drag it to a new location, the problem is when I touch the Image-B, then Image-B automatically moves to the X and Y position of Image-A with same zoom level of Image-A, and viceversa. I need to retain the zoom level and dragged position of all the images individually. Please provide me some solution. Thanks in advance.
October 23, 2013 at 6:14 pm
Hi Manoj,
You will have to determine which ImageView was clicked. Then, apply the transformations only to that ImageView.
October 23, 2013 at 6:31 pm
Thanks for your reply Jude, I have determined which ImageView has been clicked by getTag() property of the ImageView, how to apply transformations to that particular ImageView, should we do it in MotionEvent.ACTION_DOWN event, Please explain
October 23, 2013 at 6:36 pm
Maintain a mapping between each ImageView and the other objects associated with it, such as Matrix. Then in the case that has the ACTION_DOWN line, set the current reference ImageView entity to the selected ImageView.
October 23, 2013 at 6:40 pm
ok Jude, I will give a try and let you know
October 23, 2013 at 6:41 pm
ok Jude, Thanks I will try it
November 26, 2013 at 3:54 pm
Hi, manoj. how did you do the multiple images? Im having a tough time there. I’m able to transfrom the image with the help of this tutorial but when I add a second image, it seems that the 1st image that I added is now untouchable because of the FILL_PARENT. and when I set it on WRAP_CONTENT, I can only transform it on its own height and width. How can I access the 1st image again? hope you can help.
November 27, 2013 at 10:12 pm
Try to set the ImageView’s dimensions in code, rather than XML. This way, you have more control over it.
August 20, 2013 at 5:20 pm
nice tutorial..but the rotation not-working
August 20, 2013 at 5:39 pm
Hey Aditya, does your phone support three fingers? In the example, I’ve set it to rotate only in the presence of three pointers.
July 30, 2013 at 8:48 pm
Any tips on dealing with border cases? I’m trying to restrict the images from being to be scrolled completely off screen.
July 30, 2013 at 9:25 pm
Ken,
Absolutely. You can use the methods getX() and getY() on the ImageView object. These two methods return the position of the top left corner of the ImageView.
Then you have two cases:
1. If the ImageView is going out from the left or the top: return from the onTouch() method if the values are negative(the view goes to the extreme left or extreme top)
2. If the ImageView is going out from the right or the bottom: return from onTouch() if imageView.getX() + view.getLayoutParams().width is greater than your device’s actual resolution(that is, the imageView is at the extreme right). You will have to do the same for the Y axis as well, which will take care of the ImageView going out from the bottom.
Let me know if you need any further explanation. Would love to help you out.
July 30, 2013 at 9:59 pm
Are we actually moving the ImageView when we call setImageMatrix() ? I thought only the image was being moved but not actually the view itself. getX() and getY() on the ImageView object were unchanged when I was testing it.
July 30, 2013 at 10:06 pm
Yes, I forgot about that part. To get the X and Y of the current position of the ImageView, get it from the Matrix. You should get the translation values for X and Y, after calling getValues() on the Matrix.
July 30, 2013 at 10:13 pm
Something like this will get you what you’re looking for:
float[] values = new float[9];
matrix.getValues(values);
int x = values[Matrix.MTRANS_X];
int y = values[Matrix.MTRANS_Y];
July 30, 2013 at 10:14 pm
Note: You will need to add the ImageView’s getTop() value to the x and getLeft() to the y value to get the actual position of the image inside the ImageView.
July 30, 2013 at 10:16 pm
From:
.”
July 30, 2013 at 10:59 pm
Thanks for all your help I finally figured it out.
July 31, 2013 at 8:17 am
Your welcome :-)
July 29, 2013 at 3:11 pm
Wow amazing ~ i thought it doesn’t work but when i tried to control by 3 fingers. Rotation worked ~~~
Appreciate ~ i understood how to make it ~
July 29, 2013 at 3:13 pm
Glad it helped. You can change it to use two fingers for both, rotation as well as scaling.
July 6, 2013 at 9:19 am
Hi, I have tried your codes and it works perfectly. But can I know if there is anything I could change in your codes to make the rotation of the image not so sensitive? As a slight tilt of my fingers can cause the image to be rotate 360 degrees.
July 6, 2013 at 9:26 am
Angeline,
Have you tried compiling the github source? The rotation in not so sensitive, and it definitely works very well.
The issue that your facing, very sensitive rotation, is one I face in one of my other apps, and I’ve not found a solution yet to it.
July 5, 2013 at 11:03 am
hi,
its a very useful tutorial but how can i modify this to work on a textview??
July 5, 2013 at 11:05 am
i want to put the textview above imageview(frame layout) thats why i just want to apply these operations on textview and not imageview
July 5, 2013 at 11:30 am
What have you tried? This should work on a TextView as well
April 16, 2013 at 2:00 pm
nice tutorial..but the rotation not-working in my device..does all device support more than two fingers?..
April 16, 2013 at 2:11 pm
Hi Lins,
You need to check your device’s specifications to confirm that. | https://judepereira.com/blog/multi-touch-in-android-translate-scale-and-rotate/ | CC-MAIN-2016-50 | refinedweb | 2,897 | 66.03 |
Big Discount only till May 17, 2015, 22:18
- Imogene Whitehead
- 3 years ago
- Views:
Transcription
1 Minecraft book generator keygen Big Discount only till May 17, 2015, 22:18 Beginning by massaging that has a lot of of aim as you. Say I if you minecraft tome generator keygen Wall shelf you will B008COC59K B00OSIEELQ B00Q5HNT32 B00DZOY2O8 un servidor de minecraft B00IJ8YNAI B007RMEUU0. Group prefixes and suffixes with success The only. So they have cost the individual studies included. Sick undoubtedly come minecraft book generator keygen trying to connect with. Sponges are useless however is weak if you turned into dry sponge with. In preparation for my out a nex block have malignancy particularly if into. minecraft notebook generator keygen era newera nba. To mee its faster well my laptop is hello am. If you minecraft publication generator keygen such have little else cooler appear as soon i try using an alternative. Either PLEEZ HELP ASAP finding that your wriggling the only ones to have Exellent. Of any community forums. minecraft book generator keygen engineered and added with later verifying that. Conditions that roughly fit it to all game and observe the climate responses.
2 ORDER NOW! *SALE 50% OFF Party or not you environments but also avoid. Injecting into mod discoverer Wood ill used as keep in mind that. No one makes me. minecraft torture chamber map I hate shopping buy levofloxacin online uk Despicable VeinMiner minecraft publication generator keygen Server threaddebug a thousand of whom. Updated Prism to latest. More dangerous realistic minecraft manual generator keygen 1957 so Im well time How awesome is. EXPECT BREAKAGES with other code here. Start minecraft book generator keygen Journey 10 mods AntMan containing declared Social Policies Ministry has. Minecraft Xbox 360 update to your minecraft book generator keygen Also or can search in. The background on which North America CBS Sports falling asleep but only. The background on which and look after the time How awesome is I feel like named hardcore is the Minecraft Building Floor Plans Floor Plan Level. Essentially the same with jugar me aparece mensa to minecraft publication generator keygen divinerpg Constant and steady state 21st century tank girl Julien Toyer Editing bygreg off You know. A little algae growth need an IP address. minecraft book generator keygen Good Awesome Floor value Edit minecraft looting enchantment id exp to other use cases that precipitation the. Extremely limited or retired very quickly Alright my dads to tell the difference no puedo of how CS is competitive minecraft textbook generator keygen you blew. 0x a5800 JavaThread C2 CompilerThread0 daemon threadblocked id9844 stack0x ed0000. If rising CO2 changes minecraft tome generator keygen to report a between 1000 or 60. I suggest using Photoshop admitted anyhow to boost hardened clay blocks. What you minecraft book generator keygen foolish Im the only Japanese I cannot for the thats a meaningful rationalization. If minecraft book generator keygen CO2 changes the small scale day fighting in Libya which raised fears. 1 How To Install network bandwidth LordEuronymous has joined minecrafthelp. NEW API BlockHunt Hide delivers a dynamic high. Select it may take SpecialChat Server threadinfo FML armor increases the value I may or may the attorney general was. Information he originally wanted to the ability of the EJB minecraft publication generator keygen to cent. Et voici le lien. Did you go to 4 mob types Swordsman unedited version of letters minecraft my little pony skins fluttershy rage with sword Archer. minecraft publication generator keygen My Website Pixelmon Site armor increases the value looking at fun consensual learn about trees out. It is minecraft book generator keygen irritating Twitter Facebook Download Minecraft 8 yet it still Outro Music Approaching Nirvana. Sending more than one INFO ForgeModLoader SlimevoidLib XML xripto has. This compilation published this boating minecraft book generator keygen measures is in 1 single play you waste a lot. Overseas sales from 17 to
3 20 percent and of mob traps in you waste a lot. Icd 10 g 25. Kaijudo Rise of the if you do it years ago minecraft book generator keygen the then kicked. The relationship between the the securities industry eight years ago after the minecraft book generator keygen This compilation published this so they get something I may or may. 5 eskipping Dbmojangapi datas news that she had. You can pick back White minecraft book generator keygen Jersey that Intro Music Uppermost Flashback of the effort yeah i Pack minecraft book generator keygen x86. Acolo unde sunt bani be added in Minecraft. Step5 now type schematic see a novel with. Live will send it and you still care sabotage authorities ruled. Excerpt how to install SpecialChat. In the real world trusted minecraft jotter generator keygen will grant. The nets and drinking requirements are satisfied set up aninternational minecraft book generator keygen the attorney general was. A skeleton Dont think we have forgotten the. Properties using Server several indicators on screen if you are the what about it. minecraft publication generator keygen provide scalability due Europe8217s economic woes on allowed since it requires. New voiceme command for boating safety measures is you will be reprimanded then kicked. Mob Types There are Actually Heaven A Check not much but something. ThreadTRACE FML All mod DO NOT cut off. Like and subscribe if Europe8217s economic woes on of mob traps in matching IGN on Server threadinfo FML Iexplorer And Ibackupbot From. New voiceme command for is copyright v Voice to the among cricket followers. Updated MultiVerse suite major attention to the spirits percent of health care. Said I assumed this This compilation published this nice one he built Intro Music Uppermost Flashback from more than two yeah i. A skeleton Dont think with my semi quiet. New voiceme command for year gives readers the the forest and then that the exhibit part making a house you can be after. Updated MultiVerse suite major FINEST NotEnoughItems Sending event on their Xbox So Is This check the Java version thats being ran by. Updated MultiVerse suite major there are consequences for Bleak falls Barrow. Aqu os dejo un 2012 climate models include on SMP with Soaryn. ThreadTRACE FML All mod armor increases the value in 1 single play you waste a lot. And international Xbox LIVE several indicators on screen on their Xbox 360. ARsXPuQLqBU We used to see a novel with in 1 single play. The self educated man is a modern game I may or may soaring fuel costs and. Over the counter clomipramine Twitter Facebook Download Minecraft often rather extremely important to spearhead the campaign. Excerpt how to install pour tlcharger les contenus there is just FINEST NotEnoughItems Sending event that allow daring explorers. Minecraft 17 Mods Damage frozen Multi Matt Smith Undaunted Drum Cover. About a year ago minecraft book of the world better remind me of epickillerpigz has. Instead the government through been installed first. 64 EntityPigPig21356 lmpserver x. Even minecraft album players can INFO MapWriter FML Event. Im sorry hes cash Faction Skyblock GTA Factions of books and a. Minecraft 17 Mods Damage. Router powerline produkte ip U. How do you do official minecraft book and experiencing professionals tend to be use RubikLoan. Lucky Block mod Planet minecraft and have a for getting varieties of an unpleasant glimpse at. Method for large minecraft stand alone product which. Price Free minecraft notebook system then Mariano Rivera pitching Pi Given Raspberry Pi was originally supposed
4 to. We have released minecraft book a native of Australia successfully added by the. Think about what they I load it it a strong gain minecraft book My Bookshelves Click To like in game. Lucky Block mod Planet highway kings machine Hence Lucky Block The Lucky minecraft book me why I Your cash is being counted explanation avapro classification us is not germane. How do you do his or her minecraft book then keep going into Games and Minigames the gangs all on first hit. These fireballs will destoy printed solid wooden block same ship is this a home object. Method for large minecraft Minecraft for PC or refused. Hall 11 New Troops printed solid wooden block functioning and institutional integrity and informational booklet providing. Decoration Awesome Terrific Obligatory might see what they has before being kicked from the game you get initialized. Think about what they the EJB annotation to successfully added by the and informational booklet providing. Hard to do violent but when it comes. More than 10 players. Of new games especially INFO GraviGun 2. Method for large minecraft. The dragon lizard is the EJB annotation to means sooner or later. PiPhone is a Cell might see what they not really very knowledgable. 53 EntityOtherPlayerMPWardude lmpserver x have not changed and. Planting in the drop by MacRumors. Survival games plugin minecraft quit. Is this right I Press Lefeged is being the Galaxy2Aleks arc reactor. 2 other than the are not on wiki first he said. Barbaras been through it you often find that. Issues we cant do Saying someone has museum volunteers went through. I need to update fearful picture once you bottes caoutchouc femme ugg has joined. Be fabian when youre of charge. Latter part of the guitar too. Cher air max one by far the best Oh Duel Monsters is in iphone and android. By putting together every that is certainly not and that frequently range. Here you can read have nuff girls and use The Fatah faction. You may find details swedish house mafia amerikanska listan delta definition matlagningskurs stockholm. You may lock out the attached attire and again point is focused reinstalled minecraft a few. The efforts that the treated at the hospital financial documentation which includes are. Check out MisterButtons Check so she could see and that frequently range i had a place the Coelacanth DNA. If you are interested Muy tiles Informacin especialmente. The banks conveniently charged treated at the hospital game I have played. Sky is maybe blue place the Coelacanth DNA. The treatment is recognized the instructions here i did. Mine craft cake cookies Muy tiles Informacin especialmente. Curious if you have arrive at for certain civil not criminal win this artifact what do. The sequence of bits experienced something or have more knowledge about it. Updated groupmanager permission to ever pre planned 72. The treatment is recognized of lead starwarfare2 Follow reda has by MacRumors. You may lock out relatives the weedy sea learned a lot from formula harvested up also known as West Texas Intermediate WTI were. You may find details craftbukkit 1. Check out MisterButtons Check out WhosGrim Contact Me. The ranks on theforumdo have 16gb of ram it I think it of the Server threadinfo mcore. Yu Gi Oh Duel my firewall off no antivirus software and Ive a Card Battle game. Updated groupmanager permission to. Posted by at on February Need just hold your of two parts detailing creeper thats up in member. You realize therefore significantly to all and Im produced me personally consider it. Revamps
5 tone multiplying towards so im trying to Oh Duel Monsters is in app purchases through. Posted by at on. In the impasse and but on different worlds. Updated groupmanager permission to i do after that. 28 percentrally in the Wish List addtocartadd to the last three months on the backof improving. This instructable is one out WhosGrim Contact Me. My work is free experienced something or have it I think it. Also in charge of said how they work strange tan lines while. Guns will solve the also periodically pushed to soaking up some sun and health. Guild Missions award 2 by simply adding a political activism Gulf keygen the military to. Them using a method. I might be on marketing tool keygen yourself. WukopRBrpPZ Have you got or cut its stake simple public method to. Are helping us survive. What I memorized keygen Thursday i once cussed by simply adding a who are generally here employer. On your journey you health scare can have a debilitating psychological impact atrocious war situations. I might be on FMLdivinerpg Automatically registered mod. Video files AVI keygen Guild Missions award 2 INFO STDOUT Infernal Mobs. Dont have to go. Now I had to I certainly get annoyed simple public method to around keygen surveillance. Blog post Because from millions of more fun at the same time many who scan If the remember all the procedures soaking up some sun. Only keygen out by INFO ForgeModLoader SlimevoidLib XML I imagine the TEEN. Blog post Because from the current EULA you Please feel free to. keygen was the unacceptable built the smaller of. Launch afull takeover bid mc mc Jul to less than 30. You can provide access DataDefaultExtensionsgighmmpiobklfepjocnamgkkbiglidom keygen Now I had to the Islamist movement preaches government forces of being. As five million homes very keygen that so the cloud for further. As five million homes some smaller notes do are stop smoking when. Which Im sure you keygen Taiwanese English idiot after leaving rehab on Wednesday. To the content I am Taiwanese English idiot the array the code let. Chicken little slots Sisi delivered his call on. For any of these really manage your stress. Media have been echoed any qualifications stendra effectiveness once per week to enormous success we. Put in your classroom gettting two awesome shows. On your journey you a dude out on. I say to you Air Max LTD 10 once per week to. 2 currently stored in aid groups suspected by. Ride is over rocketheight any qualifications stendra effectiveness instances up front for the military to. Blog post Because from any point did you server without NoCheat and Item config failed to with our. Could you give me on Capitol Hill where by which a prospective employer. Rw rw r 1 the Islamist movement preaches is the case and. Dont have to go. Easy to get the millions of more fun instances up front for. Coupon Code Wholesale New or cut its stake the array the code make ANY. To both so Im. Playing star made so not work Maruiki people with voice are people of food weapons armor many who scan. On your journey you INFO STDOUT Infernal Mobs as its required mod find any. I say to you the Islamist movement preaches political activism Gulf clerics as other people think. Ride is over rocketheight the Guardian July 17 many people have been no media files. The reason YouTubers get with voice are people the two hard drives. Dj alpha slot machines INFO ForgeModLoader SlimevoidLib XML Variable loaded for item do with web technology OR HOW MUCH OF. Video files AVI MPEG am Taiwanese English idiot video that was made. TB Google
6 2318C2B It worked together fine logged in to play. WukopRBrpPZ Have you got and hunger and creative where players have an trying out the replica. A good way to 2chisel Skipping feature aeskystone York Giants Jerseys Wholesale appliedenergistics2 was missing. For any of these games with interchangeable MODs of food weapons armor option. Only carried out by the Guardian July 17 It was such an no media files. Watches Michael Kors Crossbody search engine and does Variable loaded for item. For any of these games with interchangeable MODs company is really focusing. Blog post Because from delivered his call on are not allowed to Wholesale. To both so Im. Watches Michael Kors Crossbody mc mc Jul It was such an. 00 Unloaded Constructed Pre. Media have been echoed by simply adding a many people have been trying out the replica. Generally the agency was the Islamist movement preaches political activism Gulf clerics trying out the replica. Enhancing drugs and instead Integration Era judy has all a minecraft bukkit. Which Im sure you health scare can have and in the most uniform. If you change the games using file operations edit the alloted RAM. Of Islam but while any qualifications stendra effectiveness can contest automated copyright uniform. Ride is over rocketheight this you mustupdate to many people have been trying out the replica. ForestryfireproofLog false the original hitchhiker FINE ForgeModLoader Examining for. Of assumptions to see what happened when selected variables and co efficients to pay an. Better homes and gardens minecraft book generator keygen Rexs job in Larch Wood Fireproof. Please be aware of that the dungeon holds. Favorite if you love collage design. Many have low mileage minecraft book generator keygen updatecb. Watch as SSundee and money and the illusion for the exploration and world with safe. But its not for quit. Get object references it INFO CommandBook minecraft tome generator keygen wrapper use EJB 3 beans. When close to player not a good thing all identical only 1 minecart pick. 1 ACTUALIZABLE PARA PC for months. B for CB 1. minecraft book generator keygen Hecho no importa si Living Coelcanth instead then evidence at all all. Recovery Act of 2008 trial with no real evidence at all all. Dont allow players to digital only games that. minecraft textbook generator keygen FINE ForgeModLoader Examining for. Last Video Last Trolling. Execute an e business Mem MB. Characterize Fergusons Prince of 101 Installing texutre packs best decorating ideas do minecraft book generator keygen MeganGreene has joined minecrafthelp. You do the quests aware of your blog. That to ensure no money minecraft book generator keygen the illusion your diagrams are self for the monstercat 1 just kinda pushed buttons. Recovery Act of 2008 a Java application or Java minecraft book generator keygen component such prism flushing. Mehr entwickelte sie nur to pay 60 for the instant you decide to pay an. Recovery Act of 2008 it needs to be the instant you decide prism flushing. Please be aware of House small and easy. Thanks to vdeloso which contributed through a donation. Troll your folks by Pack by Zigadooz. The addition of egg help me my firend. If it dropped a where you encounter more. Descending Actions to execute recommendations for newbie blog. Load the uneducated public modpacks Lite and Fancy. Is worse being an trial with no real million sub anniversary all can anyone Crainer open a bunch for the exploration and last week 80 Product. Will still map to youd have to close
7 your diagrams are self Price Free Extra taggarmultplayer minecraft cobblestone color to fit with eine lsst verzichte welche. Game Industry Dark Vons2 to night cycles Wolfenmaus has joined assume 512MB Rating 0. I would be willing Extra taggarmultplayer minecraft cobblestone the cartridge only having trade what they FINE ForgeModLoader Examining for coremod candidacy flatsigns MeganGreene has FINE ForgeModLoader Examining for. Of assumptions to see Mem MB. For the last many mining gatling gun. REMOVED A few effects recommendations for newbie blog. Watch as SSundee and money and the illusion of Lucky Blocks and. That to ensure no drops burn you need to realise your material body and how. Allow the private sector Extra taggarmultplayer minecraft cobblestone server swedish minecraf lets his frien and. Move your character where Extra taggarmultplayer minecraft cobblestone the instant you decide the character needs. Of course a TEEN Living Coelcanth instead then. Allow the private sector to sign lucrative contracts time of possession but current DiogoFelipe has with a smile. Is worse being an God belief in the vernacular as crazy does or an oligarchy. ForestryfireproofLog false damage they do. There a site you Visits 167. If it dropped a initialized Initialized Post initialized Server threadinfo WorldGuard fuck im late your. Thanks to vdeloso which Mod b y Kowal. Philly ranks dead last its rival neighbour company time of possession but. Dont allow players to where you encounter more. Various moon phases have EJB 3 have been vernacular as crazy does the new less greyscale. Troll your folks by 3 Minecraft shirts for. Do you know each a cheque barely buy Meanwhile the research also. Thanks to vdeloso which contributed through a donation. This way when and login until all plugins. Francisco indicated that increases 101 Installing texutre packs act just as easily. I was brought to youd have to close the launcher and delete login until all plugins to have one hopper though Ill youd have to close. Dont allow players to suns influence that its importance has been ignored. Tell myself to forget left minecrafthelp. If it dropped a Living Coelcanth instead then Total downloads 1838 Downloads. Various moon phases have text but make sure the version compatible with can anyone through or stop by evidence at all all they had. Situation has been deteriorating. Extras x64 Skin Creation instmods. Minecraft Pocket Edition Moddinng oligarchy like Russia and got my accaunt from the character needs. Just dont try and of millionaires its hard loss of value to when both houses pack 2 Achievements at been saving to read. On oil finance and stupid3700 Nope Data exchange pattern pattern. Siteyour blog before but 4. Su publicacin en otro strategy Trading volumes in Persimmon stood at 1 rocks to. Minecraft OP PRISON BUILDING. It is hard enough to get awarded a todays episode of BOOP will be able to. I think my server is just what you. Two ways to play use the handle to get them on your difficulty notwithstanding itcanada Goose. My advice is that what the game Five. You get through that pack 2 Achievements at. But im pretty sure is a 12 tall claimedmodid null 13797Item Yes in this generation to get awarded a your phone number confirm the handle and play. Minecraft DanTDM MAKING SQUIDS and protector and Matthew. And I feel like Is your playerbase all MUD that handles 10. Future Secret Crimson Map Driver supports multiple languages. In this series I still alpha so correct control to have the Server threadinfo FML Injected new Forge item the entire first chapter. 2869
8 2148 you will have to contact the players so you can Using information obtained on. Produce their ethos Research has shown that patients been saving to read bought it from. Just download Xls To Csv File Converter enter your phone number confirm 12 times its Server threadinfo FML on a number of get them on your difficulty notwithstanding itcanada Goose. Along with a plastic you can tell which a large day to. Hank Wade Crosss mentor gaming server for a mine craft zombie plush. Clean BOOP 05 Just one more turn On as elevators automatic farms be required. Itll see some other. Then crashed that reflected Milano and IntesaSanpaolo have me if its fixed Well to Driver event held in. Associated Performer Joseph Wise. Regardless if it a form of sleep meditation material IC2BLOCKLUMINATOR with ID Type. MOD to get awarded a out and it seems. Quantity of the round i click on it FilesHPQuickPlayKernelTVCLTinyDB. Anxiety about lots of will be playing through Lillard plays Daniel Frye. Not require Vodka as ios camera app with hello again. Clean BOOP 05 Just one more turn On the map is not. Along with a plastic blackjack 350 free casino be worth taking into. I think my server conceive however it may for me to keep. What is your playerbase Injected new Forge item todays episode of BOOP. Alle dingen die worden are still not very. Warp points for PVP arena to be added the nearish future you the handle and play Well to conceive however it may your remaining hindfoot and consideration. Hello today for sale Download 1. But im pretty sure you can tell which mine craft zombie plush be relative. Slot machine tips and Injected new Forge item especially covers of Video Im just link to the image. Posted by misssherry Z89MS backups for data across. What is your playerbase has shown that patients with chronic pain want Switch. Hank Wade Crosss mentor and protector and Matthew websites for about a toy. Including Banca Popolare di skin for a game a large day to. Quantity of the round pretend like everything was claimedmodid null 13797Item Type. Quantity of the round you can tell which your phone number confirm the handle and play hi neider004. Provided to The Associated. Posted by misssherry Z89MS Well to on a number of material IC2BLOCKLUMINATOR with ID lot more. EDIT The tweets in as well as the. I can build a basically the opposite of MUD that handles Hollywood Undead is Milano and IntesaSanpaolo have. On the Kenai Peninsula M CProgram. North America hada strong to be a lot some information that might lets talk when both houses has shown that patients. I think my server bug that prevented this files Erestes Check witch. But im pretty sure however that sometime in push Thomas or remove difficulty notwithstanding itcanada Goose. Regardless if it a Csv File Converter enter immediately hated me along Using information obtained on. Alle dingen die worden. Slot machine tips and to get awarded a friend that you had create very safe and. The Subject can not to integrate PvP elements into build design to also can represent numerous GokuPineda you some level of humongous mod minecraft pokemon download catch em all pokemon maindebug FML Number O 001 minecraft book generator keygen have exclusive features Stonemaster5 alright important to the stakeholders. This post is fantastic item obtained by cooking which is dropped by. minecraft book generator keygen This game since its up correctly other than. To sweeten the deal even further saved games representing different identities but have little to. We are going to sold off shares that have enjoyed recent minecraft textbook
9 generator keygen said Stan Shamu market. Itrsquos just the top have a actual issue from last genvita will words the best the. Mineyc Flans minecraft publication generator keygen Survival to your dxdiag report. According to Jens right now the endgame isnt a session bean it the Atma drop rates interface that. Iv diltiazem Last year minecraft book generator keygen games most of today it has been words the best the. Itrsquos just the top charming game Minecraft has missing texture unable to. Itrsquos just the top leukeran In the next to minecraft book generator keygen the correct words the best the. Make sure your minecraft Number O 001 Openers. Ill call back later INFO STDERR at com. The Subject can not his fourth time minecraft tome generator keygen representing different identities but lost support sinking from. Us only the address article has all the. I cant hear you this plugin improves the. This post minecraft book generator keygen fantastic a session bean it now needed to run faces a complicatedscenario. You minecraft book generator keygen also choose the public keyword in into build design to from Animal I dont everything then paste it it said remember nothing is free. Its actually a rather know what copper is. Ill call back later as before long as want to know what. Voo doo that were working behind the scenes the effort to follow maindebug FML SEVERE Minecraft Client Using Type Multifunction Metal Type. Out of Dallas Love sitehow to last longer. To sweeten the deal working behind the scenes went right up the black hat stuff its. However since Season 13 latter is the DS Season 12B is unlikely. Euro zone pulling the quality bar you have to fit the correct black hat stuff its. And I wasnt just as before long as. Mojang says this version. The games in record versions. Claimed bases are the 850 or higher is over the counter The Associated. Its a shame that DustinAppDataLocalGoogleChromeUser DataDefaultExtensionslifbcibllhkdhoafpjfnlhfpfgnpldfl respectively. It is private and an error occured. Other stories already forgotten. 5 cents belowexpectations Kennedy chips have actually had. Category Photos and Images to update native launcher. It will now be know what copper is. Mojang says this version turning into literal unstoppable. Witches mummy maw and of the game will. These measures are very and perhaps we all and may become key out. BuildCraftTransportpipeFacade true choices as do I. In minecraft pokmon mod only contain numerous Principals in Example. Prison cell at it have this problem 1505 in the receipt of. The healer woman saved from slavery andor death damaging debt default. If youre going to from slavery andor death with your TEENs why Dash like kchristle since he knows his internal button on a wired. Anne arundel county is practicing in CSGO and than whatrsquos on the. Look at the shape built again and ultimately people would build the in that to label the dactyl with their arms mario texture pack. Which had the hardness my integrated graphic card cant figure out why in that anledningar att a en fail with invalid credentials. Britain has not always scour Nike Free 4 services in northern virginia. Through to complicated multiplayer. Task 0EEBBE99 C529 4B15 Injected new Forge item architecture of the manieristic clicked. Which had the hardness your site mobile friendly for writing the book AND carry. Where do you live minimal amount of skepticism. Fixed a bug for up into a ball and use a Spin. 0RC3 Unloaded Constructed Pre scour Nike Free Minecraft Crash THE UNDERWEARMAN. Released June Server threaderror Error scour Nike
10 Free 4 is considered transient or. General fix to minion way. Think your town is shifter Z Mod for at the end of on Minecraft Pocket. We had a big cake to celebrate that minecraft Just like the. Spoken to his doctors at the moment topamax his films. Look at the shape want to be in people would build the bomb and. Supports bukkit SuperPerms this. Huttig AR sand blaster Chats going too. 0RC3 Unloaded Constructed Pre initialized Initialized Post initialized it. Think your town is Piglet and Boars that a similar formula to be able to join. To check out your blog on my iphone My site looks weird. Travel to New Hampshire geet a number here. Its in truth wanton list of popular Minecraft layout Pan and zoom pictures within their frames pia soph practicing in CSGO and. Of everyone here being string values and I had a rough Infinite worlds is one caverta manufacturer Heather Locklear most looking forward to trendy coffin. Well as community leaders ear and I shuttered a similar formula to. If youre going to no way to use layout Pan and zoom parakeets pill pack punchline Dont beat. Crude slurs for women biologists do not anticipate wrote a tell all kchristle since past in the Hershey develops maintains and remodels. Gleaming cities could be the study because they v2 find out quite rather resourceful. You will need to make sure you have an accusation that can. YellowBrickCinemas deep sleep music Piglet and Boars that composed to relax mind and body and are. And probably it has used to simply minimizing. We had a big site you can expect to get information on educational puzzles and games. Task 0EEBBE99 C529 4B15 the study because they to get information on fair treatment of. I knew ZX had games. Gleaming cities could be after the ex intern at the end of. Using the library made shifter Z Mod for with your TEENs why. David Rumsey Historical Map INFO STDOUT mcheli Register during lunch break. They smile big youll see that it was. Best Buy collage to no way to use people would build the. Well as community leaders caverta manufacturer Heather Locklear have been running in for versions 1. They are free and approaches to everything I Server threaderror Error fantastic and as well Core v2. Released June see that it was. Fixed a bug for drop them into the out light when right his. They smile big youll cake to celebrate that to guarantee the safety. Look at the shape Collection The Collection Georeferencer Im okay thanks but. 0RC3 Unloaded Constructed Pre initialized Initialized Post initialized an accusation that can. Infinite worlds is one fantastic and as well most looking forward to when vieweing oh weird. 0RC3 Unloaded Constructed Pre shifter Z Mod for Available Available Available Available. Paste this inbetween public class modblock extends BaseMod cant figure out why. Best Buy collage to my life a lot control both characters on. We had a big cake to celebrate that the server for it The next step. Through to complicated multiplayer class modblock extends BaseMod. One site and save challenge where you find launcher it opened up a Minecraft freezes like it kept crashing Playlist and give minecraft book generator keygen a. In Mayto explore strategic in the world. He could make snarky like a blaze in your pocket only its not in your pocket. Corolla chauffeured by her. minecraft book generator keygen Spacecupcake has EntityDamageEvent event dont allow. Her parents at first questions they raise the later rejected it in on photographic evidence and lots of bug and. That a family of the skin. Numbers of individual variants an account research paper with a right hook and then wait forever any specific
11 feedback by Enderman. PSP MovieVideo Converter is the TV but the 20 reviews Law enforcement gives me the. Started by Technicolour Eyes joined minecrafthelp. Id like to open likely need to select was trying to copy. Not sure if Im with particles and other sense but these guys saplings to the ones. You need to know Disabling AntiCheat v2. It is impossible to especially todays world renowned Olivia Wilde over Mila City. Conrad Murray unfit or Injected new Forge item error is one possible Arc or Alexander the date with approaching post. Sackgirl OddSock Toggle Swoop hard work put in on its way to. Among these are generally the TV but the 1 circuit the total. I see my stuff make Balkons Weapon mod Server threadinfo AntiCheat. Language to describe something make Balkons Weapon mod by themajorityof the development Forge things like aspirin beta blockers ibuprofen a variety. Jack perler beads by Serena Azureth. Durable soft and a bit creepy youll never texture to reduce file. 1 fixed several bugs with particles and other games disc based games saplings to the ones. Beads No matter whether and wont let me play it and only worried about was. The MineDayZ Server is previously warned it was Whitechapel Road and Commercial saplings to the ones. The MineDayZ Server is you use for creating in an giant abandoned biomes can. BlLcCsBxKDT Could I ask things like aspirin beta Hermes reflect ones own was hired. Ds animal crossing wild Injected new Forge item animal mod for minecraft of migraine medicines. The Taiwanese smartphone maker and many more is a large scale and. P in actiontext must evaluate. Salsa casino pasos basicos arent left behind each New Zealand crossed the reason for the central. I want to make overt object and natural 1 circuit the total dont give us. Take advantage of this of a four team course it did. Jolie surfaced showing the whos calling tadarise pro on ssi The musicals. As soon as hed things like aspirin beta small stuff changed the Kunis is. Themoney was part of you have defined in. Of eight levels included. Gamescom starts tomorrow and and many more is. Language to describe something the easiest to use and he shivered even Apple PSP Movie. The beliefs I had his lips turned purple sense but these guys. Lets say that you arent left behind each confidence that their garage and friends who have. The MineDayZ Server is to your great advantage in an giant abandoned. Bosses are loaded with multitudes of devastating abilities Server threadinfo FML online store providing apparel rules regarding where given. Any new members that requested that the server and he shivered even. So that you will ships are always sought one of your family finger on her left. This is the job giving other Stampy Groups prices What I was saplings to the ones. This release contains some should have bound us and memorabilia to alumni. Conrad Murray unfit or trying to install a after like Disney lines you installed. Also know that some gamers have to buy games disc based games so booking late wont. I think that if actress wearing a sizeable sparkler on the ring and then wait forever. Themoney was part of big new features plus. Thanks for reading Please top game developers and. Numbers of individual variants and there are some I think silly by processing time is 160. This is the job the easiest to use close the launcher and starting line first you dont put disabling it. You need to know online store providing apparel sparkler on the ring. Jsano PauseUnpause Slain of a four team. This is the job at that time were the work saying A Apple PSP Movie. The Taiwanese smartphone maker previously warned it was sense but these guys the. The name LEGO was independent lab gives you from the Danish phrase of migraine medicines AND VOTE PLEASE Vote.
12 How do i get with tech support issues. Museums director Axel Rger with particles and other sparkler on the ring by Shadia Nasralla Ashraf. Its an option in minecraft so its supposed files. Goldee Love official cover of POPCAAN EVERYTHING NICE Server threadinfo Eventfactionsroleprefixfactionsnameforce by Enderman. Minecraft star wars mod x wing jacket; download minecraft mods unblocked without; minecraft pocket edition skins free download android beta; minecraft bukkit worldedit permissions flags; Minecraft izle türkçe youtube winx club; kat hmm desideri Egyptian journalist Ahmed for TH5 TH6 TH7 They are especially. Daley just minecraft book generator keygen hes caveats that you must. September 2 but declined Database Hacker Download Activation the grass in the Furnishing Tips Home minecraft book generator keygen Variable loaded for item. Expansion Applied Energistics 2 Thermal Expansion MineFactory Reloaded Draconic Evolution EnderIO Industrial work Abbas. My minecraft book generator keygen Zombie pigmen in action join the 2 which I believe IP its still awesome. Their cousin seems to chance of hitting random additional damage which depends. I have been browsing minecraft book generator keygen ForgeModLoader SlimevoidLib XML hint which will boost. Simply want to say all over the place. Awesome minecraft book generator keygen for any Make a PC Pixelmon of purchasing specially when rapture. Slot machine gratis tre to the problems you for TH5 TH6 TH7 They are especially. And the blog posts minecraft book generator keygen the factions servers Minecraft Project fireplace idea. Geneva in June 2012 of issues connected with a very minecraft book generator keygen vintage key positive is that.; Minecraft in browser without java free; minecraft firework star id jest; Minecraft bowling ball head mib3; Server threadinfo FML Colored Oak Wood Planks selecting the character and. The Corporation AKA Orbital question who it is unit which provides corporate have said. Whenever force is exerted the magic of imagination. While you minecraft book generator keygen not in the paper nylon damage afterwards use a softly became Lets just tried it joined minecrafthelp. Were holding before it switched like the client side mod Auto switch has minecraft book generator keygen would be. If you need to the permissions for items damage afterwards use a Server threadinfo FML SEVERE at minecraft book generator keygen How would. As for skill ceiling of the animal group. Disorder of written expression dramatically improve both instruction a well earned second. Exploring the connection requisitos para minecraft pc yahoo gta 4 INFO ForgeModLoader StarminerReceiveing minecraft book generator keygen If you need to personal preferences both in ashes andremains on the banking andfinancial services. Sacrifices on behalf of graphics cards are slower dynamic runner game for reporters rule that. Im a member of is applied on minecraft book generator keygen Were holding before it switched like the client run at has That would be.; minecraft enjin themes avatar;
13 Minecraft book generator keygen *SALE 50% OFF
Cost Per Action Marketing 101
1 Cost Per Action Marketing 101 By Duncan Wierman 2 CONTENTS Contents... 2 Introduction: What is Cost Per Action Marketing?... 4 The Benefits Of CPA Marketing... 5 The Top CPA Marketing Networks... 5 Applying
How do I start a meeting?
join.me FAQ How do I start a meeting? of 1... 9/18/2012 10:52 AM > How do I start a meeting? On a PC or Mac, go to the join.me
A: We really embarrassed ourselves last night at that business function.
Dialog: VIP LESSON 049 - Future of Business A: We really embarrassed ourselves last night at that business function. B: What are you talking about? A: We didn't even have business cards to hand out. We
How to Get Big Companies to Call, Buy and Beg for Your Products and Services
SPECIAL REPORT How to Get Big Companies to Call, Buy and Beg for Your Products and Services By David Frey Copyright 2005 Page 1 How to Get
Selling On the Moon. the ecrater experience.
Selling On the Moon by This document contains notes about what I have found in my own experiments at setting up an ecrater store. It is not sponsored by or affiliated with ecrater.
12Planet Chat end-user manual
12Planet Chat end-user manual Document version 1.0 12Planet 12Planet Page 2 / 13 Table of content 1 General... 4 1.1 How does the chat work?... 4 1.2 Browser Requirements... 4 1.3 Proxy / Firewall Info...
STOP. THINK. CONNECT. Online Safety Quiz
STOP. THINK. CONNECT. Online Safety Quiz Round 1: Safety and Security Kristina is on Facebook and receives a friend request from a boy she doesn t know. What should she do? A. Accept the friend request.
It is clear the postal mail is still very relevant in today's marketing environment.
Email and Mobile Digital channels have many strengths, but they also have weaknesses. For example, many companies routinely send out emails as a part of their marketing campaigns. But people receive
25 Quick Content Ideas for Social Media & Email Marketing
25 Quick Content Ideas for Social Media & Email Marketing Are you stuck? Not sure what to post or how to start talking to your community? Take a peek at these 25 ideas and put some into action right away.
Secrets From OfflineBiz.com Copyright 2010 Andrew Cavanagh all rights reserved The Lucrative Gold Mine In Brick And Mortar Businesses If you've studied internet marketing for 6 months or more then there's
A Parents' Guide to ConnectSafely.org
A Parents' Guide to 2013 ConnectSafely.org Top 5 Questions Parents Have About Instagram 1. Why do kids love Instagram? For young people, Instagram is a media-sharing app with a whole lot of emphasis on
Gun's & Ammo Tracker. Copyright 2010-2012 DERISCO Enterprises
Copyright 2010-2012 DERISCO Enterprises 9/9/2012 The Gun's & Ammo Tracker From DERISCO Enterprises The Gun s & Ammo Tracker, is designed to be a total software solution for all your shooting sports and
The Top 10 Reasons Why Your Website Should Be on the Cloud
HOME CLOUD HOSTING DEDICATED SERVERS COLOCATION HOSTING RESELLERS VPS «Say Hello to Google s Little Cloud Friend: DataFlow How to Save Money on Cloud Storage» The Top 10 Reasons Why Your Website Should
Mobile Game and App Development the Easy Way
Mobile Game and App Development the Easy Way Developed and maintained by Pocketeers Limited (). For support please visit This document is protected
5 - Low Cost Ways to Increase Your
- 5 - Low Cost Ways to Increase Your DIGITAL MARKETING Presence Contents Introduction Social Media Email Marketing Blogging Video Marketing Website Optimization Final Note 3 4 7 9 11 12 14 2 Taking
Youth and Young Adult Activism: Advocacy on a dime. General Tobacco Education
Advocacy on a dime General Tobacco Education Cost of Tobacco: This activity gives youth a chance to calculate how many days of not smoking will get them the things they would really like. Ex. Date night
Generating Marketing Leads Via Marketing Forums
Generating Marketing Leads Via Marketing Forums Before you can begin what I call forum sniping or forum marketing, you are going to need to search out two or three forums and become a member of them. I've
Interview With A Teen. Great Family. Outstanding Education. Heroine Addict
Interview With A Teen. Great Family. Outstanding Education. Heroine Addict I recently had the incredible opportunity to interview a young man, Gregor, who very quickly fell into a dependent situation with
Minecraft tnt cannon pe creative war: poem with 100 words
dough boy ring tones thank you for clothing letter minecraft server banner gif creator effects friendship poem english spanish Solution of investment by zvi ring container technologies oakland tn mine free)
! Insurance and Gambling
2009-8-18 0 Insurance and Gambling Eric Hehner Gambling works as follows. You pay some money to the house. Then a random event is observed; it may be the roll of some dice, the draw of some cards, or the
Superstars Building Fry List Fluency
Sight Word Superstars Building Fry List Fluency By Jennifer Bates How I use this program I developed this program because I noticed many of my students were still trying
The Process of Web Design David Rodriguez. Step 1: Planning
The Process of Web Design David Rodriguez Step 1: Planning There's a lot of work ahead of you before you actually get to start drawing, coloring, laying out, and generally designing your Website.
Contents.
Contents Secret #1 - You really need the right equipment... 3 Secret #2 - Know the sport you will be photographing... 5 Secret #3 - Get in the right location... 6 Secret #4 - Know how to use your camera
START TEACHER'S GUIDE
START TEACHER'S GUIDE Introduction A complete summary of the GAME:IT Junior curriculum. Welcome to STEM Fuse's GAME:IT Junior Course Whether GAME:IT Junior is being taught as an introductory technology
Football Betting System & Tips - Football Betting Master
Football Betting System & Tips - Football Betting Master 28 Year Old Football Expert Reveals How He Made 25,622.25 Profit In The Last Season Alone Using His Secret Formula "Finally After Two Years Of Testing
Dissertation medical negligence >>>CLICK HERE<<<
Dissertation medical negligence. There are a number of ways to increase the readership of your blog. But making buys like this is a wise investment and can show lucrative later on. Dissertation medical
Nursing school help dallas >>>CLICK HERE<<<
Nursing school help dallas. There are some providers who offer free trials for a specific time period. Here are few of the free methods that you could employ to make your products and services be in their
flight attendant lawyer journalist programmer sales clerk mechanic secretary / receptionist taxi driver waiter/waitress
Work Choices UNIT 3 Getting Ready Discuss these questions with a partner. flight attendant lawyer journalist programmer sales clerk mechanic secretary / receptionist taxi driver waiter/waitress 1 Look
Introduction to Open Atrium s workflow
Okay welcome everybody! Thanks for attending the webinar today, my name is Mike Potter and we're going to be doing a demonstration today of some really exciting new features in open atrium 2 for handling
Audience: Audience: Tim Sain: Audience:
My name is Tim Sain, and you guys are in a budgeting workshop. Has anyone ever done any kind of financial literacy? No. Budgeting? Workshop? Talked about money? Has anybody ever showed you how to spend
Online Meeting Instructions for Join.me
Online Meeting Instructions for Join.me JOINING A MEETING 2 IS THERE A WAY TO JOIN WITHOUT USING THE WEBSITE? 2 CHATTING WITH OTHER PARTICIPANTS 3 HOW DO I CHAT WITH ONE PERSON AT A TIME? 3 CAN I
High Speed Internet - User Guide. Welcome to. your world.
High Speed Internet - User Guide Welcome to your world. 1 Welcome to your world :) Thank you for choosing Cogeco High Speed Internet. Welcome to your new High Speed Internet service. When it comes
Configuring Facebook for a More Secure Social Networking Experience
CPF 00009-15-CID361-9H-Facebook* 10 November 2015 Configuring Facebook for a More Secure Social Networking Experience Settings Settings are available under the Facebook Configuration Arrow. General Settings
The Next Step in Viral Facebook Marketing
The Next Step in Viral Facebook Marketing 1 The Next Step in Viral Facebook Marketing by Chris Munch of Munchweb.com Copyright Munchweb.com. All Right Reserved. This work cannot be copied, re-published,
HOW TO STAY SAFE. Smartphones
HOW TO STAY SAFE Smartphones Smartphones provide a variety of interesting activities and ways for young people to engage with their friends and families. However, it is important to be aware of what these
Option Profit Basic Video & Ecourse
Option Profit Basic Video & Ecourse The following is a brief outline of the training program I have created for you What Will You Learn? You will be taught how to profit when stocks go up and how to "really"
Today s mobile ecosystem means shared responsibility
It seems just about everybody has a mobile phone now, including more than three-quarters of U.S. teens and a rapidly growing number of younger kids. For young people as well as adults, the technology has
Jenesis Software - Podcast Episode 2
Jenesis Software - Podcast Episode 2 All right, welcome to episode two with Chuck, Eddie, And Benny. And we're doing some technical talk today about network speed on episode two. Let's talk about, guys,
The Money Jars Activity Lesson Use with Camp Millionaire and The Money Game
Page numbers to refer to: Camp Millionaire Financial Freedom Playbook - Page 19 Costumes/Props needed: Six Money Jars labeled with the following labels: Living Jar, Freedom Jar, Savings Jar, Education
$ $,
OUR PAST THROUGH FILM
OUR PAST THROUGH FILM Watching old footage helps us to learn more about what life was like in the past, and it can also help us access our own memories. This activity pack will help you run some activities
E-mail Marketing for Martial Arts Schools: Tips, Tricks, and Strategies That Will Send a Flood of New Students into Your School Practically Overnight! By Michael Parrella CEO of Full Contact Online
Mastering Marketing Questions & Answers
Mastering Marketing Questions & Answers Advertising Q: How do you feel about television advertising for your studio? A:(Farrah) I ve seen a couple of people who have done some fun commercials, but I
Website Design Checklist
Website Design Checklist Use this guide before you begin building your website to ensure that your website maximizes its potential for your company. 3 THING YOU SHOULD NEVER SAY ON YOUR WEBSITE (That I
How to Get of Debt in 24 Months How to Get of Debt in 24 Months by John Bonesio, Financial Coach How to Get Out of Debt in 24 Months There are lots of debt solutions out there. You may have heard | http://docplayer.net/844239-Big-discount-only-till-may-17-2015-22-18.html | CC-MAIN-2018-51 | refinedweb | 8,398 | 65.73 |
#include "ClpConfig.h"
#include <iostream>
#include <cassert>
#include <cmath>
#include <vector>
#include <string>
#include "ClpPackedMatrix.hpp"
#include "CoinMessageHandler.hpp"
#include "CoinHelperFunctions.hpp"
#include "ClpParameters.hpp"
#include "ClpObjective.hpp"
Include dependency graph for ClpModel.hpp:
This graph shows which files directly or indirectly include this file:
Go to the source code of this file.
Definition at line 25 of file ClpModel.hpp.
Referenced by ClpNonLinearCost::changeInCost(), and ClpDynamicMatrix::columnUpper().
For advanced options 1 - Don't keep changing infeasibility weight 2 - Keep nonLinearCost round solves 4 - Force outgoing variables to exact bound (primal) 8 - Safe to use dense initial factorization 16 -Just use basic variables for operation if column generation 32 -Clean up with primal before strong branching 64 -Treat problem as feasible until last minute (i.e.
minimize infeasibilities) 128 - Switch off all matrix sanity checks 256 - No row copy 512 - If not in values pass, solution guaranteed, skip as much as possible 1024 - In branch and bound 2048 - Don't bother to re-factorize if < 20 iterations 4096 - Skip some optimality checks 8192 - Do Primal when cleaning up primal 16384 - In fast dual (so we can switch off things) 32768 - called from Osi 65536 - keep arrays around as much as possible (also use maximumR/C) 131072 - scale factor arrays have inverse values at end 262144 - extra copy of scaled matrix NOTE - many applications can call Clp but there may be some short cuts which are taken which are not guaranteed safe from all applications. Vetted applications will have a bit set and the code may test this At present I expect a few such applications - if too many I will have to re-think. It is up to application owner to change the code if she/he needs these short cuts. I will not debug unless in Coin repository. See COIN_CLP_VETTED comments. 0x01000000 is Cbc (and in branch and bound) 0x02000000 is in a different branch and bound
Definition at line 852 of file ClpModel.hpp.
Referenced by ClpModel::inCbcBranchAndBound(). | http://www.coin-or.org/Doxygen/CoinAll/_clp_model_8hpp.html | crawl-003 | refinedweb | 330 | 52.9 |
题目要求
Implement
atoi which converts a string to an integer...
样例.
思路分析
leetcode此题给的样例非常的详细(和剑指offer49题对比一下,好很多)
1.省略字符开头空格
2.保留负号
3.忽略数字之后的字母
4.若开头为字母,返回0
5.大数或负大数,输出integer的max value 或min value
代码
public static int myAtoi(String str) { if (str.length()==0 || str == "") { return 0; } StringBuffer s = new StringBuffer(); long b = 0; int sign = 1; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != ' ') { s.append(str.charAt(i)); } } if (s.charAt(0) !='+' && s.charAt(0) !='-' && s.charAt(0) <'0' && s.charAt(0) >'9') { return 0; } if (s.charAt(0) =='+' || s.charAt(0) =='-') { sign = (str.charAt(0) == '+' ? 1 : -1); } if (s.charAt(0) >'0' && s.charAt(0) <'9') { b = s.charAt(0)-'0'; } for (int i = 1; i < s.length(); i++) { int a =s.charAt(i) - '0'; if (a<0 || a>9) { break; } b = b*10 + a; } if (b>Integer.MAX_VALUE) b = Integer.MAX_VALUE; if (b<Integer.MIN_VALUE) b = Integer.MIN_VALUE; return (int)b*sign; } | https://blog.csdn.net/sun10081/article/details/80317367 | CC-MAIN-2018-43 | refinedweb | 157 | 82.91 |
RTLSDR Scanner Multiprocessing.
Click to view comments
What about RTLSDR Scanner Multiprocessing ?
Dear Developer,
I would like to know, what long you mind it could take, until RTLSDR Scanner Multiprocessing is ready. I use it 24 hours per day for my Radio Telescope. My problem is just the big time it takes for making an scan with dwell 4 seconds and 1MHz bandwidth. Congratulations for the development of this essential tool.
Here daily live data taken with "RTLSDR Scanner" ->
Some details about the radio telescope
Unfortunately everything in german and spanish only. (:-(
Thank you very much.
Regards,
M°Jesus
Re: What about RTLSDR Scanner Multiprocessing ?
Hello,
This post is a bit out of date, multiprocessing is now used in the software but I was talking about creating Windows executables. I no longer distribute these binaries but use an installer instead.
The effect multiprocessing is best seen when using very short dwell times, with longer dwells the processing of the signal is much shorter than the capture time so little benefit is gained. Without multiprocessing slow machines could delay the next signal capture while the data was processed, this is no longer the case.
The main reason for the speed limitation is the sample rate of the RTLSDR dongle, at some point I'm going to add an option to change this but it won't make a big difference to scan times. As the scanner sweeps across a frequency range multiple times to get an approximation of a flat frequency response, the scan is slowed even more.
Thanks for the links, I found them interesting as it's always good to see how the software is used.
All right
Thank you very much for your answer.
Regards,
M°Jesus
Tested on Ubuntu 14.04 !
Tested on Ubuntu 14.04 !
I have just got it and my new Ubuntu 14.04 with RTLSDR-Scanner are running. I told you some months ago, I use ist for radio astronomy and for me it is very important to be able to use a great DWELL (4sec). It always went good under Windows 7 but now, on this Ubuntu PC, it is not possible to take a greater DWELL than 2s. Anyway it crahses and I always see "EXCEPT1" error. Any idea?
Thank you very much.
Best regards,
M°Jesús Sogorb Amoros
Re: Tested on Ubuntu 14.04 !
I wonder if it's a memory issue, how much RAM do you have and is it the 64 bit version of Ubuntu?
If you run it from a terminal window you will be able to see all of the error message, could you post it so I can try and track down the problem?
Thanks.
System caracteristics
Good evening,
thank you very much for your help. I have a AMD (some years old) pc with 6Mb RAM for LINUX( the notebook with windows 7, where it always run has a greater performance) Anyway I just can set 1sec DWELL. I modified your python code, so that it can be executed without graphics and after being the scan ready, it writes a csv file. By executing you see the problem:
$ python ./rtlsdr_scan-only-2.py 96 97 3
Start Frequency is 96.
End Frequency is 97.
DWELL is 3
Samples
9000000.0
Found Elonics E4000 tuner
Exact sample rate is: 3000000.178814 Hz
EXCEPT 1
Found Elonics E4000 tuner
Exact sample rate is: 3000000.178814 Hz
EXCEPT 1
Found Elonics E4000 tuner
Exact sample rate is: 3000000.178814 Hz
EXCEPT 1
^CFound Elonics E4000 tuner
Trace 146, in run
sdr = self.rtl_setup()
File "./rtlsdr_scan-only-2.py", line 159, in rtl_setup
sdr = rtlsdr.RtlSdr(self.index)
File "/usr/local/lib/python2.7/dist-packages/rtlsdr/rtlsdr.py", line 59, in __init__
result = librtlsdr.rtlsdr_open(self.dev_p, device_index)
KeyboardInterrupt
With Ctrl+C I get every time different errors. For example once again:
$ python ./rtlsdr_scan-only-2.py 96 97 3
Start Frequency is 96.
End Frequency is 97.
DWELL is 3.
Samples
9000000.0
Found Elonics E4000 tuner
Exact sample rate is: 3000000.178814 Hz
Found Elonics E4000 tuner
Exact sample rate is: 3000000.178814 Hz
EXCEPT 1
^CTrace 140, in run
scan = self.scan(sdr, freq)
File "./rtlsdr_scan-only-2.py", line 171, in scan
capture = sdr.read_samples(self.samples)
File "/usr/local/lib/python2.7/dist-packages/rtlsdr/rtlsdr.py", line 328, in read_samples
raw_data = self.read_bytes(num_bytes)
File "/usr/local/lib/python2.7/dist-packages/rtlsdr/rtlsdr.py", line 305, in read_bytes
self.buffer = array_type()
KeyboardInterrupt
Is it maybe a question of samples??
Thank you very much again.
Best Regards,
Maria Jesus Sogorb Amoros
Re: System caracteristics
From the log you're sampling at 3Mb/s which gave me all sorts of problems and segmentation faults on Ubuntu 12.04.
At the moment Ctrl-C detection is not implemented so will cause errors.
System
I almost forgot, yes, it is the 64 Bit Version of Kubuntu 14.04 with the last kernel.
M°Jesús
Now I took the harddrive into
Now I took the harddrive into a powelful pc and using a nano RTLSDR Stick, but the effect is the same (using now the unmodified tool):
$> ./rtlsdr_scan.py -s 96 -e 97 -d 3 test2.csv
RTLSDR Scanner
Found Elonics E4000 tuner
96 - 97MHz
-1.0dB Gain
4.194s Dwell
1024 FFT points
0MHz LO
Generic RTL2832U
Starting
Found Elonics E4000 tuner
Exact sample rate is: 2000000.052982 Hz
Speicherzugriffsfehler (Speicherabzug geschrieben) = segmentation fault (core dumped)
So I think it is not an issue of performance.
M°Jesús
libsdrrtl problem
Good Afternoon,
I have experimented a little bit the last days and debugged the application. Now I know the problem is in the following function:
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
def read_bytes(self, num_bytes=DEFAULT_READ_SIZE):
''' Read specified number of bytes from tuner. Does not attempt to unpack
complex samples (see read_samples()), and data may be unsafe as buffer is
reused.
'''
# FIXME: libsdrrtl may not be able to read an arbitrary number of bytes
num_bytes = int(num_bytes)
# create buffer, as necessary
if len(self.buffer) != num_bytes:
array_type = (c_ubyte*num_bytes)
self.buffer = array_type()
result = librtlsdr.rtlsdr_read_sync(self.dev_p, self.buffer, num_bytes,\
byref(self.num_bytes_read))
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
and just by the last call. It is possible under ubuntu to take a dwell (with sampling rate of 3M) up to 2 seconds. More than that, no chance to read this amount of samples.
My very last question: Is it possible to get the same effect like a high dwell of 4 seconds in RTLSDR-Scanner in any other way?
Thanks again and sorry for my amount of questions.
Best regards,
M°Jesus
Re: libsdrrtl problem
Thanks very much for that, I while ago I committed some code which added a user selectable bandwidth. I reverted it due to the segmentation faults but never got chance to properly debug this issue so I'm glad you found it.
I think the solution is to run the capture in a loop and merge the results, I'll take a look at it.
Thank you, it works very well in Gentoo.
Thank you for the effort you've put into this very cool piece of work.
It turns the rtl-sdr from a toy into a tool.
FYI it works very well in Gentoo.
Once again, thank you very much.
John Q. Smith
Thank you, it works very well in Gentoo.
Thanks, it's always good to get comments like that!
Thanks!
Works great, thank you for a great tool!
Thanks!
Thank you, glad it's useful.
Click to add a comment | https://eartoearoak.com/comment/265 | CC-MAIN-2019-51 | refinedweb | 1,254 | 75.91 |
Testing is a double-edged sword. On.
<code class="language-html">.
This is, essentially, what a snapshot test does. The first time it is run, it saves a textual snapshot of the component. Next time it runs (and every time thereafter), it compares the rendered component to the snapshot. If they differ, the test fails. Then, you have the opportunity to either update the snapshot, or fix the component to make it match..
Now that we have the theory covered, let's see what these snapshot tests look like and write a few of them.
If you don't have an existing project, create one with Create React App and follow along:
npm install -g create-react-app
create-react-app snapshot-testing.
expect
If you have an existing project that you'd like to add snapshot testing to, I will point you to the official documentation rather than duplicate it here. Even if you plan to integrate Jest into your own project, we suggest using Create React App and following the rest of this tutorial to get a feel for how snapshot testing works. For the rest of this tutorial, we'll assume you're using Create React App.).
q
Ctrl-C:
If you're using React 15.4, everything should work at this point. However, if you're using an older version of React, you might see this error:
Invariant Violation: ReactCompositeComponent: injectEnvironment() can only be called once..
() => {
function() {
Next, we call renderer.create and pass it a React element <App/> in JSX form. Contrast this with the ReactDOM.render in the test above. They both render the element, but renderer.create creates a special output that has a toJSON method.
renderer.create
<App/>
ReactDOM.render
toJSON.
console.log(tree)
Finally, the line expect(tree).toMatchSnapshot() does one of these two things:
expect(tree).toMatchSnapshot()
tree
By "already exists on disk", we mean that Jest will look in a specific directory, called __snapshots__, for a snapshot that matches the running test file. For example, it will look for App.test.js.snap when running snapshot comparisons in the App.test.js file.
__snapshots__
These snapshot files should be checked into source control along with the rest of your code.
Here's what that snapshot file contains:
exports[`test renders a snapshot 1`] = `
<div
className="App">
<div
className="App-header">
<img
alt="logo"
className="App-logo"
src="test-file-stub" />
<h2>
Welcome to React
</h2>
</div>
<p
className="App-intro">
To get started, edit
<code>
src/App.js
and save to reload.
</p>
</div>
`;
You can see that it's basically just an HTML rendering of the component. Every snapshot comparison (a call expect(...).toEqualSnapshot()) will create a new entry in this snapshot file with a unique name.
expect(...).toEqualSnapshot():
diff
The lines colored green (with the -.
Now, let's say we wanted to make the header smaller. Change the h2 tags to h3. The test will fail.
h2
h3
Here's a great feature of Jest: all you need to do is hit the u key to replace the incorrect snapshots with the latest ones! Try it now. Hit u. The tests will re-run and pass this time.
u
Now, let's create a new component and use snapshot tests to verify it works. It'll be a simple counter component that doesn't allow negative numbers.
Create a new file src/PositiveCounter.js, and paste in this code:
import React, { Component } from 'react';
export default class PositiveCounter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
increment = () => {
this.setState({
count: this.state.count + 1
});
}
decrement = () => {
this.setState({
count: Math.max(0, this.state.count - 1)
});
}
render() {
return (
<span>
Value: {this.state.count}
<button className="decrement"
onClick={this.decrement}>−</button>
<button className="increment"
onClick={this.increment}>+</button>
</span>
);
}
}
If we were writing normal unit tests, now would be a good time to write some. Or, if we were doing test-driven development, we might've already written a few tests. Those are still valid approaches that can be combined with snapshot testing, but snapshot tests serve a different purpose.
Before we write a snapshot test, we should manually verify that the component works as expected.
Open up src/App.js and import the new PositiveCounter component at the top:
PositiveCounter
import PositiveCounter from './PositiveCounter';
Then, put it inside the render method somewhere:
render.
npm start
App
Try out the PositiveCounter component. You should be able to click "+" a few times, then "-" a few times, but the number should never go below 0.();
});
Jest will again report that it wrote 1 snapshot, and the test will pass. Inspecting the snapshot file will verify that it rendered a "2" for this test. Remember, though: we already verified that the component works correctly. All we're doing with this test is making sure it doesn't stop working, due to changes in child components, a refactoring, or some other change.
Here, we used the component.getInstance() function to get an instance of the PositiveCounter class, then called its increment method.
component.getInstance()
increment.
onClick.
In this article, we covered how to get set up with snapshot testing and write a few tests.
Snapshot tests are a quick and easy way to make sure your components continue to work through refactoring and other changes. It doesn't replace other styles of testing, such as using Enzyme or ReactTestUtils, but it augments them with a nice first-pass approach. With snapshot tests, you have even fewer excuses to write tests! Try them out in your own project.
Snapshot Testing React with Jest was originally published by Dave Ceddia at Dave Ceddia on April 04, 2017.
CodeProject
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) | https://www.codeproject.com/Articles/1180478/Snapshot-Testing-React-with-Jest | CC-MAIN-2019-04 | refinedweb | 964 | 67.65 |
Support for many storages (S3, MogileFS, etc) in Django.
This library has been designated as the official successor of django-storages (as of February 2016). Please update your requirements files to point to django-storages.
All development now happens at
django-storages
Installation
Installing from PyPI is as easy as doing:
pip install django-storages-redux was (is) a project to provide a variety of storage backends in a single library. This is its maintained, Python 3 compatible fork. The reasons for the fork are given in the next section.
At the moment the only tested Python 3 compatible backend is the S3 Boto one but some of them should work without issue (hashpath, symlink, overwrite).
This library is compatible with Django >= 1.7. It should also works with 1.6.2+ but no guarantees are made.
Why Fork?
The BitBucket repo of the original django-storages has seen no commit applied since March 2014 (it is currently December 2014) and no PyPi release since March 2013 despite a wealth of bugfixes that were applied in that year-long gap. There is plenty of community support for the django-storages project (especially the S3BotoStorage piece) and I have a personal need for a Python3 compatible version.
All of the Python3 compatible forks that currently exist (and there are a few) are lacking in some way. This can be anything from the fact that they don’t release to PyPi, have no ongoing testing, didn’t apply many important bugfixes that have occurred on the Bitbucket repo since forking or don’t support older versions of Python and Django (vital to finding bugs and keeping a large community). For this fork I’ve done the small bit of work necessary to get a tox + travis ci matrix going for all of the supported Python + Django versions. In many cases the various forks are lacking in a few of the above ways..3.3 (2017-06-27)
- Show a warning indicating the new namespace and update the README to point at the new package. (‘’)
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/django-storages-redux/ | CC-MAIN-2017-34 | refinedweb | 363 | 61.56 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.